Jump to content

Search the Community

Showing results for tags 'sql'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • Welcome to PHP Freaks
    • Announcements
    • Introductions
  • PHP Coding
    • PHP Coding Help
    • Regex Help
    • Third Party Scripts
    • FAQ/Code Snippet Repository
  • SQL / Database
    • MySQL Help
    • PostgreSQL
    • Microsoft SQL - MSSQL
    • Other RDBMS and SQL dialects
  • Client Side
    • HTML Help
    • CSS Help
    • Javascript Help
    • Other
  • Applications and Frameworks
    • Applications
    • Frameworks
    • Other Libraries
  • Web Server Administration
    • PHP Installation and Configuration
    • Linux
    • Apache HTTP Server
    • Microsoft IIS
    • Other Web Server Software
  • Other
    • Application Design
    • Other Programming Languages
    • Editor Help (PhpStorm, VS Code, etc)
    • Website Critique
    • Beta Test Your Stuff!
  • Freelance, Contracts, Employment, etc.
    • Services Offered
    • Job Offerings
  • General Discussion
    • PHPFreaks.com Website Feedback
    • Miscellaneous

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


AIM


MSN


Website URL


ICQ


Yahoo


Jabber


Skype


Location


Interests


Age


Donation Link

  1. Hey guys I am struggling here. I am making an recipe website and right now attempting to create an search engine, to search the database for recipes. BUT the search form has form filters the user can edit such as one dropdown menu with preptime, another with what type of meal type, another like what type of cooking method etc etc. So how would the php if statements, query look like, I am not very experienced in sql so that is an main reason I am having such an struggle. Thanks
  2. Hello guys, am new to this forum. I have a question that i'd like some help with, this is part of my dissertation project. So i'm creating a system that will gather hardware parts from the database manually (I have 7 hardware parts for each component which is cpu,gpu,psu,motherboard,ram and case) for each and the user will input the price tag in the listbox ($300-$450) for example and the system will display hardware parts from the database within that price range. How can I link the listbox with the database? And how can I make the total price from hardware parts display depending on what the user pressed? Thanks
  3. Hi all. I have two tables where the username is what they have in common. i want to perform a join for both tables but i'm having problems with mysql joins. //to get the desire result individually i did //table one $stmt = $pdo->query("SELECT * FROM tableone WHERE username = '$_GET[id]'"); $row = $stmt->fetch(PDO::FETCH_ASSOC); $credit_score = $row['credit_score']; $acct_num = $row['acct_num']; $acct_name = ucwords($row['surname']) ." ". ucwords($row['firstname']); $username = $row['username']; if($credit_score ==3){ $bill_limits = 2000; }elseif($credit_score ==2){ $bill_limits = 1000; }elseif($credit_score ==1){ $bill_limits = 500; } //table two $stmt=$pdo->query("SELECT SUM(amt) as bill FROM tabletwo WHERE username = '$_GET[id]' AND relationship = 'PARENT'"); $row = $stmt->fetch(PDO::FETCH_ASSOC); $bill = $row['bill']; $service_charge_for_limits = '0.05' * $bill; $tax_rate_for_limits = '0.13' * $service_charge_for_limits; $bill_sum = $tax_rate_for_limits + $service_charge_for_limits + $bill; Approved Bill Limits = $<?php echo number_format($bill_limits,2); ?> <br> Bill Limits Used = $<?php echo number_format($bill_sum,2); ?> <br> <?php $available_limits = $bill_limits - $bill_sum; ?> Bill Limits Available = $<?php echo number_format($available_limits,2); ?> The above gives me the correct result, but now i have another page where i want to all the clients and their corresponding available limits, used limits and approve limits form table two and other information from table one On the page i have $stmt = $pdo->prepare("SELECT * FROM tableone WHERE status = 'COMPLETED' ORDER BY id DESC LIMIT $start, $limit"); $stmt->execute(); $num_rows = $stmt->rowCount(); echo "<table width='100%' class='table-responsive table-hover table-condensed table-striped'>"; echo "<tr> <th bgcolor='#444444' align='center'><font color='#fff'>Account Number</th> <th bgcolor='#444444' align='center'><font color='#fff'>Subscriber's Name</font></th> <th bgcolor='#444444' align='center'><font color='#fff'>Username</font></th> <th bgcolor='#444444' align='center'><font color='#fff'>Limits ($)</font></th> <th bgcolor='#444444' align='center'><font color='#fff'>View Profile</font></th> <th bgcolor='#444444' align='center'><font color='#fff'>Delete Account</font></th> </tr>"; // keeps getting the next row until there are no more to get while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { // Print out the contents of each row into a table echo "<tr><td>"; echo $row['acct_num']; echo "</td><td>"; echo ucwords($row['surname']." ". $row['firstname']); echo "</td><td>"; echo $row['username']; echo "</td><td>"; $credit_score = $row['credit_score']; if($credit_score ==3){ $bill_limits = 2000; }elseif($credit_score ==2){ $bill_limits = 1000; }elseif($credit_score ==1){ $bill_limits = 500; } echo number_format($bill_limits, 2); echo "</td><td>"; echo "<a href='view-client-profile.php?id={$row['username']}'>view more</a>"; echo "</td><td>"; echo "<a href='delete-account.php?id={$row['username']}'>Delete Account</a>"; echo "</td></tr>"; //echo "</td><td>"; //echo "<a href='settle.php?id={$row['acct_num']}'>Points</a>"; } echo "</table>"; How ca i join tableone and tabletwo (plus sum)
  4. Hey guys, I am not sure how to phrase this WHERE statement. I currently have this: WHERE approved = "1" AND item_gender="1" OR item_gender="3" It seems to be omitting the 'approved' part. What I require is that approved=1 must be adhered to regardless, but item_gender can be equal to 1 or 3. Any ideas what I am doing wrong? Thanks!
  5. Hi I'm currently having a problem with concatenation. My fields is as follow Leerder ID - Van - Eerste Voornaam - Datum 120 - Botha - Peter - 15/02/2015 120 - Botha - Peter - 16/02/2015 121 - Jacobs - John - 17/02/2015 I want it to show as Leerder ID - Van - Eerste Voornaam - Datum 120 - Botha - Peter - 15/02/2015 & 16/02/2015 121 - Jacobs - John - 17/02/2015 My current SQL code is as follow SELECT [Leerder Afwesigheid].[Leerder ID], Students.Van, Students.[Eerste Voornaam], Count([Leerder Afwesigheid].Datum) AS CountOfDatum FROM Students RIGHT JOIN [Leerder Afwesigheid] ON Students.ID = [Leerder Afwesigheid].[Leerder ID] GROUP BY [Leerder Afwesigheid].[Leerder ID], Students.Van, Students.[Eerste Voornaam] HAVING (((Count([Leerder Afwesigheid].Datum))>=5)); How can I change it to add another field Datums Afwesig with the concatenated info?
  6. I am trying to create a "login" webpage. The PHP codes for the login (login100.php) are called by another file (index100.php). Whenever I run index100.php on XAMPP, I get two errors: Warning: mysqli_error() expects exactly 1 parameter, 0 given in C:\xampp\htdocs\login100.php on line 24 Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in C:\xampp\htdocs\login100.php on line 26 My codes for index.php are: <?php include('login100.php'); // Includes Login Script if(isset($_SESSION['login_user'])){ header("location: profile100.php"); } ?> <!DOCTYPE html> <html> <head> <title>Login Form in PHP with Session</title> <link href="style100.css" rel="stylesheet" type="text/css"> </head> <body> <div id="main"> <h1>PHP Login Session Example</h1> <div id="login"> <h2>Login Form</h2> <form action="" method="post"> <label>UserName :</label> <input id="name" name="username" placeholder="username" type="text"> <label>Password :</label> <input id="password" name="password" placeholder="**********" type="password"> <input name="submit" type="submit" value=" Login "> <span><?php echo $error; ?></span> </form> </div> </div> </body> </html> My codes for login.php are: <?php session_start(); // Starting Session $error=''; // Variable To Store Error Message if (isset($_POST['submit'])) { if (empty($_POST['username']) || empty($_POST['password'])) { $error = "Username or Password is invalid"; } else { // Define $username and $password $username=$_POST['username']; $password=$_POST['password']; // Establishing Connection with Server by passing server_name, user_id and password as a parameter $connection = mysqli_connect("localhost", "root", "", "Company"); // To protect MySQL injection for Security purpose $username = stripslashes($username); $password = stripslashes($password); $username = mysqli_real_escape_string($connection, $username); $password = mysqli_real_escape_string($connection, $password); // SQL query to fetch information of registerd users and finds user match. $sql = "SELECT * FROM login where password='$password' AND username='$username'"; $query = mysqli_query($connection, $sql); if (false === $query) { echo mysqli_error(); } $rows = mysqli_num_rows($query); if ($rows == 1) { $_SESSION['login_user']=$username; // Initializing Session header("location: profile100.php"); // Redirecting To Other Page } else { $error = "Username or Password is invalid"; } mysqli_close($connection); // Closing Connection } } ?> I have worked on this for the past FIVE days and I cannot resolve this issue. All I want is a code which fetches a user's username and password from the database, and no such username or password exist, a message saying "invalid password" is generated. For some reason, I'm getting the two error messages above. Can someone help?
  7. hey guys, HOpe you can help me. I need a code about "Lock out after serveral attemps", and "Change password after first login"
  8. I have a php page which is ran after a form is posted from the previous page. I am having trouble getting the SQL strings to work. When the page is ran online there is no WSOD or error message but the tables in my database are not being updated. Any help with this would be greatly appreciated. payment.php
  9. If i check more than one checkbox. I dont get any value from database. HTML <form method="post"> <input type="checkbox" name="receiver[]" value="cheater">CHEATER <input type="checkbox" name="receiver[]" value="un-verified">UN-VERIFIED <input type="checkbox" name="receiver[]" value="inactive">INACTIVE <input type="checkbox" name="receiver[]" value="active">ACTIVE <input type="submit" name="submit" value="ADD"> </form> PHP $errors = array(); $success = NULL; $error = NULL; $var['receiver'] = isset($_POST['receiver']) ? $_POST['receiver'] : NULL; ................. if(!empty($_POST['submit'])){ // FORM VALIDATION // } if(!empty($_POST['submit']) and empty($errors)){ $status = array_map('strval', $var['receiver']) + array(0); $statusSql = implode(',', $status); $query = 'SELECT email FROM users WHERE status IN("'.$statusSql.'")'; $select = $db->prepare($query); $select->execute(); $arrayData = array(); while($row = $select->fetch(PDO::FETCH_ASSOC)){ $arrayData[] = $row['email']; } $errors[] = implode(',', $arrayData); } require_once 'includes/antiCsrf/index.php'; $csrf = new antiCsrf(); $smarty->assign('success', $success); $smarty->assign('error', $error); $smarty->assign('errors', $errors); $smarty->assign('csrfKey', $csrf->csrfKey()); $smarty->assign('csrfToken', $csrf->csrfToken()); $smarty->assign('var', $var); .................
  10. i have a form for my admin to update the products and their deails on my site. but i have decided to add stock and supplier tables to the database. so i have a products table, stock and supplier. each have an id. in my admin form, id like the admin to submit once to multiple tables... php code that i need to improve <?php // Parse the form data and add inventory item to the system if (isset($_POST['product_name'])) { $product_name = $_POST['product_name']; $price = $_POST['price']; $category = $_POST['category']; $stock = $_POST['stock']; $details = $_POST['details']; $rating =$_POST['rating']; $letter = $_POST['letter']; $supplier = $_POST['supplier']; // See if that product name is an identical match to another product in the system $sql = mysqli_query($con, "SELECT id FROM products WHERE product_name='$product_name' LIMIT 1"); $productMatch = mysqli_num_rows($sql); // count the output amount //if product match is greater than 0 if ($productMatch > 0) { echo 'Sorry you tried to place a duplicate "Product Name" into the system, <a href="inventory_list.php">click here</a>'; exit(); } // Add this product into the database now by sql query $sql = mysqli_query($con, "INSERT INTO products (product_name, price, details, category, stock, letter, supplier, rating, date_added) VALUES('$product_name','$price','$details','$category', '$stock' ,'$letter',' $supplier' , '$rating' now())") or die (mysqli_error()); $pid = mysqli_insert_id($con); // Place image in the folder $newname = "$pid.jpg"; move_uploaded_file($_FILES['fileField']['tmp_name'], "../inventory_images/$newname"); //_FILES is a global var header("location: inventory_list.php"); //auto refresh, and it wont try to re add the item exit();//not necessary but its always safe to exit } ?> html form <form action="inventory_list.php" enctype="multipart/form-data" name="myForm" id="myForm" method="post"> <table width="95%" border="0" align="center" cellpadding="5" cellspacing="0" summary="this is where the admin will insert new items"> <caption><div id="title"><a id="add_new_item"></a>Add New Inventory Item</div> </caption> <tr > <th width="30%" scope="col" align="left">Product Image</th> <th width="70%"><label class="desc"> <input type="file" name="fileField" id="fileField" autofocus required /> </label></td> </tr> <tr > <th width="30%" scope="col" align="left">Product Name</th> <th width="70%" scope="col" align="left"> <label class="desc"> <input name="product_name" type="text" id="product_name" size="64" autofocus required /> </label></th> </tr> <tr> <th width="30%" scope="row" align="left">Letter</th> <td width="70%"> <label class="desc"> <input name="letter" type="text" id="letter" autofocus required /> </label></td> </tr> <tr> <th width="30%" scope="row" align="left">Product Price</th> <td width="70%"> <label class="desc"> <input name="price" type="text" id="price" autofocus required /> </label></td> </tr> <tr> <th width="30%" scope="row"align="left">Category</th> <td width="70%"><label class="desc"> <select name="category" id="category"> <option value="Fruits">Fruits</option> <option value="Vegetables">Vegetables</option> <option value="Indoor Plants">Indoor Plants</option> <option value="Outdoor Plants">Outdoor Plants</option> </select> </label></td> </tr> <tr> <th width="30%" scope="row" align="left">Suppliers</th> <td width="70%"> <label class="desc"> <select name="supplier" id="supplier"> <option value="Kenny's Organic Supplies">Kenny's Organic Supplies</option> <option value="Mom's Garden">Mom's Garden</option> <option value="Big Brother">Big Brother</option> </select> </label></td> </tr> <tr> <th width="30%" scope="row" align="left">Stock</th> <td width="70%"> <label class="desc"> <input name="stock" type="text" id="stock" autofocus required /> </label></td> </tr> <tr> <th width="30%" scope="row"align="left">Product Details</th> <td width="70%"><label class="desc"> <textarea name="details" id="details" cols="35" rows="5" autofocus required></textarea> </label></td> </tr> <tr> <th width="30%" scope="row" align="left">Rating</th> <td width="70%"><label class="desc"> <select name="rating" id="rating" > <option value="1">1 of 3 Stars</option> <option value="2">2 of 3 Stars</option> <option value="3">3 of 3 Stars</option> </select> </label></td> </tr> <tr> <th width="30%" scope="row"> </th> <td width="70%" align="right"><label class="desc"> <input type="submit" name="button" id="button" value="Add This Item Now" /> </label></td> </tr> <tr> <th width="30%" scope="row"> </th> <td width="70%"> </td> </tr> </table> </form>
  11. Hi, I'm quite new to OOP PHP and i'm trying to make a dynamic insert function , i've followed an example on Stackoverflow to do so since its my first try at making something dynamic.http://stackoverflow.com/a/13333344/3559635 It works but im still quite confused about the two foreach loops , and if possible could someone explain that part to me please and or is there an easier more clean way to do this for a new guy like me? Im sending my POST values from the index.php <?php include("Database.php"); $db = new Database(); var_dump($db); $table = "users"; $whitelist = array('username', 'password'); $data = array_intersect_key($_POST, array_flip($whitelist)); if(isset($_POST['username']) AND ($_POST['password'])) { $db->postTesting($data, $table); } else { echo "Please fill in everything!"; } Database.php <?php class Database { private $connection; private $typedb = "mysql"; private $host = "127.0.0.1"; private $dbname = "oopphp"; private $username = "root"; private $password = ""; public function __construct() { try{ $this->connection = new PDO($this->typedb. ":host=".$this->host. ";dbname=".$this->dbname, $this->username, $this->password); $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return $this->connection; } catch(PDOException $e) { throw new Exception("Connection failed: ".$e->getMessage()); } } public function postTesting($data, $table) { try{ //var_dump($table, $data); $columns = ""; $holders = ""; foreach ($data as $column => $value) { //var_dump($column); //var_dump($value); $columns .= ($columns == "") ? "" : ", "; $columns .= $column; $holders .= ($holders == "") ? "" : ", "; $holders .= ":$column"; //var_dump($columns); //var_dump($holders); } $sql = "INSERT INTO $table ($columns) VALUES ($holders)"; //return $sql; $stmt = $this->connection->prepare($sql); //var_dump($stmt); foreach ($data as $placeholder => $value) { $stmt->bindValue(":$placeholder", $value); //var_dump($stmt); //var_dump($placeholder); //var_dump($value); } //var_dump($sql); //var_dump($stmt); $stmt->execute(); } catch(PDOException $rError) { throw new Exception("Registering Failed: ".$rError->getMessage()); } } } Im seriously confused about this part. foreach ($data as $column => $value) { //var_dump($column); //var_dump($value); $columns .= ($columns == "") ? "" : ", "; $columns .= $column; $holders .= ($holders == "") ? "" : ", "; $holders .= ":$column"; //var_dump($columns); //var_dump($holders); } Thanks in advance for the help
  12. So I have been slowly working on a custom forum. I have recently been trying to implement an achievement system. For the most part achievements would work based on the users amount of posts amount of characters in a post amount of replies on a post time past from the users join date. I was hoping to find out how I could put an entry into a database field based on the above. Any help would be greatly appreciated
  13. Hey guys! im currently learning javascript, PHP and SQL. I have a pretty solid understanding of HTML and CSS. I want to make a site similar to facebook (a good facebook). this is going to be a big project and i plan on moving to a bigger server system in a year or so to keep up with demands. Heres how the site will function: 1. Basic registration/splash page. I understand that the finished form is sent to a php file on the server side, correct? (ill change my server name files of course) 2. after the registration page, while the user is logged in with their new account, there are 3 pages after that that explain what the website is all about and how to use it. the last page allows the user to setup their profile information, ask friends to join, and asks what type of things they like. After the last page, it sends the user to their main control panel, where social media feed can be seen, friends and online chats, news, advertisements, links, pages and groups (think facebook and linkedin) 3. the user will have the ability to look at their profile (not the control panel), and of course switch back to their control panel. social media, friends, groups and ads will also be on their individual profile page as well. 4. i want the site to have two views: a standard view and an enhanced view. the enhanced view will reposition divs and all that stuff so they can see a background image (either stock or one they uploaded) this image will eventually change to an animated image of a 3d environment. 5. the site is going to be heavily social media based. This means social media feeds, image uploading, a structured comment system, a friend system, search functions and targeted advertising. This is obviously a lot to ask, but since their is so much to learn related to PHP and SQL, can someone point me to the right tutorials on how to get these things done? I am currently learning javascript, PHP and SQL on lynda.com. Expect me to be on this forum a lot and asking a lot of questions. Thanks for any help.
  14. I'm trying to display the null values only, where am I going wrong? SELECT IFNULL(trans, 0) AS 'Transactions', customer.cID AS 'Customer ID', customer.surname AS 'Surname' FROM customer LEFT JOIN account ON (account.cID = customer.cID) WHERE IFNULL(trans, 0);
  15. Im struggling with how to filter items that have multiple categorises say if i wanted to search for a shoe that is good for walking and hiking in my database? Shoe_id Shoe name color_id type_id colors color_id color type type_id type My problem is what do i do in a situations like this? say a shoe is good for walking and running? aka type 1 and 2 shoe id 1 shoe name nike color id 1 type id 1 and 2
  16. Hi guys so for my website I want to add a feature where a user can upload a zipped folder and send that folder to another user through my Private message system, so I am wondering how this would work, would I need to upload the folder to my database, upload it to a separate folder and use some php code to display a download link to download it?
  17. I'm attempting to create a SQL command that can sort through a concatenated string in my database it is listed at Colors: blue,red,green,yellow is SELECT * FROM `shoes` WHERE CONCAT(',',color,',') LIKE '%,blue,red%' How do I filter the data where it can come up with shoes that are available in red or blue or red and blue and so on? I could use where find_in_set('blue', colors) > 0 and find_in_set('red', colors) > 0 Is there a better way of doing this? Shoe name: shoe A Shoe size: 7,8,9 Shoe color: black , brown, grey For example could have a shoe available in black , size 8 or 9 or 8 and 9.
  18. I'm making statistic for 5 tables. I have made the example with one client data. loan: payment_schedule: payment_schedule_row payment_schedule_cover: payment_schedlue_delay: And the query is: SELECT period, loan_sum, covers, delay FROM (SELECT MAX(EXTRACT(YEAR_MONTH FROM psc.date)) AS period, (SELECT SUM(psr2.payment) FROM payment_schedule_row AS psr2 WHERE psr.payment_schedule_id = psr2.payment_schedule_id) AS loan_sum, (SELECT SUM(psc2.sum) FROM payment_schedule_cover AS psc2 WHERE psc.payment_schedule_id = psc2.payment_schedule_id) AS covers, (SELECT SUM(psd2.delay) FROM payment_schedule_delay AS psd2 WHERE psr.id = psd2.payment_schedule_row_id) AS delay FROM loan INNER JOIN payment_schedule AS ps ON ps.loan_id = loan.id INNER JOIN payment_schedule_row AS psr ON psr.payment_schedule_id = ps.id INNER JOIN payment_schedule_cover AS psc ON psc.payment_schedule_id = ps.id WHERE loan.status = 'payed' GROUP BY ps.id) AS sum_by_id GROUP BY period Sqlfiddle link: http://sqlfiddle.com/#!2/21585/2/0 Result for the query: period | loan_sum | covers | delay --------------------------------------- 201407 | 384 | 422 | 0.07 Everything is right except the delay. It should be 0.11 (0.07 + 0.03 + 0.01) So I have been trying to find the error from the query for days now. Maybe someone can tell me what I'm doing wrong.
  19. I have 2 queries that I want to join together to make one row This queries returns all rows from both tables which is what i want SELECT table_A.*, table_B.* FROM table_A INNER JOIN table_B ON table_A.code = table_B.code and this is the output table_A.id | table_A.code | table_B.id | table_B.code | table_B.complete =============================================================================================== 1 | 123456 | 1 | 123456 | yes 2 | 654321 | 2 | 654321 | no and this is the second query SELECT table_C.*, table_D.* FROM table_C INNER JOIN table_D ON table_C.code = table_D.code INNER JOIN table_B ON table_D.code = table_B.code WHERE table_B.complete = 'yes' and again the output table_C.id | table_C.code | table_D.id | table_D.field2 | table_B.complete ======================================================================================== 1 | 123456 | 1 | 123456 | yes What I've been trying to for the last couple of days is join the 2 queries together to make one query that returns this table_A.id | table_A.code | table_B.id | table_B.code | table_B.complete | table_C.id | table_C.code | table_D.id | table_D.field2 | table_B.complete ==================================================================================================================================================================================== 1 | 123456 | 1 | 123456 | yes | 1 | 123456 | 1 | 123456 | yes 2 | 654321 | 2 | 654321 | no All i want it to do is get all rows from tables A and B and return all rows from C and D only if table_B.complete equals "yes". All tables are joined by the code column which all have the same value
  20. Hello, I don't know if this is possible. I want to make a switch between pages, lets say i have more than 100 pages and each page have a unique name.php. So what i want to do is when page equal to random-page.php SELECT * FROM `jobs` WHERE title LIKE '%news%' And for example how it should be, but i don't know what is exactly wrong here and how to fix it. $sql_q; $path=$_SERVER['PHP_SELF']; $page=basename($path); switch("$page") { case 'index.php': $sql_q = 'SELECT * FROM `jobs` WHERE `title` LIKE '%news%' LIMIT $p_num, $per_page'; break; case 'jobs.php': $sql_q = 'SELECT * FROM `jobs` WHERE `title` LIKE '%jobs%' LIMIT $p_num, $per_page'; break; case 'region.php': $sql_q = 'SELECT * FROM `jobs` WHERE `title` LIKE '%region%' LIMIT $p_num, $per_page'; break; } And here: $getquery = mysql_query("$sql_q"); Is that possible somehow ? Thanks.
  21. I am trying to create a simple forum in a MVC architecture. This is my database setup (the relevant part): Table: forum_categories `forum_categories` ( `cat_id` INT( NOT NULL AUTO_INCREMENT, `cat_title` VARCHAR(255) NOT NULL, `cat_desc` TEXT NOT NULL, PRIMARY KEY (`cat_id`), UNIQUE KEY (`cat_title`) Table: forum_topics `forum_topics` ( `topic_id` INT( NOT NULL AUTO_INCREMENT, `cat_id` INT( NOT NULL COMMENT 'foreign key with forum_categories table', `user_id` INT(11) NOT NULL COMMENT 'foreign key with users table', `topic_title` VARCHAR(255) NOT NULL, `topic_desc` TEXT NOT NULL, `topic_date` DATETIME DEFAULT NULL, PRIMARY KEY (`topic_id`), FOREIGN KEY (`cat_id`) REFERENCES forum_categories (`cat_id`) ON DELETE CASCADE ON UPDATE CASCADE Example of the functionality, I would like to achieve: Category 1 has cat_id = 1 Category 2 has cat_id = 2 Topic 1 has cat_id = 1 Topic 2 has cat_id = 2 Now when category 1 is selected I just want topic 1 to show. If category2 is selected I just want topic 2 to show. This prepared SQL statement achieves that: PREPARE stmnt FROM 'SELECT * FROM forum_categories fc JOIN forum_topics ft ON fc.cat_id = ft.cat_id WHERE fc.cat_id = ? ORDER BY ft.topic_date DESC'; SET @a = 1; EXECUTE stmnt USING @a; My Problem: I would like to move this functionality into my PHP MVC structure. Here is my attempt, which does not work (it shows all topics in all categories). Controller /** * Show all the topics in the chosen category */ public function showForumTopics() { $topic_model = $this->loadModel('Forum'); $this->view->forum_topics = $topic_model->getForumTopics(); $this->view->render('forum/viewTopics'); } Model /** * Gets an array that contains all the forum topics in the database. * Each array element is an object, containing a specific topic's data. * @return array All the forum topics */ public function getForumTopics($cat_id) { $sql = 'SELECT * FROM forum_categories fc JOIN forum_topics ft ON fc.cat_id = ft.cat_id WHERE fc.cat_id = :cat_id ORDER BY ft.topic_date DESC'; $query = $this->db->prepare($sql); $query->execute(array(':cat_id' => $cat_id)); return $query->fetchAll(); } View if ($this->forum_topics) { foreach($this->forum_topics as $key => $value) { echo '<p><strong>Title:</strong>' . $value->topic_title . '</p>'; echo '<p><strong>Description:</strong> ' . $value->topic_desc . '</p>'; echo '<p><strong>Author:</strong> ' . $value->topic_author . '</p>'; echo '<p><strong>Date:</strong> ' . $value->topic_date . '</p>'; } } else { echo 'No forum topics.'; } Help would be highly appreciated! Thank you!!
  22. Hi there, I want to pass a input variable from login_success.php which will be sent to sqlprocess.php as the variable 'SQLinput'; sqlprocess.php $link = mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); $query = $_REQUEST['SQLinput']; //You don't need a ; like you do in SQL $result = mysql_query($query); $numfields = mysql_num_fields($result); login_sucess.php <form action="" method="post" <label> <span>SQL Input :</span> <input type ="text" id="message" name="SQLinput" placeholder="Input SQL"></textarea> </label> <label> <span>SQL Output :</span> <output id="text" id="SQLoutput" ></input> <script type="text/javascript" charset="utf-8"> // handles the click event for link 1, sends the query function getOutput() { getRequest( 'sqlprocess.php', // URL for the PHP file drawOutput, // handle successful request drawError // handle error ); return false; } // handles drawing an error message function drawError () { var container = document.getElementById('output'); container.innerHTML = 'Bummer: there was an error!'; } // handles the response, adds the html function drawOutput(responseText) { var container = document.getElementById('output'); container.innerHTML = responseText; } // helper function for cross-browser request object function getRequest(url, success, error) { var req = false; try{ // most browsers req = new XMLHttpRequest(); } catch (e){ // IE try{ req = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { // try an older version try{ req = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e){ return false; } } } if (!req) return false; if (typeof success != 'function') success = function () {}; if (typeof error!= 'function') error = function () {}; req.onreadystatechange = function(){ if(req .readyState == 4){ return req.status === 200 ? success(req.responseText) : error(req.status) ; } } req.open("GET", url, true); req.send(null); return req; } </script> <a href="#" onclick="return getOutput();"><button type="submit" id="search_btn" value="Submit">Submit</button> </a> <div id="output">waiting for action</div> Prior to the JS code - I was able to peform this action - however the JS code enables me to post the query onto the same page. I would like essentially like to query the database through an input box and output the same result on the same page. Thanks!
  23. Hi there, This may not be the correct space to post this - but I'm very new to all this. I've created a page that will run a php script to output a query. I would then like to send that same query via email - however from a design perspective I don't think the correct process is to click 'submit' to view the query and then 'submit' to send the result via email? Can you please advise on some design solutions regarding this issue? Thanks!
  24. I am just new to relational algebra probably a pre-step before learning SQL queries. Can you help me make the expressions of relational algebra expression for each of the following queries. This is the table contained inside a bus driver database. driver ( driver_id, driver_name, age, rating ); bus ( bus_id, bus_name, color); reserves ( driver_id, bus_id, date); a. Find the names of drivers who have reserved at least three busses. b. Find the names of drivers who have reserved all busses. c. Find the names of drivers who have reserved all busses called Shuttle. d. Find the IDs of drivers whose rating is better than some driver called Paul. I would be grateful if somebody can help me here.
  25. (I'm putting this in PHP since it's not a question specific to MySQL or other DB stuff.) I have a page that uses the GET id to find a product. GET variables are sanitized, and the SQL string is escaped even though it's expecting a number only. So the code seems safe to me. I'm getting some error_log results that appear to be hack attempts: SELECT p.*, t.id as blah FROM some_table p left outer join some_other_table t on p.id = t.product_id WHERE p.id = 139\' and benchmark(20000000,sha1(1))-- Should I be worried about something like this? Anything more (or less) that I should be doing?
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.