Query works in phpmyadmin but not in PHP script - php

I found similar questions but can't solve my problem yet. Here is the relevant code:
$query = "SELECT * FROM conceptos WHERE descripcion = '$descripcion'";
if ($result = mysql_query($query,$connection)){
if (mysql_num_rows($result) > 0){
//Do something
} else {
die($query);
exit;
}
} else {
die(mysql_errno() . ' - ' . mysql_error());
exit;
}
I don't have problems with the connection or the permissions, because this code snippet is inside a loop and the other queries enter the "Do something" section. But when I take the echoed query and execute it in phpMyAdmin, it returns 1 value as expected. Why? What reasons can lead to this behavior? Thanks in advance for any advice.

I had this problem and found that it was because I junked up my database by copy/pasting directly to the database from MS Word. Pasting had inserted special slanted apostrophes that PHPMYADMIN could apparently parse but my php code could not. Once I replaced those with a standard single quote, all was well.

Try this "SELECT * FROM conceptos". If it's worked, you have bad query in "WHERE ..."

Are you sure your query is searching for the right description? The double quotes should expand all internal variables, but you do have single quotes as well in case there is a copying to stackoverflow issue.
This will ensure that the description is expanded in case.
$query = "SELECT * FROM conceptos WHERE descripcion = '" . $descripcion . "'";
Secondly, have you validated the variable contents you are using, as suggested by #crotos?
The mysql_ are also deprecated, so you should use PDO, or at the least, mysqli_.

You can try to setup the general query log of your mysql server and see what queries are really executed. See http://dev.mysql.com/doc/refman/5.1/en/query-log.html
Also, check your encodings. Maybe your mysql connection is in ISO8859-1 and your table fields are in UTF-8 (or the opposite). Do you have any accents or special characters in your data?

i also faced this problem and got it solved using:
mysqli_query($con,$query);
instead of
mysql_query($query);
coz its depreciated
source:
File Downloading error from database php

Related

Returning a field with an ampersand

I'm having a strange problem while trying to get some data out of a MySQL database using PHP. Not sure if it matters, but encoding on database, connection and PHP file are all UTF-8. Heres my code:
$testcode = "Unique12345 & TestName";
$sql="
Select
dw_test.testID,
dw_test.testText
From
dw_test
Where
dw_test.testCode = '".$testcode."'
";
if(!$qry = mysqli_query($link, $sql)) reporterror(mysqli_error($link), $sql, $_SERVER['SCRIPT_URL'], __FILE__, __LINE__);
if(mysqli_num_rows($qry)>0){
$test_array = mysqli_fetch_assoc($qry);
$resultTest = $test_array['testID'];
$testText = $test_array['testText'];
}else{
echo "Nothing found";
}
If I run that using PHP, it will say "Nothing found", but if I run it using Windows MySQL Workbench, it returns 1 record (the correct one). I suspect that it is the ampersand (&), because changing the query to something else that exists works fine.
I have tried escaping the & with a slash:
$testcode = str_replace("&","\&",$testcode);
and I have tried playing around with single and double quote combinations, but everything I try produces the same result
What am I doing wrong in my PHP? How come the Workbench tool works fine when using the same query?
I solved it!
I added this in front of the sql query:
$testcode = str_replace("&","&",$testcode);
Thanks for everyones help

How to solve parameters in MYSQLi?

I am having a problem in my php file named JO-dashboard.php. It displays the error presented below the code.
Here is my code:
<?php
$link = connectToDB();
$strXML = "<chart caption='Factory Output report' subCaption='By Quantity' pieSliceDepth='30' showBorder='1' formatNumberScale='0' numberSuffix=' Units'>";
$strQuery = "select DISTINCT profile from vgprofile";
$result = mysqli_query($link, $strQuery) or die(mysqli_error());
if($result) {
while ($ors = mysqli_fetch_array($result)) {
$strQuery = "select sum(MT) as totalLM from tbljocreator where PROFILE =" . $ors['profile'];
$result2 = mysqli_query($link, $strQuery) or die(mysqli_error());
$getresult2 = mysqli_fetch_array($result2);
$strXML .= "<set label='" . $ors['profile'] . "' value ='" . $getresult2['totalLM'] . "' />";
mysqli_free_result($result2);
}
}
mysqli_close($link);
$strXML .= "</chart>";
echo renderChart("FusionCharts/Column3D.swf", "", $strXML, "JoCreator", 450, 300, false, true);
?>
THE ERROR IS IN:
$result2 = mysqli_query($link, $strQuery) or die(mysqli_error());
In the browser it shows:
Warning: mysqli_error() expects exactly 1 parameter, 0 given in C:\xampp\htdocs\LearningFusionCharts\MyFirstChart\JO-dashboard.php on line 29
the mysqli_error function requires a parameter. http://us3.php.net/mysqli_error
p.s clean up your code and using tabs :)
The initial problem
You have to pass the connection object to the function mysqli_error, like this:
$result = mysqli_query($link, $strQuery) or die(mysqli_error($link));
And this...
$result2 = mysqli_query($link, $strQuery) or die(mysqli_error($link));
Note: your code must have another problem that will be revealed after you do this. PHP wouldn't be executing the part of mysqli_error if there weren't an error in the query or something related to it.
The hidden problem
In fact, I have reasons to think* the problem is that $ors['profile'] is string, and therefore it should be between quotation marks in the query string:
$strQuery = 'select sum(MT) as totalLM from tbljocreator where PROFILE = "' . $ors['profile'] . '"';
*: This was confirmed in the comments. The error was:
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 'RIVETS' at line 1
In this case RIVETS is the value of $ors['profile'] and evidently it is an string, ergo it must go between quotation marks...but that doesn't mean it is safe.
SQL Injection
We could say that your code is correct, the same code will probably work is the data where different. Yet, since the values you are putting in the query string may not be entirely safe (even with the data comming from the database), you will have to escape the dangerous characters.
This is put in evidence by the error you got:
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 '"CUTTING DISC 4""' at line 1
In this case, the variable $ors['profile'] got the string CUTTING DISC 4". This value is comming from the database and is causes a problem. It contains 4" meaning four inches, but Mysql sees the quotation marks (") and thinks that that is the end of the string, and tries to interpret whatever comes after the quotation marks as SQL.
If this input weren't from the database, but form the user... it would be worst... a malicious user could take adventage of it to execute arbitrary commands in the database. The potential of this kind of attack is overwhelming.
I recommend the video Hacking Websites with SQL Injection - Computerphile, it is a very good introduction to SQL injection for those beginners to web security, database security or information security in general. To learn more about what can be potentially be done with this kind of attack, read SQL Injection Walkthrough (DVWA) by Trenton Ivey.
Preventing SQL Injection - The old way
The old way to solve this problem is to escape the characters. SQL allows to do so by using the backslash character (\). So, in this example you would have to pass 4\" instead of 4". But that is the tip of the iceberg, there are plenty of security problems with it.
Something you could do for ease of migration is to declare a function to sanitize the data you send to the database, the idea is to escape any possibly treating character... in fact there is a function for that in PHP (mysql_real_escape_string):
$strQuery = 'select sum(MT) as totalLM from tbljocreator where PROFILE = "' . mysql_real_escape_string($ors['profile']) . '"';
The problems with the old way
But mysql_real_escape_string is deprecated and should not be used in new development (you would notice it is not form mysqli... ), this function has some quirks of itself too... for example there is no way to tell that function what character encoding you are using (it uses whatever the databases is using), and there has been reports of problems with it when using multibyte characters. That is the old way to solve this.
Here goes another recommendation: The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets by Joel Spolsky. I understand if you don't want to read... get another video: Characters, Symbols and the Unicode Miracle - Computerphile
Preventing SQL Injection - The new and improved way
With that said, the correct solution is to migrate to prepared statements, they are not really that hard with mysqli, it would be something like this:
$strQuery = 'select sum(MT) as totalLM from tbljocreator where PROFILE = ?';
if($stmt = $link->prepare($strQuery))
{
//s for string
//i for integer
//d for double (or float)
$stmt->bind_param('s', $ors['profile']);
if (!$stmt->execute())
{
die mysqli_error($link);
}
}
else
{
die mysqli_error($link);
}
Read more about Prepared Statements at PHP.net.
Just change
mysqli_error()
to
mysqli_error($link)
in each of the places where it occurs.
ie 4th line:
$result = mysqli_query($link, $strQuery) or die(mysqli_error($link));
and 8th line:
$result2 = mysqli_query($link, $strQuery) or die(mysqli_error($link));
Replace
mysqli_error()
by
mysqli_error($link)
By the way, if the error message is as clear, you don't need to ask here. Just read the manual.

Pause foreach and continue

I'm trying to loop data from a api and then post these values to a MySQL db.
something like this:
$values = json_decode(file_get_contents("my-json-file"));
$SQL = new mysqli(SQL_HOST, SQL_USER, SQL_PASS, DB_NAME);
$SQL->autocommit(FALSE);
foreach($values As $item)
{
$query = "INSERT INTO my_table VALUES ('".$item->value1."', '".$item->value2.";)";
$SQL->query($query);
if(!$SQL->commit())
{
echo "ERROR ON INSERT: [" . $query . "]<hr/>";
}
}
$SQL->close();
Since the loop is too fast, the SQL can't catch up. (Yea!)
I would then need something like this:
foreach($values As $item)
{
/**** STOP/PAUSE LOOP ****/
$query = "INSERT INTO my_table VALUES ('".$item->value1."', '".$item->value2.";");
$SQL->query($query);
if($SQL->commit())
{
/**** START THE LOOP AGAIN ****/
}
else
{
echo "ERROR ON INSERT: [" . $query . "]<hr/>";
}
}
Or how should I do this the right way?
EDIT: It inserts random posts every time.
EDIT 2: This is just example code. It does escape and all that, and yes the semi colon is wrong here but since so many commented on it i will not change it. This was not the problem in the real case.
I tried to run it on another server and there it worked. The problem was fixed by restarting MAMP.
Firstly, your idea that the loop runs too fast for MySQL to keep up is completely totally wrong. The $SQL->query() call will wait for the MySQL to return a response before proceeding, so the loop won't run any faster than MySQL is responding.
Now onto the actual problem.... your query:
$query = "INSERT INTO my_table VALUES ('".$item->value1."', '".$item->value2.";)";
There's a semi-colon in there at the end, after value2 which is invalid. I guess you intended to type a quote mark there? The semi-colon will be causing all your queries to fail and throw errors.
This may be the cause of your problem but you haven't got any error checking in there, so you won't know. Add some error checking to your code after calling the query; even if the query is right, it's still possible to get errors, and your code should check for them. See the examples on this manual page: http://www.php.net/manual/en/mysqli-stmt.error.php
Finally, since you're using the mysqli API, it's worth mentioning that your code would be a lot better and probably more secure if you used prepared statements. See the examples in PHP manual here: http://www.php.net/manual/en/mysqli-stmt.bind-param.php
[EDIT]
Another possible reason your query is failing is that you're not escaping the input values. If any of the input values contains a quote character (or any other character that is illegal in SQL) then the query will fail. In addition, this problem makes your code vulnerable to a SQL injection hacking attack.
You need to escape your input using $SQL->real_escape_string() OR by changing your query to use prepared statements (as recommended above).
Your query is inside the loop, which means that the loop will wait until your query finished executing before it continue, php code is processed in order...
Has #phpalix said, PHP goes in order, and waits for the previous action to finish.
I think you SQL is wrong. Try replacing your INSERT with this:
$query = "INSERT INTO my_table VALUES ('".$item->value1."', '".$item->value2."');";
And don't forget to run at least mysql_real_escape_string for each variable, for security measures.
As many of the answers and comments say, it does not continue until the SQL is done. The problem was in my local apache/mysql server. It was fixed by restarting it. Yes, stupid post.

PHP MySql Select statement not working... Any advice?

[UPDATED] with new code "sql_real_escape_string()"
[UPDATED] if anyone wants to look at the site its at Test site
[UPDATED] with the while code showing any results via echo
Hello All,
I have looked at many posts on this matter, but simply cannot understand why the following code doesn't work:
$username = $_POST['username'];
// get the record of the user, by looking up username in the database.
$query = sprintf("SELECT UserName, Password FROM userlogin WHERE UserName='%s'", mysql_real_escape_string($username));
$result = mysqli_query($dbc, $query) or
die ("Error Querying Database for: " . $query .
"<br />Error Details: " . mysql_error() . "<br/>" . $result);
while ($row = mysqli_fetch_assoc($result))
{
Echo($row['UserName']);
}
The Code seems to be correct... the database is working perfectly (for input purposes) and the connection is a shared connection applied with require_once('databaseconnection.php'); that is working for the registration side of things.
like normal I'm sure this is something simple that I have overlooked but cannot for the life of me see it!
I do not get any error messages from the myssql_error() its simply blank.
any help would be much appreciated.
Regards
Check the username you try to query as it might be empty. Do you really use a post-request to run that script? How do you verify that it does not work? What do you do with $data after the query?
If just nothing seems to happen it is likely your query did not match any record. Check for whitespace and case of the username you are looking for.
Mind those warnings:
Use a prepared statement or at least sql-escape any user-input before using it in sql.
Don't use die in serious code only for debugging.
The $data will contain a result object. You need to iterate over it using something like mysqli_fetch_assoc($data).
Also, you can interpolate variables directly into double quoted strings - i.e. UserName='".$username."'" could be written more cleanly as UserName='$username' rather than breaking out of the string.
Also, please sanitize your input - all input is evil - using mysqli_real_escape_string() function. You've got a SQL injection exploit waiting to happen here.
Bear in mind that it's a very good idea to validate all data to be inserted into a database.
Very often you have problems with query itself, not implementation. Try it in phpMyAdmin first and see if there are any problems.
Check server logs.
BY THE WAY: Never put variables from POST to query! That's definitely a SQL injection'
You might have some issue with the query.
Have you Tried to echo the $query and run that directly with mysql client or workbench?
This piece of code seems ok. That is, if $dbc contains an actual database connection. But the choice of naming that variable $data while the function actually returns a result object or a boolean, indicates that you may process the data wrong.
If that is not the problem, we'll definately have to see more code.
Try printing $data variable instead of printing only query. Check, whether you are able to get any error messages. If you could see any data then you should use mysql fetch function to iterate things. Try it.

PHP sql with foreach loop variable problem

This is really getting frustrating. I have a text file that I'm reading for a list of part numbers that goes into an array. I'm using the following foreach function to search a database for matching numbers.
$file = file('parts_array.txt');
foreach ($file as $newPart)
{
$sql = "SELECT products_sku FROM products WHERE products_sku='" . $newPart . "'";
$rs = mysql_query($sql);
$num_rows = mysql_num_rows($rs);
echo $num_rows;
echo "<br />";
}
The problem is I'm getting 0 rows returned from mysql_num_rows. I can type the sql statement without the variable and it works perfectly. I can even echo out the sql statement from this script, copy and paste the statement from the browser and it works. But, for some reason I'm not getting any records when I'm using the variable. I've used variables in sql statements tons of times, but this really has me stumped.
Try trimming and mysql_real_escape_string on your variable.
Check the source code of what is being echoed out and try to copy and paste that into PHPMyAdmin or something similar.
file includes newlines in the array elements. This may explain why it works when you copy the browser output but not in the script. You can try either:
$file = file('parts_array.txt', FILE_IGNORE_NEW_LINES);
or:
$sql = "SELECT products_sku FROM products WHERE products_sku='" . trim($newPart) . "'";
Note: Even though you're importing from a file of your own making, you can never be 100% sure that inject-able data hasn't been inserted into it. You should make sure to properly escape any data with mysql_real_escape_string. Even better would be using PDO prepared statements instead.
Obviously your code does something different than you expect. Running a successful query, for one: you don't check the return value of the mysql_query call, so you cannot be sure the query executed ok.
My idea:
dump your sql statement from the foreach
check the return code of the mysql_query
What does your parts_array.txt file look like? Do SKU numbers contain the ' character?
Can you please try this:
$file = file('parts_array.txt');
foreach ($file as $line_num => $line)
{
$sql = "SELECT products_sku FROM products WHERE products_sku='$line'";
echo $sql;
$rs = mysql_query($sql);
$num_rows = mysql_num_rows($rs);
echo $num_rows;
echo "<br />";
}
You might want to check for a mysql_error. It sounds like you've already verified the variable and have copied the query into a database interface like PHPMyAdmin or Query Browser, but if you haven't, I would recommend that.
After, verify that a very basic query will work, like SELECT * FROM Products. That will tell you if there is a problem outside of the query.
Overall, I would say the strategy would be to break the problem down into possible problem areas, like database, connection, query, errors, etc. Try to eliminate them one at a time until the problem is apparent. In other words, list the possibilities and cross them off one at a time.
I've encountered problems like this before; the trick is usually to start echoing things until you see the problem, and don't work off of assumptions.
I know this is pretty old now- but I'd like to help out others who may also be facing a similar problem with SQL statements that need to contain a potentially infinite number generated search parameters.
The code in the askers question is perfectly valid (for the avoidance of doubt) [see below]:
$file = file('parts_array.txt');
foreach ($file as $newPart)
{
$sql = "SELECT products_sku FROM products WHERE products_sku='" . $newPart . "'";
$rs = mysql_query($sql);
$num_rows = mysql_num_rows($rs);
echo $num_rows;
echo "<br />";
}
Their problem lies in the formatting of their text file ('parts_array.txt'). The root cause of the issue can be tracked down by dumping the information sent back by the server. Alternatively- they can try writing an SQL query in PHPMyAdmin and pasting in some or all of the data in their text file. MySQL will happily torment them until they find the problem.
For those trying to implement a variable based SQL query- the above is the way to go.
If you are trying to get data from an array, instead of a text file- you could do something like the following:
foreach ($array as $array_stuff)
{
$search_query = "SELECT * FROM table WHERE id='" . $array_stuff . "'";
$rs = mysqli_query($database_connection, $search_query);
$table_rows = mysqli_fetch_assoc($rs);
echo $table_rows['id']." - ".$table_rows['desc'];
echo "<br />";
}
/* free result set */
mysqli_free_result($rs);
This would output your data like this:
1001 - data 1 1002 - data 2 1003 - data 3
Note: The use of "mysql" functions are actively discouraged by MySQL. Therefore the second example I have given above is more up-to-date with current technologies, and using "mysqli" instead.
Also important
If you are here from a Google search as a result of trying to get data from a database, using a complex SQL query- you might have already tried to do something like the example below (or be considering it).
Do not attempt to write a variable based SQL query as per the example below. It won't work and will be incredibly frustrating.
Based on recent technological advancements- the second example I have given (using "mysqli") is the correct way (if there is one) to achieve this.
Bad example:
if ($search_result = mysqli_query($dbh1, "SELECT FROM sic_codes WHERE id = (".foreach ($_POST['SIC_Codes'] as $sic_codes) {echo "'".$sic_codes."' OR id = '',";})) {
/* fetch associative array */
while ($search_row = mysqli_fetch_assoc($search_result)) {
echo $row["id"]." - ".$row["desc"]."<br/>";
}

Categories