Why won't this query work?!?
Error
Parse error: syntax error, unexpected T_STRING in E:\xampp\htdocs\pf\shop\buy.php on line 5
Example Info For Variables
$character->islots = 20
$chatacter->name = [RE] Tizzle
$e2 = 10
The Function
function increaseSlots($e2) {
$slots = ($character->islots)+($e2);
mysql_query('UPDATE `phaos_characters` SET `inventory_slots`="'.$slots.'" WHERE `name`="'.$character->name.'"'); // <-- Line 5
if (mysql_affected_rows() != 0) {
echo 'Inventory Size Incresed By '.$e2.' Slots';
}else{
echo mysql_error();
}
}
Look at the docs: http://php.net/manual/en/function.mysql-num-rows.php
Retrieves the number of rows from a result set. This command is only valid for statements like SELECT or SHOW that return an actual result set. To retrieve the number of rows affected by a INSERT, UPDATE, REPLACE or DELETE query, use mysql_affected_rows().
You need to use mysql_affected_rows() or better yet, PDO or mysqli.
$slots = ($character->islots)+($e2);
Looks like there is a typo. Try:
$slots = ($character->slots)+($e2);
First off you should know that mysql_num_rows only returns a valid result for SELECT or SHOW statements, as stated in the PHP documentation. You can use mysql_affected_rows() for your particular needs.
However, the old PHP MySQL API (that you are using) is being phased out, so I would recommend using mysqli or PDO for your DB connection needs.
While keeping with your requirements, though, you can try to use the following syntax to make sure you receive the MySQL error if it throws one. Your PHP script will stop, but you will see the error.
$query = sprintf('UPDATE `phaos_characters` SET `inventory_slots`=%d WHERE `name`="%s"',$slots,$character->name)
$result = mysql_query($query) or die(mysql_error());
As a final idea, in situations like this it helps to print out your resulting $query and run it manually through something like phpMyAdmin to see what happens.
Bleh... I Found a better way to do it for the time being.. sorry to waste your guys' time...
I just threw the $character object into a variable before processing the function.
function increaseSlots($e2,$charname,$charslots) {
$slots = $charslots+$e2;
mysql_query('UPDATE `phaos_characters` SET `inventory_slots`="'.$slots.'" WHERE `name`="'.$charname.'"');
if (mysql_affected_rows() != 0) {
echo 'Inventory Size Incresed By '.$e2.' Slots';
}
}
Related
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.
I am troubleshooting this query that I was previously trying to use to count rows but now I have discovered that 0 rows are being found in the database even though they exist. I have checked previous queries I have used and they work and look the same. The $db_conx definitely works to connect to the database as I am using it on other web pages. Does any one have any suggestions? Thanks
$result =("SELECT * FROM Request WHERE user2='joey' AND accepted='0'");
$query = mysqli_query($db_conx, $result);
$rows = mysqli_num_rows($query);
if (rows < 1) {
echo '<strong style="color:#F00;">No rows</strong>';
exit();
} else {
echo '<strong style="color:#F00;">Rows exist</strong>';
exit();
}
You are missing an important step to select something from the database and that is what are you trying to select. And, you are also missing the $ in the rows.
$result =("SELECT something FROM Request WHERE user2='joey' AND accepted='0'");
$query = mysqli_query($db_conx, $result);
$rows = mysqli_num_rows($query);
if ($rows < 1) {
echo '<strong style="color:#F00;">No rows</strong>';
exit();
} else {
echo '<strong style="color:#F00;">Rows exist</strong>';
exit();
}
You edited your original post https://stackoverflow.com/revisions/33307758/1
being SELECT FROM Request
You have selected "nothing" from your query
SELECT FROM ...
Read the manual on SELECT:
https://dev.mysql.com/doc/refman/5.0/en/select.html
and this if (rows < 1) { - rows is treated as a constant instead of a variable.
Error reporting would have told you that if it was setup to catch and display on your system.
if ($rows < 1) {
and make sure you are successfully connected to your db using the same MySQL API as your query.
Check for errors on your query
http://php.net/manual/en/mysqli.error.php
Look into using a prepared statement also.
https://en.wikipedia.org/wiki/Prepared_statement
Nota:
You will also need to escape your data should it be coming from user input at one point.
I.e.:
$var = $_POST['var'];
and if $_POST['var'] is equivalent to joey's bistro.
MySQL will see that as WHERE user2='joey's bistro' if it were passed as a variable in the query WHERE user2='$var' resulting in a syntax error.
Escaping it will render it as joey\'s bistro being valid syntax.
$var = mysqli_real_escape_string($db_conx,$_POST['var']);
This would be beneficial for just that as well as helping to protect against an SQL injection.
https://en.wikipedia.org/wiki/SQL_injection
I want to use PHP to find out if no matches are found. I tried the following, but "is_resource()" always returns true.
$result = mysql_query('...');
if(is_resource($result)){
// Results are found
}
mysql_num_rows() will do the trick.
if (mysql_num_rows($result)>0) {
//Results are found
}
http://php.net/manual/en/function.mysql-num-rows.php
So $result will always be a resource as long as you have proper access to the database. And mysql_num_rows() assumes that the query itself ran successfully. I'd say try something like this:
if($result === FALSE) // Query failed due to not having proper permissions on the table
die('Invalid query: ' . mysql_error());
else if(mysql_num_rows($result) >0)) // We have more than 1 row returned which means we have data
// INPUT RESULTS PROCESSING HERE
else // No rows were returned therefore there were no matches
echo 'No rows returned';
Hope that helps a little =)
Look here for more information if you need: http://www.php.net/manual/en/function.mysql-query.php
This is what you want: mysql_num_rows()
If the query fails it mysql_query will return false so you can check your code like this:
if ( $stmt = mysql_query("...") )
{
// Do some things
}
else
{
// Do some other things
}
Or you could use mysql_num_rows like the people above have stated.
But you should really be looking into MySQLi it's a built in database class. Learn it and use it. Your life will be so much easier.
HI everyone i tried for 3 days and i'm not able to solve this problem. This is the codes and i have went through it again and again but i found no errors. I tried at a blank page and it worked but when i put it inside the calendar it has the syntax error. Thanks a million for whoever who can assist.
/** QUERY THE DATABASE FOR AN ENTRY FOR THIS DAY !! IF MATCHES FOUND, PRINT THEM !! **/
$testquery = mysql_query("SELECT orgid FROM sub WHERE userid='$userid'");
while($row4 = mysql_fetch_assoc($testquery))
{
$org = $row4['orgid'];
echo "$org<br>";
$test2 = mysql_query("SELECT nameevent FROM event WHERE `userid`=$org AND EXTRACT(YEAR FROM startdate)='2010' AND EXTRACT(MONTH FROM startdate)='08' AND EXTRACT(DAY FROM startdate)='15'") or die(mysql_error());
while($row5=mysql_fetch_assoc($test2))
{
$namethis = $row5['nameevent'];
$calendar.=$namethis;
}
}
First question: what calendar are you talking about?
And here are my 2-cents: does the EXTRACT function returns a string or a number?
Are the "backticks" (userid) really in your query? Try to strip them off.
Bye!
It's a guess, given that you haven't provided the error message you're seeing, but I imagine that userid is a text field and so the value $org in the WHERE clause needs quotes around it. I say this as the commented out testquery has quotes around the userid field, although I appreciate that it works on a different table. Anyway try this:
SELECT nameevent FROM event WHERE userid='$org' AND EXTRACT(YEAR FROM startdate)='2010' AND EXTRACT(MONTH FROM startdate)='08' AND EXTRACT(DAY FROM startdate)='15'
In such cases it's often useful to echo the sql statement and run it using a database client
First step in debugging problems like this, is to print out the acutal statement you are running. I don't know PHP, but can you first build up the SQL and then print it before calling mysql_query()?
EXTRACT() returns a number not a character value, so you don't need the single quotes when comparing EXTRACT(YEAR FROM startdate) = 2010, but I doubt that this would throw an error (unlike in other databases) but there might be a system configuration that does this.
Another thing that looks a bit strange by just looking at the names of your columns/variables: you are first retrieving a column orgid from the user table. But you compare that to the userid column in the event table. Shouldn't you also be using $userid to retrieve from the event table?
Also in the first query you are putting single quotes around $userid while you are not doing that for the userid column in the event table. Is userid a number or a string? Numbers don't need single quotes.
Any of the mysql_* functions can fail. You have to test all the return values and if one of them indicates an error (usually when the function returns false) your script has to handle it somehow.
E.g. in your query
mysql_query("SELECT orgid FROM sub WHERE userid='$userid'")
you mix a parameter into the sql statement. Have you assured that this value (the value of $userid) is secure for this purpose? see http://en.wikipedia.org/wiki/SQL_injection
You can use a JOIN statement two combine your two sql queryies into one.
see also:
http://docs.php.net/mysql_error
http://docs.php.net/mysql_real_escape_string
http://www.w3schools.com/sql/sql_join.asp
Example of rudimentary error handling:
$mysql = mysql_connect('Fill in', 'the correct', 'values here');
if ( !$mysql ) { // some went wrong, error hanlding here
echo 'connection failed. ', mysql_error();
return;
}
$result = mysql_select_db('dbname', $mysql);
if (!$result ) {
echo 'select_db failed. ', mysql_error($mysql);
return;
}
// Is it safe to use $userid as a parmeter within an sql statement?
// see http://docs.php.net/mysql_real_escape_string
$sql = "SELECT orgid FROM sub WHERE userid='$userid'";
$testquery = mysql_query($sql, $mysql);
if (!$testquery ) {
echo 'query failed. ', mysql_error($mysql), "<br />\n";
echo 'query=<pre>', $sql, '</pre>';
return;
}
I am running a query with a mysql stored procedure :
$AddProf_qr = mysql_query("call AddStudent('$d_Pass', '$d_Titl', '$d_Firs', '$d_Midd', '$d_Last', '$d_Addr', '$d_City', '$d_Stat', '$d_County', '$d_Zipc', $d_Gend, '$d_Birh', '$d_Phom', '$d_Phoh', '$d_Phoo', '$d_Email', '$d_Webs', '$d_Natn', '$d_Profsn', '$d_Compny', '$d_Desig', $d_ProfAcc)", $this->c_remote) or die ("first call" . mysql_error($this->c_remote));
I am supposed to get just one result from the call : ##IDENTITY = a number;
$AP_result = mysql_fetch_array($AddProf_qr);
$CurrentSID = $AP_result['##IDENTITY'];
which works fine. but when i run another mysql update query right after this, it gives an error saying :
Error: 2014 (CR_COMMANDS_OUT_OF_SYNC)
Message: Commands out of sync; you can't run this command now
i have tried inserting :
mysql_free_result($AddProf_qr);
but still the same.
The MySQL call executes fine also
the rest of the script runs without issues the above is commented out. but they don't run at the same time. My best guess is, the call is doing something that's messing this up.
Your stored procedure is returning multiple resultsets. See this post
Solution?
Use mysqli_multi_query
Stop using the ancient mysql library - the i in mysqli stands for "Improved" - with good reason.
#DMin Yes that's would work, but you'll crash the server sooner or later.
Just make the math, one resquest to a page that makes 3 * number of procedures to database!
Just think about it!
[UPDATE] solution:
$aCategory = array();
$it=0;
$res = $mysqli->multi_query( "call ListCategory();" );
if( $res ) {
do {
if ($result = $mysqli->store_result()) {
while( $row = $result->fetch_row() ) {
$aCategory[$it] =$row;
$it= $it + 1;
}
$result->close();
}
} while( $mysqli->next_result() );
}
foreach($aCategory as $row){
echo . $row[0] . " - " . $row[1] . "<br />";
}
Just wanted to add that you are ready to call the next Routine.
PS: By this way I couldn't use
echo $aCategory['category_id'] ;
//or
echo $aCategory->category_id;
//just
echo $aCategory[0]
Check out here: http://us3.php.net/manual/en/function.mysql-query.php In comments, one guy claims that he made it work by setting connection flag to MYSQL_MULTI_RESULTS (131072).
But it would be much better to use mysqli...
mysql_free_result(client->res);
while (mysql_more_results(client->conn))
{
mysql_next_result(client->conn);
}
This did the charm for me :)
Result sets returned from a stored procedure cannot be fetched correctly using mysqli_query(). The mysqli_query() function combines statement execution and fetching the first result set into a buffered result set, if any. However, there are additional stored procedure result sets hidden from the user which cause mysqli_query() to fail returning the user expected result sets.
Result sets returned from a stored procedure are fetched using mysqli_real_query() or mysqli_multi_query(). Both functions allow fetching any number of result sets returned by a statement, such as CALL.
look at official manual