Question:
Problem with my php code: Warning: mysql_fetch_row(): supplied argument is not a valid MySQL result resource?
anonymous
2014-08-21 12:33:41 UTC
Hello, I am having a problem with my code. I am making a registration system and this happens.

Here is my code:


if($message == NULL)
{
$userQuery = mysql_fetch_row(mysql_query("SELECT COUNT(*) FROM `$tableName`
WHERE `$userNameField`='$userName'"));
if($userQuery[0] > 0){
$message = 'This username already exists. Please select another.';
} else {
/* Add user */
$addUser = mysql_query("INSERT INTO `$tableName` (`$userNameField`,`$userPasswordField`)
VALUES ('$userName','$password')");
if($addUser)
{
/* Disconnect from database */
if($connectDatabase == TRUE){$action=FALSE;include('connect.php');}

/* Log use in */
$_SESSION['isLoged'] = 'yes';
$_SESSION['userName'] = $userName;
/* add cookies ?*/
/* expire in 1 hour */
if($useCookies == TRUE)
{
setcookie("isLoged", 'yes', time()+logedInFor, "/", ".$domainName", 1);
setcookie("userName", $userName, time()+logedInFor, "/", ".$domainName", 1);
}


Thanks for any help
Four answers:
Matt
2014-08-21 13:29:12 UTC
Well this could mean:



- Your query is wrong so it is not able to fetch a record.

- Your database is not connected properly so it's not able to execute the query.



Try doing some debugging using var_export();.



P.S. You should be using MySQLi or PDO. MySQL is deprecated.
Chris
2014-08-21 22:48:15 UTC
Disregarding the security concerns here: you should never pass an expected result directly into further processing.

Always use an intermediate step:



$result = mysql_query("SELECT COUNT(*) FROM $tableName WHERE $userNameField = '$userName';");

if (!$result) die(mysql_error());

// query was successful, continue here
just "JR"
2014-08-22 06:34:55 UTC
Incorrect syntax Your query fails.

For clarity, separate your queries:

$sql = "SELECT COUNT(*) FROM `".$tableName."` WHERE `".$userNameField."`='".$userName."'";

$res = mysql_query($sql) or die (mysql_error());

expanded for readability:

` " . $tableName . " ` and

` " . $userNameField . " ` = ' " . $userName . " ' ";

The "risks" are that tablename, usernamefield and username MAY contain special characters, such as `, ', ", _ etc which will crash your query. Typical example here: my name contains double quotes and is never displayed correctly... :-)
God
2014-08-21 22:32:22 UTC
STOP RIGHT THERE.

You are opening the system to SQL injection. Use a stored procedure instead, NEVER, EVER DIRECT SQL.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...