mysql_result() expects parameter 1 to be resource, boolean given instead - mysql

if(mysql_result(mysql_query("SELECT COUNT (`user_id`) FROM `users` WHERE `email` = '$email' AND `email_code` = '$email_code' AND `active` = 0"), 0) == mysql_query("UPDATE `users` SET `active` = 1 WHERE `email` = '$email'");
return true;
} else {
return false;
}
I know that this is probably a duplicate from somewhere, but this is driving me insane right now. Please help.

This error message is displayed when you have an error in your query which caused it to fail.
Note: This error does not appear if no rows are affected by your query. Only a query with an invalid syntax will generate this error.
Troubleshooting Steps
Make sure you have your development server configured to display all errors. You can do this by placing this at the top of your files or in your config file: error_reporting(-1);. If you have any syntax errors this will point them out to you.
Use mysql_error(). mysql_error() will report any errors MySQL encountered while performing your query.
Sample usage:
mysql_connect($host, $username, $password) or die("cannot connect");
mysql_select_db($db_name) or die("cannot select DB");
$sql = "SELECT * FROM table_name";
$result = mysql_query($sql);
if (false === $result) {
echo mysql_error();
}
Run your query from the MySQL command line or a tool like phpMyAdmin. If you have a syntax error in your query this will tell you what it is.
Make sure your quotes are correct. A missing quote around the query or a value can cause a query to fail.
Make sure you are escaping your values. Quotes in your query can cause a query to fail (and also leave you open to SQL injections). Use mysql_real_escape_string() to escape your input.
Make sure you are not mixing mysqli_* and mysql_* functions. They are not the same thing and cannot be used together. (If you're going to choose one or the other stick with mysqli_*. See below for why.)
Other tips
mysql_* functions should not be used for new code. They are no longer maintained and the community has begun the deprecation process. Instead you should learn about prepared statements and use either PDO or MySQLi. If you can't decide, this article will help to choose. If you care to learn, here is good PDO tutorial.

Your mysql_query() function call is failing and returning FALSE which is an invalid 1st parameter for mysql_result().
Run the mysql_query() separately and call mysql_error() to get the error.
The query is failing because COUNT (...) should be COUNT(...) otherwise it tries to find a column called count in the table.

Your query should read
SELECT COUNT(`user_id`) FROM `users` WHERE `email` = '$email' AND `email_code` = '$email_code' AND `active` = 0
Remove the space between COUNT and (user_id)

Related

Use same mysqli prepared statement for different queries?

Throughout some testings; a little question popped up. When I usually code database updates; I usually do this via callbacks which I code in PHP; to which I simply pass a given mysqli connection object as function argument. Executing all queries of for example three queries across the same single connection proved to be much faster than if closing and reopening a DB connection for each query of a given query sequence. This also works easily with SQL transactions, the connection can be passed along to callbacks without any issues.
My question is; can you also do this with prepared statement objects ? What I mean is, considering we successfully established a $conn object, representing the mysqli connection, is stuff like this legit? :
function select_users( $users_id, $stmt ) {
$sql = "SELECT username FROM users where ID = ?";
mysqli_stmt_prepare( $stmt, $sql );
mysqli_stmt_bind_param( $stmt, "i", $users_id );
mysqli_stmt_execute( $stmt );
return mysqli_stmt_get_result( $stmt );
}
function select_labels( $artist, $stmt ) {
$sql = "SELECT label FROM labels where artist = ?";
mysqli_stmt_prepare( $stmt, $sql );
mysqli_stmt_bind_param( $stmt, "s", $artist );
mysqli_stmt_execute( $stmt );
return mysqli_stmt_get_result( $stmt );
}
$stmt = mysqli_stmt_init( $conn );
$users = select_users( 1, $stmt );
$rappers = select_labels( "rapperxyz", $stmt );
or is it bad practice; and you should rather use:
$stmt_users = mysqli_stmt_init( $conn );
$stmt_rappers = mysqli_stmt_init( $conn );
$users = select_users( 1, $stmt_users );
$rappers = select_labels( "rapperxyz", $stmt_rappers );
During the testing; I noticed that the method by using a single statement object passed along callbacks works for server calls where I call like 4 not too complicated DB queries via the 4 according callbacks in a row.
When I however do a server call with like 10 different queries, sometimes (yes, only sometimes; for pretty much the same data used across the different executions; so this seems to be weird behavior to me) I get the error "Commands out of sync; you can't run this command now" and some other weird errors I've never experienced, like the amount of variables not matching the amount of parameters; although they prefectly do after checking them all. The only way to fix this I found after some research was indeed by using different statement objects for each callback. So, I just wondered; should you actually ALWAYS use ONE prepared statement object for ONE query, which you then may execute N times in a row?
Yes.
The "commands out of sync" error is because MySQL protocol is not like http. You can't send requests any time you want. There is state on the server-side (i.e. mysqld) that is expecting a certain sequence of requests. This is what's known as a stateful protocol.
Compare with a protocol like ftp. You can do an ls in an ftp client, but the list of files you get back depends on the current working directory. If you were sharing that ftp client connection among multiple functions in your app, you don't know that another function hasn't changed the working directory. So you can't be sure the file list you get from ls represents the directory you thought you were in.
In MySQL too, there's state on the server-side. You can only have one transaction open at a time. You can only have one query executing at a time. The MySQL client does not allow you to execute a new query where there are still rows to be fetched from an in-progress query. See Commands out of sync in the MySQL doc on common errors.
So if you pass your statement handle around to some callback functions, how can that function know it's safe to execute the statement?
IMO, the only safe way to use a statement is to use it immediately.

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 - at line 1

I have this issue here with my code, and cant find where the problem actually is, has anyone had similar issue?
<?php
include("db.php");
if(isset($_POST['submit']))
{
$name=$_POST['namename'];
$job=$_POST['job'];
$message=$_POST['message'];
$insert=mysql_query("insert into commenttable(name,job,message)values('$name','$job','$message')")or die(mysql_error());
header("Location:../home.php");
}
?>
this is running on localhost
Server type: MySQL
Server version: 5.5.42 - Source distribution
forgot to mention that if I post simple comment such a "Hello" it works fine, but when i try to post comment like this
<INPUT TYPE="IMAGE" SRC="javascript:alert('XSS');">
for a attack it wont work and I get the error message.
Im doing this for small attack project, this is why i need to get this to work.
Thanks!
If your code fails when you are trying to insert the text <INPUT TYPE="IMAGE" SRC="javascript:alert('XSS');"> then obviously, what is happening is what Uueerdo suggested in his comment: the single quote right before "XSS" is interpreted by MySQL as the closing single quote of the string, leaving you with a dangling XSS');', which is, of course, a syntax error.
There are two ways to overcome this problem:
Programmatically escape the single quotes. This would be quite tricky if you were to do it by yourself, but there ought to be some library function in PHP for that, so it would look like message = escape_for_sql( message ). (Sorry I am not reproducing the dollar signs, I am allergic.)
Better yet, use a parameterized query, where you construct your query using a "?" in place of each value, signifying a parameter to the query, then you supply the value for each parameter, and then you execute the query. I don't know how this is done in PHP, search for "parameterized query PHP".
To extend #Mike's answer, the correct prepared-statement PHP syntax would be, using the mysql driver:
None. Don't use the mysql driver. It's been deprecated since forever.
Using mysqli:
// You need to define the following $db_* vars elsewhere
$dbh = new mysqli($db_host, $db_user, $db_password, $db_name;)
$query = "INSERT INTO commenttable (name, job, message) VALUES (?, ?, ?)";
$stmt = $dbh->prepare($query);
$stmt->bind_param($name, $job, $message);
$stmt->execute();
// When you're finished...
$stmt->close();
Using PDO:
// Edit the connection string as appropriate for your installation
$dbh = new PDO('mysql:host=mydbhost;dbname=whatever', $db_user, $db_password);
$query = "INSERT INTO commenttable (name, job, message) VALUES (:name, :job, :message)";
$stmt = $dbh->prepare($query);
$params = array(':name' => $name, ':job' => $job, ':message' => $message);
$stmt->execute($params);
// PDO has no explicit close() call.
I leave error handling as an exercise for the reader. Hope that helps.

Perl and MYSQL - Select data between year-month-day hour:minute:seconds (unix?) style timestamps

I have looked all day for an answer and tried all my thoughts as well.
What I am doing is seemingly easy but, VERY difficult for me.
I must do this without installing additional Perl Modules.
I am trying to select a list of names that were entered between two dates.
I know these examples are obviously not strict or safe but, I am just trying to figure out.
I will fix all that later once I get the means to my required result figured out.
The incoming data example for the $to and $from:
$to= '2013-03-01 00:00:01';
$from= '2013-03-01 23:23:59';
The entered column in the database is in that format as well.
I tried:
$names = DBI->connect("$sdb","$user","$password");
$getnames = $names->prepare(qq{SELECT DISTINCT `name`
FROM `users`
WHERE `entered`
BETWEEN UNIX_TIMESTAMP($from)
AND UNIX_TIMESTAMP($to)
AND `active` = ?
AND `confirmed` = ?
ORDER BY `entered` DESC});
$getnames->execute($active,$confirmed);
And I tried:
$names = DBI->connect("$sdb","$user","$password");
$getnames = $names->prepare(qq{SELECT DISTINCT `name`
FROM `users`
WHERE `entered` BETWEEN ?
AND ?
AND `active` = ?
AND `confirmed` = ?
ORDER BY `entered` DESC});
$getnames->execute($from,$to,$active,$confirmed);
I also tried many variations of the above two but, I keep getting:
Can't call method "prepare" on an undefined value at users-by-date.pl line 120 even when I hard code the variables.
Can someone show me how to do this? My query executes fine in phpmyadmin but, I need the result printed to a page using Perl. I believe it has something to do with the dates format. NO, I cannot change the dates format in the database.
Thanks so much.
$names = DBI->connect("$sdb","$user","$password");
should be
$names = DBI->connect($sdb, $user, $password) or die "Couldn't connect to database: $!";
Adding the or die... part will serve two purposes:
1) It will stop your program immediately, preventing you from getting spurious errors later when you try to use the database handle, when the real problem is that it failed to connect to the database.
2) It will tell you why the database connection failed. (The database's error message will be in $!.)
I also removed the double quotes around the variables because they're not needed.

SQL query is correct but still a "SQL error 1064" appears

I can't deal with it. I'm experiencing big troubles with this very query:
UPDATE books
SET books.out = books.out + 1
WHERE id = 81813130;
UPDATE books
SET books.available = 0
WHERE books.in = books.out;
If I run it on my phpMyAdmin, everything's fine and everything completes, but in my CakePHP application this query doesn't work and when I perform a debug this is what I'm told:
Warning (512): SQL Error: 1064: 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 'UPDATE books SET books.available = 0 WHERE books.in = books.out' at line 1**
I'm calling my query from a controller:
$this->Lending->update_lendings($this->data['Lending']['book_id']);
and the actual query is of course into the model:
$query = "
UPDATE books
SET books.out = books.out + 1
WHERE id = ".$id.";
UPDATE books
SET books.available = 0
WHERE books.in = books.out;
";
I really can't say why this isn't working. It seems that error 1064 Mysql is a very common question in here but I didn't find anything useful about my very issue.
I steadfastly thank you for your support and help.
It looks like your problem might be due to PHP's lack of support for Multiple Statement Execution. Multiple Statement Execution allows you to run two queries in a single request and receive multiple result-sets in response.
MySQL DOES support it, but the default setup in PHP prevents this (that is, if you're using the deprecated mysql_connect() era functions). This is actually a nice default because there are some serious bugs that can be introduced by allowing multiple-queries (see SQL injection).
So, the solution could be to alter your code to request the data separately.
$query = "
UPDATE books
SET books.out = books.out + 1
WHERE id = ".$id.";";
mysql_query($db, $query);
$query = "UPDATE books
SET books.available = 0
WHERE books.in = books.out;";
mysql_query($db, $query);
That being said, if you think that it's safe enough to use multi-statements (that is, if all of the input values are sanitized), then go ahead and try to use the mysqli functions (there not even deprecated!).
mysqli_multi_query( $query ) should give you the flexibility you need.
aparently, it's because you use reserved words in your query, try and escape all table names and table columns in ``
list of reserved words in mysql available here
If the second Update statement is meant to change only the row that the first statement updated, then you could use a single Update:
UPDATE books
SET out = out + 1
, available = CASE WHEN in = out
THEN 0
ELSE available
END
WHERE id = 81813130

Update Else Insert MySQL query

Hello i was here yesterday with this problem, i don't really know how to use this site well as i am new so i reposted. but I'm getting an error with this block of code and i think its the Update query which contains a syntax error.
// Updates if player's record already exists
$result = mysql_query("UPDATE PlayerStat SET Position='$POS', Number='$NUM', Name='$PlyrName', Status='$Status', TDS='$TDS', INT='$INT', YDS='$YDS', RTG='$RTG', Team='$Team' WHERE Name='$PlyrName'");
echo mysql_error();
if (mysql_affected_rows()==0){
// Populates table if record is non existent
$result = mysql_query("INSERT INTO PlayerStat(`Position`, `Number`, `Name`, `Status`, `TDS`, `INT`, `YDS`, `RTG`, `Team`) VALUES ('$POS','$NUM','$PlyrName','$Status','$TDS','$INT','$YDS','$RTG','$Team')");
echo mysql_error();
}
The Error message
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 'INT='1', YDS='86', RTG='52.5', Team='ARI' WHERE Name='Bartel, Richard'' at line 1
INT is a keyword in mysql (declares and integer), if it's your column name you should surround it backticks (`) like so: `INT`.
It's good practice to put these in even though they're not necessary in all cases
UPDATE
PlayerStat
SET
`Position` = '$POS',
`Number` = '$NUM',
`Name` = '$PlyrName',
`Status` = '$Status',
`TDS` = '$TDS',
`INT` = '$INT',
`YDS` = '$YDS',
`RTG` = '$RTG',
`Team` = '$Team'
WHERE
`Name` = '$PlyrName'
Two things:
Check the manual for INSERT ... ON DUPLICATE KEY UPDATE which should do this in one statement.
I suggest you take a hard look at mysql_real_escape_string() or similar in PHP to escape your data and prevent SQL Injections.
If you don't know what SQL Injections are, then google it and spend a bit of time reading NOW before it's too late and some cracker or script kitty has your database.
Hope this helps!
You may want to check these websites.
http://www.w3schools.com/php/php_mysql_update.asp
http://www.tizag.com/mysqlTutorial/mysqlupdate.php
And you might also want to check your spelling mistake or the single quote or double quote. Other than that, check your database namings and data type.