PHP - What To Do ??? Prepared Sql Stament And Dynamic Query Becoming Impossible.
I have a dilemma. Maybe it's an easy fix but i just cant see the solution.
My code already works without preparing the sql. The problem is preparing the sql and building the dynamic query. In a nut shell, I have a form with 10 different fields. And depending on which field gets data, I build my query so that it only works on the fields the user typed something into. let me summarize .... I have a basic query that starts off like this $updatestring = ""; $query = "UPDATE table a SET "; if field1 set then $updatestring = $updatestring . " field1 = field1val " if field2 set then $updatestring = $updatestring . " field2 = field1val " if field3 set then $updatestring = $updatestring . " field3 = field1val " if field4 set then $updatestring = $updatestring . " field4 = field1val " and so on .... Finally $query = $query . $updatestring which can end up looking like: UPDATE table a SET field1 = field1val, field3 = field1val .... depending on which fields were set. I take care of commas and so on. Like I said this works. However, to prepare the statement really complicates things because if it looks like this: UPDATE table a SET field1 = ? , field3 = ? how do I know which variable to bind to the param out of the 10 possible fields ? How do I build the string types and place them in the right order? Do you see my dilemma? mysqli_stmt_bind_param($stmt, 'ii', $field1val, $field3val); Any help would be appreciated. I will also post this in the mysql section. Thanks, JT then Similar Tutorialsclass getjson { function query_db ($mysqli, $search_string){ $query = "SELECT name, location, address FROM csv_table WHERE address LIKE CONCAT('%',?,'%') OR name LIKE CONCAT('%',?,'%') OR location LIKE CONCAT('%',?,'%') LIMIT 0,5"; $stmt = $mysqli->prepare($query); $stmt->bind_param("sss", $search_string, $search_string, $search_string); $stmt->execute(); // $stmt->bind_result($name, $location, $address); // not necessary for code to work $result = $stmt->get_result(); while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){ foreach ($row as $value) { $data[] = array( 'label' => $value .', '. $value.' '. $value , 'value' => $value ); } } return $data; } } $results = new getjson; $results = $results->query_db($mysqli, $search_string); print_r($results); echo count($results); I have the following code. It works, but I cannot get array notation working correctly. For instance, I would like to access $row['address'] to input into my array in the foreach statement. But I can't seem to get it to work after a couple hours. So any ideas appreciated. Thanks, Mark I'm trying to use a prepared statement inside a function and it's giving me some trouble. I have an RPG game I'm working on an want a function to include on pages that tells a user to collect their egg from the professor if they haven't already received it yet. When I try to call the function on the page these are the errors I get:
Notice: Undefined variable: link in /home/evoarena/public_html/Dev/functions.php on line 23 $link is defined in a db config file and on the page I'm trying to call the function I have the files required like this so I'm wondering why it still thinks link is an undefined variable require "config.php"; require "functions.php"; Function Code: function egg_received () { if (isset($_SESSION['username'])) { $username = $_SESSION['username']; $query = "SELECT egg_received FROM users WHERE username=?"; if ($stmt = $link->prepare($query)) { $stmt->bind_param("s", $username); $stmt->execute(); $result = $stmt->get_result(); $egg = $result->fetch_array(); if ($egg['egg_received'] == '0') { echo "<div class='alert alert-primary' role='alert'> Oh well hello there! It appears the professor is looking for you today!<br><a href='../world/professor.php'>Visit the Professor</a> </div>"; require "footer.php"; exit; } } else { $error = $link->errno . ' ' . $link->error; echo $error; } } }
So I am trying to learn PDO and after some reading, I have found that you cannot use exec with select statements, however, if you are using a prepared statement, you can. However, PDO has a function just selecting the data, using PDO::query. So my question is, how do I know when is the proper used to use PDO::query or the prepared statement route? I have been able to duplicate the queries using both methods and obtain the same results. Is the prepared statement needed for sanitizing the data if I am selecting from user input and PDO:query used if I am only doing a general select where I explicitely state what I am selecting for in the SQL statement? Hi ! I am trying to translate my mysqli count query that works perfectly into prepared statements. Unfortunately, after playing around and using my knowledge of PS, I have come up with this script which fails to execute and returns a http 500 error. I may have missed something very silly, I require some guidance on fixing the error.
<?php $conn = mysqli_connect("xxxx", "xxxx", "xxxx", "xxx"); $sel_query = "SELECT S1, B1 COUNT(IF(S1 = ?, 1, NULL)) 'Accepted', COUNT(IF(S1 = ?, 1, NULL)) 'Rejected', COUNT(IF(S1 = ?, 1, NULL)) 'Under_Review' FROM Enrol"; $stmt = $conn->prepare($sel_query); $Accepted="Accepted"; $Rejected="Rejected"; $Under_Review="Under Review"; $stmt->bind_param("sss",$Accepted, $Rejected, $Under_Review); $stmt->execute(); $result = $stmt->get_result(); // get the mysqli result if($result->num_rows === 0) exit('No records found!'); while($row = $result->fetch_assoc()) { ?> <tr> <td><?php echo $row["Accepted"]; ?></td> <td><?php echo $row["Rejected"]; ?></td> <td><?php echo $row["Under_Review"]; ?></td> </tr> </table>
Edited June 24, 2020 by PythonHelp Hello, i have the following statement in my code if($slide[active] == "0"){ echo("<div style='background: url(/img/new.png) no-repeat; padding-left: 23px; font-weight: bold;'>$slide[title]. $slide[fname] $slide[lname]</div>"); }else{ echo("$slide[title]. $slide[fname] $slide[lname]"); } ?><?php this makes any database entry thats has field 'active' set to '0' appear in bold and with a 'NEW!' image appear to the side of it. How could i alter this so that it would also make these changes (bold and 'new' image) to any entry that also had field named 'payeddeposit' set to 'no'? many thanks, gavin Hi, Can anyone point me in the right direction please? I want to have a drop down box which when a user clicks on a category the results on the page have changed to show only the data which is relative to the category chosen by the user. I also need a way so that when they click view all they are able to see all the results again. Not really sure what to look for or even how hard this might be. Lee So I'm trying to put a user selected date into a mysql query, but it seems like no matter what I do I get 0 results even though I already know there's quite a few. The way I have it now 'echo $query;' puts out the expected results, but I'm guessing it's because I'm trying to match a date to a string. I tried strtotime but I'm not sure if I was doing it right.. I also tried sprintf() just in case, but that doesn't seem to have a date feature. The variable $realdate is just to show how I was attempting to use strtotime, it's not an actualy part of the script at this time... $searchdate = $_GET['searchdate']; //$realdate = strtotime($searchdate) //connects to db dbconnect(); $query="SELECT `name`, `date`, SUM(`amount`) as `total_money`, SUM(`bricks`) as `total_bricks` FROM Aces_Donations WHERE `date`= $searchdate ORDER BY `total_money`"; echo $query; $result=mysql_query($query); //Opens the table echo "<table border = '3' width = 40% bgcolor=#A85045><caption><center>Rankings - ".$searchdate.'</center></caption>'; //Loop to run until eof while($row = mysql_fetch_array($result)){ echo "<tr><td>".$rank."</td> <td>".$row['name']. "</td><td>". $row['total_money']."</td><td>".$row['total_bricks'].'</td></tr>'; $rank++; } echo '</table>'; The page that I'm currently working on has a form which allows, through a series of check boxes and text entry fields, a dynamic mysql query to be created. The php code constructs the query based on which fields the user updated in order to find a specific user in the database. Everything was working fine until I started to only display part of the result set. In order to display a message similar to "Displaying 12-25 of 65 results." I ran the query twice. Once to get the total number of results, and once to only get the specified set. The code for the section producing the error is included below. The elseif statement works as desired, as does the initial query of the if statement. if (isset($sql) && $sql !=""){ $sql = "SELECT DISTINCT users.StudentID FROM users lEFT JOIN events ON users.StudentID=events.StudentID WHERE" . $sql; $stmt = $mysqli->prepare($sql); call_user_func_array(array(&$stmt, 'bind_param'), $array_of_params); $stmt->execute(); $stmt->store_result(); $total= $stmt->num_rows; $stmt->close(); $sql = "SELECT DISTINCT users.StudentID,users.FirstName,users.LastName,users.Email,users.Phone,users.Texting,users.Admin,users.HDHS,users.Sex,users.Confirmation FROM users lEFT JOIN events ON users.StudentID=events.StudentID WHERE" . $sql . " ORDER BY LastName,FirstName LIMIT " . $_GET['start'] . ",12"; $stmt = $mysqli->prepare($sql); call_user_func_array(array(&$stmt, 'bind_param'), $array_of_params); $stmt->bind_result($row['StudentID'],$row['FirstName'],$row['LastName'],$row['Email'],$row['Phone'],$row['Texting'],$row['Admin'],$row['HDHS'],$row['Gender'],$row['Confirmation']); } elseif(isset($_GET['submit']) || isset($_GET['earlier']) || isset($_GET['later'])){ $stmt = $mysqli->prepare("SELECT StudentID,FirstName,LastName,Email,Phone,Texting,Admin,HDHS,Sex,Confirmation FROM users ORDER BY LastName,FirstName"); $stmt->bind_result($row['StudentID'],$row['FirstName'],$row['LastName'],$row['Email'],$row['Phone'],$row['Texting'],$row['Admin'],$row['HDHS'],$row['Gender'],$row['Confirmation']); $stmt->execute(); $stmt->store_result(); $total= $stmt->num_rows; $stmt = $mysqli->prepare("SELECT StudentID,FirstName,LastName,Email,Phone,Texting,Admin,HDHS,Sex,Confirmation FROM users ORDER BY LastName,FirstName LIMIT " . $_GET['start'] . ",12"); $stmt->bind_result($row['StudentID'],$row['FirstName'],$row['LastName'],$row['Email'],$row['Phone'],$row['Texting'],$row['Admin'],$row['HDHS'],$row['Gender'],$row['Confirmation']); $stmt->execute(); } If anyone would be willing to help me out here it would be greatly appreciated. If you need more information let me know. Thank you! Please guys, I need your help on this one. How can call the data from mysql and make the values checked on the checkboxes Have got three tables. I am retrieving data and updating two tables at once... Hi there. Im a noob to sql and php not sure if this is right place to post, Im trying to get a dynamic drop down menu to show the 1st column in my sql database the column is called cat and holds category info ie audio, internet, music ect. ( i have no idea how to do lol ) it has taken me 2 days to find and edit this the bold and underline'd bit is what im trying to change with the dropdown menu. Or thinking bout it is there a way to do it with the URL. IE.. page name.php?cat=audio ? would that be easer ? is there any security issues with doing it that way ? Code================================== $db_host = '*******'; $db_user = '******'; $db_pwd = '*****; $database = 'nbbcj_co_uk'; $table = 'penapps'; if (!mysql_connect($db_host, $db_user, $db_pwd)) die("Can't connect to database"); if (!mysql_select_db($database)) die("Can't select database"); // sending query $result = mysql_query("SELECT * FROM {$table} WHERE `cat` = 'audio' LIMIT 10 "); if (!$result) { die("Query to show fields from table failed"); } $fields_num = mysql_num_fields($result); //echo "<h1>Table: {$table}</h1>"; echo "<table border='1' width='100%'><tr>"; // printing table headers for($i=0; $i<$fields_num; $i++) { $field = mysql_fetch_field($result); //echo "<td>{$field->name}</td>"; } echo "</tr>\n"; // printing table rows while($row = mysql_fetch_row($result)) { echo "<tr>"; // $row is array... foreach( .. ) puts every element // of $row to $cell variable foreach($row as $cell) echo "<td>$cell</td>"; echo "</tr>\n"; } mysql_free_result($result); ?> code end ====================== the test page can been seen here http://www.nbbcj.co.uk/testd/1/test1.php Any more questions let me know Thanks for any help you can give, a we all have to start some ware lol thanks kaine. Hi, I had a form which contains, 8 select boxes. In those 8 select boxes, 3 of the boxes are interlinked, like, I am able to generate data in other 2 select boxes, if one box is been selected. i.e. based upon selection of one select box, and i am able to generate data in other select box. So, 3 select boxes are interlinked. And remaining 5 selects are optional, if the user selects, then we need to generate data based upon selection of the user. Here the main issue is how to grab data in the post back form, like, how to capture the number of selects boxes selected and what are those selected, and based upon that we need to generate data. Here one more important thing is that, in the report generation form(postback form), I need to show the data in a table. So , in table I had 9 columns and these would be common to whatever the selection made, but, only the requeired data would be changed based upon the selection of the remaining 5 optional boxes. Hope you got me!!!! First question: is the third line of code here even nessesary Code: [Select] $_SESSION['asked']=array(); $catagories = array("easy", "medium", "hard"); $random = $catagories[mt_rand(0, count($catagories)-1)].mt_rand(1,5); while(in_array($random, $_SESSION['asked'])) { $random = $catagories[mt_rand(0, count($catagories)-1)].mt_rand(1,5); } $_SESSION['asked'][] = $random; This then generates one of 15 options (currently), those being easy1, easy2, easy3, easy4, easy5, medium1, medium2, medium3, medium4, medium5, hard1, hard2, hard3, hard4, hard5. My second question is, can I give this generator the ability to generate hard6, hard7, hard8, hard9 and hard10, while not generating anything higher than 5 with easy and medium? This topic has been moved to mod_rewrite. http://www.phpfreaks.com/forums/index.php?topic=359577.0 I am trying to create a simple forum in a MVC architecture. I have a general dbInsert class method that accepts three arguments: table, fields, and values - the last two each as an array. I am using a PDO connection and prepared statements to sanitize everything. I am having a problem with the bindParam() function accepting the parameter ID's though... here's my code and the result I am getting, any advice? My arguments: $this->_table = "testdata"; $this->_fields = array('product_id', 'store_id', 'description', 'price', 'colors', 'sizes'); $this->_values = array("20002157", "2005", "Kids polo shirt", "12.59", "White", "Large"); My object: $_crud = new Crud(); $_makeCrud = $_crud->dbInsert($this->_table, $this->_fields, $this->_values); My class: public function dbInsert($table, $fields, $values) { $_table = $table; $_fields = implode(", ", $fields); // Create and format the list of insert values $_values = ""; // replaces values with "?" placeholders foreach ($values as $value) { $_values .= "?" . ", "; } // trims off last comma and space $_values = substr($_values, 0, -2); // checks database connection if (isset($this->_dbh)) { // Create the SQL Query $this->_sql = 'INSERT INTO ' . $_table . ' (' . $_fields . ') VALUES (' . $_values . ')'; // Build the query transaction $this->_dbh->beginTransaction(); // Build the prepared statement $this->_stmt = $this->_dbh->prepare($this->_sql); // Bind the parameters to their properties foreach ($values as $key => $val) { // starts $key at 1 $key = (int) $key + 1; $this->_stmt->bindParam($key, $val); } // Execute the query $this->_stmt->execute(); $this->_affectedRows = $this->_stmt->rowCount(); } } What my new table row should look like: Code: [Select] product_id store_id description price colors sizes ---------------------------------------------------------------------------------------------- 20002157 2005 kids polo shirt 12.59 white large But this is what my new row DOES look like: Code: [Select] product_id store_id description price colors sizes ---------------------------------------------------------------------------------------------- Large 0 Large 0.00 Large Large So it's taking the value of that last $value and inserting it in all the fields, the store_id and price are 0 and 0.00 because of their numeric type... I assume it is a syntax error, missing quotes somewhere, but where? I've had to rearrange a lot of code and I've been trying to put together a prepared statement in a registration form. I'm having a really hard time and being very new to PHP the issue is really confusing for me. first, I have this function: //PROCESS DB function process_database($post) { global $table; global $conn; //THIS FUCKING THING IS DRIVING ME //check database connection if ($conn->connect_error) { return false; } else { if($statement = $conn->prepare("INSERT INTO $table (username, email, password) VALUES ( ?, ?, ? )")){ $username = $post['username']; $email = $post['email']; $password = $post['password']; $statement->bind_param("sss", $username, $email, $password); $statement->execute(); //DEBUGGING echo "Added: ".$username.", ".$email.", ".$password."<br>"; if(!$statement->execute()){ printf("Connect Failed: %s\n", $conn->connect_error); } else { echo 'fuckin ay!!!'; } //END DEBUG BLOCK } else { return false; } } return true; } The issue is very strange. I'll post the function call so it's clear: //process database actions if (!process_database($data) ) { return array( 'status' => 0, 'message' => 'Unable to process database request' ); } When I run the registration.py without process_database() everything is fine, so I'm confident in the error processing. Here's where it get weird - when I process the form Quoteecho "Added: ".$username.", ".$email.", ".$password."<br>"; is returned from the //DEBUGGING BLOCK but I also get back the error from the following if statement - "Connection Failed: ...." BUT I also get back the registration successful message that only shows if the function returns true In short, it's giving me 2 positive affirmations but also the Connection failed message and of course it's not adding anything to the database. I've been working this function all day, and I'm lost for answers. What's going on with this code? I can't see where I've gone wrong Edited July 1 by TechnoDiverHi
I wonder if someone may help, I have already had a good look online, but not found a solution that works with what i'm trying to do
At the moment I have the following code and it works great
$stmt = $mysqli->prepare("SELECT d.id,d.val FROM datalog pd LEFT JOIN datafeeds d ON d.id = pd.did WHERE pd.pid = ? AND pd.aa = ? AND pd.bb = ?"); $stmt->bind_param('sii', $id,$aa=1,$bb=1); $stmt->execute(); $stmt->bind_result($id,$val); mysqli_stmt_store_result($stmt); if(mysqli_stmt_num_rows($stmt) != 0) { while ($stmt->fetch()) { $array[] = array('numA'=>$id, 'numB'=>$val); } } return $array;but what I would like to do is use an array, which could be any length $array = array(1,2,4,7,9);and change my query to include d.type IN ($array)could someone give me some help? thanks I have just got hold of a MySQLi class (a wrapper to the built in one of course), and for EVERY query sent they have used prepared statements. Is this right? I expected it to just send using the mysqli_query function (with the prepared statements option if selected). Should you send ALL queries using a prepared statement? What (if any) are the downfalls of using prepared statements? in php, pdo, the code does not output any error messages when table is not found.
try { $stmt = $dbh->prepare("SELECT * FROM 1234"); $stmt->execute(); $row = $stmt->fetch(); } catch (PDOException $e) { echo $e->getMessage().' in '.$e->getFile().' on line '.$e->getLine(); }the code only seems to work when the following code is placed just under the "try {" $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);the above code is used just below the connection to the database code. how to get the try - catch code to work without using the setAttribute code every time for prepared statements? To keep my website more secure, I am currently using Prepared Statement. The problem is that even the simplest query (e.g. retrieve Member's First Name) involves an INSANE amount of code. Here is an example of what my code looks like... // ********************** // Find Member Salt. * // ********************** // Build query. $q2 = 'SELECT salt FROM member WHERE email=?'; // Prepare statement. $stmt2 = mysqli_prepare($dbc, $q2); // Bind variables to query. mysqli_stmt_bind_param($stmt2, 's', $email); // Execute query. mysqli_stmt_execute($stmt2); // Store results. mysqli_stmt_store_result($stmt2); // Check # of Records Returned. if (mysqli_stmt_num_rows($stmt2)==1){ // Member found. // Bind result-set to variables. mysqli_stmt_bind_result($stmt2, $salt); // Fetch record. mysqli_stmt_fetch($stmt2); // Close prepared statement. mysqli_stmt_close($stmt2); }else{ $salt=''; // $errors['pass'] = 'A System Error has occurred.'; }// End of FIND MEMBER SALT I am wondering if there is a way to streamline things, perhaps by creating a Function where I can just pass arguments to my specific query needs. Of course if I do that, then a bad guy could pass arguments to the same Function and possibly doing something really bad?! Any ideas? Thanks, Debbie P.S. I am not ready to jump in to OOP, so please keep any responses using old-fashioned Procedural Programming. Thanks! |