PHP - Call_user_func_array() With Dynamic Mysql Query Error
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! Similar TutorialsSo 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>'; Here is my code: // Start MySQL Query for Records $query = "SELECT codes_update_no_join_1b" . "SET orig_code_1 = new_code_1, orig_code_2 = new_code_2" . "WHERE concat(orig_code_1, orig_code_2) = concat(old_code_1, old_code_2)"; $results = mysql_query($query) or die(mysql_error()); // End MySQL Query for Records This query runs perfectly fine when run direct as SQL in phpMyAdmin, but throws this error when running in my script??? Why is this??? Code: [Select] You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '= new_code_1, orig_code_2 = new_code_2WHERE concat(orig_code_1, orig_c' at line 1 Here is the error I get ERROR: Could not execute query: INSERT INTO items (quickti, longti, desc, maincat, subcat1, subcat2, colour, size, style, price, stock, pic1, pic2, pic3, pic4, pic5, pic6, sold, saledate) VALUES ('quick', 'main title', 'description', 'Jewelry', 'Gemstones', 'Cubic Zirconia', 'Black', '50m', 'red', '1.50', '100', 'quick1', 'quick2', 'quick3', 'quick4', 'quick5', 'quick6', '0', '0'). You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'desc, maincat, subcat1, subcat2, colour, size, style, price, stock, pic1, pic2, ' at line 1 Here is the relevant code $sql = "INSERT INTO items (quickti, longti, desc, maincat, subcat1, subcat2, colour, size, style, price, stock, pic1, pic2, pic3, pic4, pic5, pic6, sold, saledate) VALUES ('$quickheading', '$heading', '$content', '$cat1', '$cat2', '$cat3', '$colour', '$size', '$style', '$total', '$stock', '$quick1', '$quick2', '$quick3', '$quick4', '$quick5', '$quick6', '0', '0')"; if I remove desc and $content from the query, then it works. desc is a text field. when i run the below code i get an error...
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in...
but when i take out the h>0 then there is no errors in the code. in table users, i need all columns in the array. How to get h>0 working?
$query = "SELECT * FROM users WHERE h>0 ORDER BY id"; $result = mysqli_query($link, $query); $data = array(); while($row1 = mysqli_fetch_array($result)) { $data[] = $row1; } print_r($data); Edited by kalster, 27 October 2014 - 07:38 PM. Can anyone tell me whats wrong with this code? The mysql error I get is generic and says
"Could not enter data: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Tickets (Name,Tech,Node,Address,Tap,Ped,Lash,Hardline,Other,Comments) VALUES ('C' at line 1"
<?php $name=$_POST['name']; $id=$_POST['id']; $node=$_POST['node']; $ped=$_POST['ped']; $tap=$_POST['tap']; $lash=$_POST['lash']; $hardline=$_POST['hardline']; $other=$_POST['other']; $address=$_POST['address']; $city=$_POST['city']; $comments=$_POST['comments']; $dbhost = 'xxxx'; $dbuser = 'xxxx'; $dbpass = 'xxxx'; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die('Could not connect: ' . mysql_error()); } $sql = "INSERT INTO Damage Tickets (Name,Tech,Node,Address,Tap,Ped,Lash,Hardline,Other,Comments) VALUES ('$name','$id','$node','$address','$city','$tap','$ped','$lash','$hardline','$other','$comments')"; mysql_select_db('xxxxx'); $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not enter data: ' . mysql_error()); } echo "Your Damage has been Submitted! <a href=\"damage.php\">Go Back</a>"; mysql_close($conn); ?>No idea whats wrong with it? Thanks for any help Is there a call_user_func_array() alternative other than eval()? With the shear genius of some of the individuals on this forum, I'd expect that if there is an alternative, someone here would know it. Any tips or insight greatly appreciated. Thanks Background (blah blah blah) I'm being kinda picky on efficiency and performance since I will be looking at possible hundreds of executions a request... so I'd like to avoid using the above mentioned functions since they take ~3x and ~10x longer (according to a this comment). Hello i have two questions, regarding my problem. 1. I have a script which uses call_user_func_array , i heard it is not the best solution, here i post my script, please tell me what can i use instead of call_user_func_array, of course if the rumours are true that it is not the best solution. 2. My second question is that i get a warning message, if i turn error_reporting on: 'Warning: Wrong parameter count for array_intersect() in index.php on line xxx' However the site displays properly, but i want to get rid of this error message, why is it appearing what is the problem. My script: Code: [Select] $result = mysql_query("select id from table where word = '". $value ."'); while ($row = mysql_fetch_array($result, MYSQL_NUM)) { $query_results[$value][] = $row[0]; } $ids = call_user_func_array('array_intersect', $query_results); Well in the class UserValidator I have a public method validate(), which checks the validation type and then calls specific private methods to execute the validation script. It gets a bit tricky here since the method validate() has to decide what private method to call. I am thinking about using call_user_func_array(), the script currently looks like this below: Code: [Select] public function validate(){ // The core method validate, it sends requests to different private methods based on the type if(empty($this->type)) throw new Exception('The validation type is empty, something must be seriously wrong...'); if(is_array($this->type) and !is_array($this->value)) throw new Exception('Cannot have scalar value if the type is an array.'); if(!is_array($this->type) and is_array($this->value)) throw new Exception('Cannot have scalar type if the value is an array.'); // Now we are validating our user data or input! $validarray = array("register", "login", "password", "session", "email", "reset", "profile", "contacts", "friends"); foreach($this->type as $val){ $method = "{$val}validate"; if(in_array($val, $validarray)) call_user_func_array(array($this, $method), array()); } } The method to execute depends on the validation type passed into the validator class, so it is somewhat like a dynamic function call. The problem is, well, I am not sure if I am using call_user_func_array() properly. I read it from php manual that it needs to accept a class instance, but there is no such instance inside a class method so I use $this in the argument. Is this the correct way of using call_user_func_array()? If not, how am I supposed to do this? thanks. If you also have any feedback on my code, please do tell me. I wish to improve my coding base. Basically when you fill out the register form, it will check for data, then execute the insert query. But for some reason, the query will NOT insert into the database. In the following code below, I left out the field ID. Doesn't work with it anyways, and I'm not sure it makes a difference. Code: Code: [Select] mysql_query("INSERT INTO servers (username, password, name, type, description, ip, votes, beta) VALUES ($username, $password, $name, $server_type, $description, $ip, 0, 1)"); Full code: Code: [Select] <?php include_once("includes/config.php"); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title><? $title; ?></title> <meta http-equiv="Content-Language" content="English" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link rel="stylesheet" type="text/css" href="style.css" media="screen" /> </head> <body> <div id="wrap"> <div id="header"> <h1><? $title; ?></h1> <h2><? $description; ?></h2> </div> <? include_once("includes/navigation.php"); ?> <div id="content"> <div id="right"> <h2>Create</h2> <div id="artlicles"> <?php if(!$_SESSION['user']) { $username = mysql_real_escape_string($_POST['username']); $password = mysql_real_escape_string($_POST['password']); $name = mysql_real_escape_string($_POST['name']); $server_type = mysql_real_escape_string($_POST['type']); $description = mysql_real_escape_string($_POST['description']); if(!$username || !$password || !$server_type || !$description || !$name) { echo "Note: Descriptions allow HTML. Any abuse of this will result in an IP and account ban. No warnings!<br/>All forms are required to be filled out.<br><form action='create.php' method='POST'><table><tr><td>Username</td><td><input type='text' name='username'></td></tr><tr><td>Password</td><td><input type='password' name='password'></td></tr>"; echo "<tr><td>Sever Name</td><td><input type='text' name='name' maxlength='35'></td></tr><tr><td>Type of Server</td><td><select name='type'> <option value='Any'>Any</option> <option value='PvP'>PvP</option> <option value='Creative'>Creative</option> <option value='Survival'>Survival</option> <option value='Roleplay'>RolePlay</option> </select></td></tr> <tr><td>Description</td><td><textarea maxlength='1500' rows='18' cols='40' name='description'></textarea></td></tr>"; echo "<tr><td>Submit</td><td><input type='submit'></td></tr></table></form>"; } elseif(strlen($password) < 8) { echo "Password needs to be higher than 8 characters!"; } elseif(strlen($username) > 13) { echo "Username can't be greater than 13 characters!"; } else { $check1 = mysql_query("SELECT username,name FROM servers WHERE username = '$username' OR name = '$name' LIMIT 1"); if(mysql_num_rows($check1) < 0) { echo "Sorry, there is already an account with this username and/or server name!"; } else { $ip = $_SERVER['REMOTE_ADDR']; mysql_query("INSERT INTO servers (username, password, name, type, description, ip, votes, beta) VALUES ($username, $password, $name, $server_type, $description, $ip, 0, 1)"); echo "Server has been succesfully created!"; } } } else { echo "You are currently logged in!"; } ?> </div> </div> <div style="clear: both;"> </div> </div> <div id="footer"> <a href="http://www.templatesold.com/" target="_blank">Website Templates</a> by <a href="http://www.free-css-templates.com/" target="_blank">Free CSS Templates</a> - Site Copyright MCTop </div> </div> </body> </html> 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 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... 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 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!!!! 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. I'm restarting this under a new subject b/c I learned some things after I initially posted and the subject heading is no longer accurate. What would cause this behavior - when I populate session vars from a MYSQL query, they stick, if I populate them from an MSSQL query, they drop. It doesn't matter if I get to the next page using a header redirect or a form submit. I have two session vars I'm loading from a MYSQL query and they remain, the two loaded from MSSQL disappear. I have confirmed that all four session vars are loading ok initially and I can echo them out to the page, but when the application moves to next page via redirect or form submit, the two vars loaded from MSSQL are empty. Any ideas? A friend of mine must of changed something on the site while I was asleep last night and now all the site says when you go to it is: Error Database query error Warning: mail() [function.mail]: SMTP server response: 530 SMTP authentication is required. in C:\xampp\htdocs\inc\utils.inc.php on line 449 I'm not exactly sure what he did since I can't contact him. Can anyone help me fix this? I have been pulling my hair out for the lasy 3 hours i am trying to update a MySql table but i cant get it too work, i just keep getting MySql error #1064 - You have an error in your SQL syntax; if i just update 1 field it works fine but if i try to update more than 1 field it dosent work, Help Please! <?php $root = $_SERVER['DOCUMENT_ROOT']; require("$root/include/mysqldb.php"); require("$root/include/incpost.php"); $con = mysql_connect("$dbhost","$dbuser","$dbpass"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("$dbame", $con); mysql_query("UPDATE Reg_Profile_p SET build='$build' col='$col' size='$size' WHERE uin = '$uinco'"); ?> Hello all. I have an ID Messaging system where the user puts in the ID of the user they want to contact and it sends a message to their Inbox - Great. What I need is a feature where the user puts in the ID and onblur another textbox populates with the users Name from the MySQL Database without having to reload the page so they know they have the right person. I am pretty new to this so have no idea where to start with this population feature. Here's my form code. Hope someone can help. <table width="450" border="0"> <tr> <td> <form name="messages" method="post" action="inbox_messages_send.php" onsubmit="return checkform(this);"> <table width="411" height="227" border="0"> <tr> <td align="right" bgcolor="#EAEAEA"><font size="2" face="Arial, Helvetica, sans-serif">From:</font></td> <td bgcolor="#EAEAEA"><input type="hidden" name="sentBy" size="3" maxlength="3" align="absmiddle" value="<?php echo $_SESSION['member_ID']; ?>"> <input type="hidden" name="fname" value="<?php print email('name'); ?>"><input type="hidden" name="lname" value="<?php print email('lname'); ?>"> <font size="1" face="Arial, Helvetica, sans-serif">(Your ID is automatically attached)</font></td> </tr> <tr> <td align="right" bgcolor="#EAEAEA"><font size="2" face="Arial, Helvetica, sans-serif">To:</font></td> <td bgcolor="#EAEAEA"><input type="text" name="L_ID" size="3" maxlength="3" align="absmiddle"> <font size="1" face="Arial, Helvetica, sans-serif">(Member's ID)</font></td> </tr> <tr> <td align="right" bgcolor="#EAEAEA"><font size="2" face="Arial, Helvetica, sans-serif">Subject:</font></td> <td bgcolor="#EAEAEA"><input type="text" name="subject"></td> </tr> <tr> <td align="right" bgcolor="#EAEAEA"><font size="2" face="Arial, Helvetica, sans-serif">Message:</font></td> <td bgcolor="#EAEAEA"><textarea cols="35" rows="5" name="email_message"></textarea></td> </tr> <tr> <td align="right"> </td> <td><input type="submit" name="message" value="Send Message"></td> </tr> </table> </form></td> </tr> </table> Hi there,
I have a table in a MySQL database where I keep a list of user privileges. I am trying to create variables where the name of variable matches the privileges in the table.
This is also known as variable variables (I think).
EDIT (17/07/2014 04:02 PM): This might be a better way to describe what I'd like, so if the value from the table is admin_panel I'd like to dynamically create a variable with that name.
I have created a code so far, but all I seem to be getting is a list of Notice errors telling me that the variable is undefined. (I have supplied a list of errors a bit further down the post).
Here is the code:
<?php $host = "localhost"; $account = "***"; $password = "****"; $dbname = "****"; $connect = mysql_connect($host,$account,$password) or die("Unable To Connect"); $db = mysql_select_db($dbname,$connect) or die("Unable To Select DB"); $perm_query = "SELECT * FROM `privileges`"; $permission_query = mysql_query($perm_query); while($row = mysql_fetch_array($permission_query)) { $rows[] = $row; } foreach($rows as $row) { ${$row['privilege']}; } ?>The list of errors: Notice: Undefined variable: admin_panel in C:\xampp\htdocs\DynamicVariables.php on line 20 Notice: Undefined variable: create_user in C:\xampp\htdocs\DynamicVariables.php on line 20 Notice: Undefined variable: edit_user in C:\xampp\htdocs\DynamicVariables.php on line 20 Notice: Undefined variable: delete_user in C:\xampp\htdocs\DynamicVariables.php on line 20 Notice: Undefined variable: create_group in C:\xampp\htdocs\DynamicVariables.php on line 20 Notice: Undefined variable: edit_group in C:\xampp\htdocs\DynamicVariables.php on line 20 Notice: Undefined variable: delete_group in C:\xampp\htdocs\DynamicVariables.php on line 20 Notice: Undefined variable: view_log in C:\xampp\htdocs\DynamicVariables.php on line 20 Notice: Undefined variable: log_settings in C:\xampp\htdocs\DynamicVariables.php on line 20 Notice: Undefined variable: password_change in C:\xampp\htdocs\DynamicVariables.php on line 20 Thanks Edited by chrisrulez001, 17 July 2014 - 10:05 AM. Hi So I have successfully set up a website and database where a user can create a listing and view listings on a listing details page. The viewing can only be done, however, only from either from either running a search query from the search form or from clicking one of the listings from the listing table. The listings are not being indexed from the search engines from the direct page, instead from the listing table which is about 3,000 listings, not very user friendly to land on this page and have to go through the table or use the table filter. Here's what I am trying to accomplish: A web page that has a dynamic presence / URL like a Wordpress page: http://www.mysite.com/listing_title/ The title of the page has the listing information in it: This page is about a $listing_title $listing_item listing number $listing_number that is online! Each individual Listing / page is indexed on the search engines and has a direct link to it I am familiar with PHP and have created this site but I am far from an expert! Please give me a code example or link to one because if you just say "do this to this and that" you will totally loose me. Thank you so much for any help. |