My query is not working when I use the variable in the WHERE clause. I have tried everything. I echo the variable $res, it shows me the perfect value, when I use the variable in the query the query is not fetching anything thus mysqli_num_rows is giving me the zero value, but when I give the value that the variable contains statically the query executes perfectly. I have used the same kind of code many times and it worked perfectly, but now in this part of module it is not working.
Code:
$res = $_GET['res']; // I have tried both post and get
echo $res; //here it echos the value = mahanta
$query = "SELECT * FROM `seller` WHERE `restaurant` = '$res'"; // Here it contains the problem I have tried everything. Note: restaurant name is same as it is in the database $res contains a value and also when I give the value of $res i.e. mahanta in the query it is then working.
$z = mysqli_query($conn, $query);
$row2 = mysqli_fetch_array($z);
echo var_dump($row2); // It is giving me null
$num = mysqli_num_rows($z); // Gives zero
if ($num > 0) {
while ($row2 = mysqli_fetch_array($z)) {
$no = $row2['orders'];
$id = $res . $no;
}
}
else {
echo "none selected";
}
As discussed in the comment. By printing the query var_dump($query), you will get the exact syntax that you are sending to your database to query.
Debugging Tip: You can also test by pasting the var_dump($query) value in your database and you will see the results if your query is okay.
So update your query syntax and print the query will help you.
$query = "SELECT * FROM `seller` WHERE `restaurant` = '$res'";
var_dump($query);
Hope this will help you and for newbies in future, how to test your queries.
Suggestion: Also see how to write a mysql query syntax for better understanding php variables inside mysql query
The problem is the way you're using $res in your query. Use .$res instead. In PHP (native or framework), injecting variables into queries need a proper syntax.
Related
I'm getting a bug.. and I'm thinking it might be because of this code:
$post = addslashes($post);
$r = $conn->query("select id from Posts where post='$post'");
if($id = $r->fetch_assoc()["id"]){
echo 'greg!!!<br>';
}
I'm just trying to echo 'greg!!!' if the query "select id from Posts where post='$post'" returns anything. I'm finding that sometimes this works and sometimes it doesn't... so not really sure. Maybe it's a quotes issue?... but I would think that the addslashes method would take care of that
$r->fetch_assoc()["id"]
I think this will not work, because $r->fetch_assoc() is not an array yet. It should be like:
$post = addslashes($post);
$r = $conn->query("select id from Posts where post='$post'");
$fetch = $r->fetch_assoc();
if($id = $fetch["id"]){
echo 'greg!!!<br>';
}
And it will get in if if SQL query returns anything. You can always check your array with f.ex.:
print_r($fetch);
Or use $r->num_rows to count how many rows have been returned.
You could use rowCount()if PDO, or num_rows if MySQLi to check if there were any rows returned.
// PDO
if($r->rowCount() > 0){echo "greg";}
// MySQLi
if($r->num_rows > 0){echo "greg";}
Here's what I'm doing.
I'm checking if there's a "version" value in the URL with $get_version.
Get the latest version from the database and set as a default variable.
If the URL variable is good, check the database to see if it exists then set the appropriate variables.
If doesn't exist, use default value from above.
It always goes to the "Bad query section". Either my query is wrong or my if statement doesn't work.
Here's my code. Also, is there a cleaner way of doing it?
// Check if there's a version in URL. If not, set to empty.
$get_version = isset($_GET['version']) ? $_GET['version'] : '';
// Set defaults if nothing in URL
$query = "SELECT * FROM sn_hockey_versions ORDER BY version_id DESC LIMIT 1";
mysqli_query($db, $query) or die('Error querying database.');
$result = mysqli_query($db, $query);
while ($row = mysqli_fetch_array($result)) {
$newest_version_id = $row['version_id'];
$newest_sections = $row['sections'];
}
if (!empty($get_version) && preg_match('/^[0-9.]*$/', $get_version)) {
$query = "SELECT version_id, sections FROM sn_hockey_versions WHERE version = '".$get_version."'";
mysqli_query($db, $query) or die('Error querying database.');
$result = mysqli_query($db, $query);
if ($row = mysqli_fetch_array($result)) {
$set_version = $row['version_id'];
$v_sections = $row['sections'];
$test = "IT WORKS!!!!";
}
else {
$set_version = $newest_version_id;
$v_sections = $newest_sections;
$test = "Bad query";
}
}
else {
$set_version = $newest_version_id;
$v_sections = $newest_sections;
$test = "Set default";
}
Your conditional if statement is checking to see whether $rows is set to mysql_fetch_array($result), not whether it returned any results. If the query returns results, the conditional statement returns true, $row is set to the resulting array, and your if block will be evaluated. Otherwise, $row is set to null, making the condition false, and the else block evaluates.
Since your else statement is evaluating, this leads me to believe that there is an issue with the query, which can be tested by printing out the results of the array. While there are numerous ways to check if a query returns any results, to prevent confusion in your code, checking the value of mysql_num_rows would be a better solution before fetching the results:
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_array($result)
For more information about mysqli_num_rows check out http://php.net/manual/en/mysqli-result.num-rows.php
Also see: Whats the proper way to check if mysql_query() returned any results?
The other recommendation I have for making the code more efficient is: Only query the database for the default version when necessary. Too many unnecessary queries can lead to database performance issues. One way to accomplish this, is to place the default version query into a function and call it only in the "bad query" "set default" blocks. I hope this helps.
To check if it was successful outside of the code, copy the query and run it in phpmyadmin or through ssh to see if it returns results. If it returns results then put in some stop checks in your code to see what you are getting. like so
echo '<pre>jwow',print_r($result,1),'</pre>';
die('here');
Just place that under which ever result you would like to check. I like to name the query results by different names. like $defaults_results and $version_results . if it is getting to "Bad Query" you will have found your error after trying that. If it returns no results in phpmyadmin then read the errors it gives.
I have multiple values passed through a POST form (from multiple check boxes of previous page) and I stored them into an array $vals. Now I want to write a query string (in a while loop) that generates a slightly different query depending on how far in the loop it has been.
<?php
$vals=($_POST['selectedIDs']);
$i=0;
while($vals[$i] != NULL){
$query = "SELECT * FROM List foo WHERE foo.fooID = echo $vals[$i]";
$result = mysqli_query($link, $query);
if($result) echo "YES IT WORKS!";
$i += 1;
}?>
But it doesn't seem to work this way? I thought that by having double quotes for query, the
echo $vals[$i]
would generate the actual value of the current index in $vals[$i] and not the literal string? Is this what's happening? Can I not have php inside a query string that the mysql servers would accept?
lets just say i have a fooID in my server table that is '12345'. Even if I set $vals='12345' and write:
$query = "SELECT * FROM List foo WHERE foo.fooID = $vals";
$result = mysqli_query($link, $query);
if($result) echo "YES IT WORKS!";
it still doesn't work. I guess my general question would be: is it possible to write/get values of variables in a query string, and if not, is there another way around my situation? Any help is appreciated. Thanks!
You should not be placing the un-sanitized $_POSTed values into a SQL query. Look into using paramaterized arguments and mysqli.
You can output variables using the syntax:
$myVar = 'toast';
$combined = "I like $myVar";
However, this will not work as you would like for an array.
For an array, you'll want to look into using something like php's implode() to convert your array into a string first.
first of all never do queries in loop.
Second of all never use straight $_POST or $_GET or whatever client is passing in queries because you can be harmed by sql injections.wiki and also clearing data for mysql in php
ok so how it should be done (i am saying only about first one. second one i dont know how to make it without oop ).
<?php
$vals=($_POST['selectedIDs']);
$vals = implode(',',$vals);
$query = "SELECT * FROM List foo WHERE foo.fooID IN ($vals)";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_row($result)) {
echo "YES IT WORKS!";
var_dump($row); //you will see all the data in one row
}
}?>
You have an extra echo in your SQL string:
$query = "SELECT * FROM List foo WHERE foo.fooID = echo $vals[$i]";
It should be:
$query = "SELECT * FROM List foo WHERE foo.fooID = $vals[$i]";
Generally, it's a BAD idea to construct SQL strings from user input. Use prepared statements instead. Check here for more info on prepared statements:
http://php.net/manual/en/pdo.prepared-statements.php
Thanks you guys for the advice but it turned out, my code didn't execute correctly because of a syntax error (and the extra echo statement). my original code was missing quotation marks around $vals[$i]. This is a mysql syntax mistake because it didn't accept foo.fooID=12345 but did for foo.fooID='12345'. Here is the final code that solved it
<?php
$vals=($_POST['selectedIDs']);
$i=0;
while($vals[$i] != NULL){
$query = "SELECT * FROM List foo WHERE foo.fooID = '$vals[$i]'";
$result = mysqli_query($link, $query);
if($result) echo "YES IT WORKS!";
$i += 1;
}?>
I have a problem. I have an array of values from database, when I try to pass it to a string with commas, it works fine on my localhost, but when I upload it to my online server, the string doesn't show any values. For example: select from table where in (,,) only shows the commas and in my xampp server it works excellent. Any ideas what this can be?
Here's the code:
<?php
$sql = "select id from users where gid = 1";
$result = mysql_query( $sql);
$cat_titles=array();
while( $row=mysql_fetch_assoc($result) )
{
$cat_titles[] = $row['id '];
// do stuff with other column
// data if we want
}
mysql_free_result( $result );
echo "<p>\n";
foreach($cat_titles as $v)
{
$cat_titles[]= $row['id'];
}
echo "</p>\n";
$cat_titles = implode(',',$cat_titles);
$cat_titles = substr($cat_titles,0,-2);
echo $cat_titles;
echo "select * from users where IN (".$cat_titles.")";
?>
A number of potential issues here:
You are not handling error conditions around you database access, so if you are having issue with your queries you would never know.
Your second select query doesn't specify a field in the WHERE clause, so it will never work
This section of code does absolutely nothing and is in fact where you problem likely lies.
foreach($cat_titles as $v)
{
$cat_titles[]= $row['id'];
}
Here $row['id'] won't have a value, so you are basically looping throguh your existing array and appending empty value to new indexes.
In all likelihood you could do this with a single query, it might help if you explain what you are actually trying to do.
You should not be using mysql_* functions. They are deprecated. Use mysqli or PDO instead.
I'm trying to take a MySQL result row and pass it to a function for processing but the row isn't getting passed. I'm assuming this is because the actual row comes back as a object and objects can't get passed to function?
E.G
function ProcessResult($TestID,$Row){
global $ResultArray;
$ResultArray["Sub" . $TestID] = $Row["Foo"] - $Row["Bar"];
$ResultArray["Add" . $TestID] = $Row["Foo"] + $Row["Bar"];
}
$SQL = "SELECT TestID,Foo,Bar FROM TestResults WHERE TestDate !='0000-00-00 00:00:00'";
$Result= mysql_query($SQL$con);
if(!$Result){
// SQL Failed
echo "Couldn't find how many tests to get";
}else{
$nRows = mysql_num_rows($Result);
for ($i=0;$i<$nRows;$i++)
{
$Row = mysql_fetch_assoc($Result);
$TestID = $Row[TestID];
ProcessResult($TestID,$Row);
}
}
What I need is $ResultArray populated with a load of data from the MySQL query. This isn't my actual application (I know there's no need to do this for what's shown) but the principle of passing the result to a function is the same.
Is this actually possible to do some how?
Dan
mysql_query($SQL$con); should be mysql_query($SQL,$con); The first is a syntax error. Not sure if this affects your program or if it was just a typo on here.
I would recommend putting quotes around your array keys. $row[TestID] should be $row["TestID"]
The rest looks like it should work, although there are some strange ideas going on here.
Also you can do this to make your code a little cleaner.
if(!$Result){
// SQL Failed
echo "Couldn't find how many tests to get";
}else{
while($Row = mysql_fetch_assoc($Result))
{
$TestID = $Row['TestID'];
ProcessResult($TestID,$Row);
}
}
mysql_fetch_assoc() returns an associative array - see more
If you need an object, try mysql_fetch_object() function - see more
Both array and object can be passed to a function. Thus, your code seems to be correct, except for one line. It should be:
$Result= mysql_query($SQL, $con);
or just:
$Result= mysql_query($SQL);