简体   繁体   中英

PHP mysql fetch array error

  Warning: mysql_fetch_array() expects parameter 1 to be resource, string given in C:\xampp\htdocs\arun\login.php on line 9

Code:

$db_select = mysql_select_db('my_db', $con);
$username = $_GET['username'];
$password = $_GET['password'];
$role = $_GET['role'];
$result = mysql_query("Insert into  table1(Username,Password,Role) values (Username='$username', Password='$password',Role='$role') ",$con);
$row = mysql_fetch_array($result);

if ( mysql_error() )
 {
  die ( mysql_error());
}
$row_PK = mysql_fetch_assoc($row);
mysql_close($con);
?>

Replace

$result = mysql_query("Insert into  table1(Username,Password,Role) values (Username='$username', Password='$password',Role='$role') ",$con);

with

$result = mysql_query("Insert into  table1(`Username`,`Password`,`Role`) values ('$username', '$password','$role') ",$con);

You don't have to assign the value to the column on your INSERT query as you have done. Just map the values as shown above.

Apart from the above issues... Dissecting your code ..

The main issue with your code is you are doing an INSERT but you are expecting a resultset as you have done a SQL SELECT which is wrong.

You need to change your code like this..

The below code is just an illustration to tell you what you had done was actually wrong. Do not use this code ! You first need to migrate to the latest database API provided for you in the side note section.

$db_select = mysql_select_db('my_db', $con);
if(isset($_GET['username'],$_GET['password'],$_GET['role']))
{
$username = mysql_real_escape_string($_GET['username']);
$password = mysql_real_escape_string($_GET['password']);
$role =     mysql_real_escape_string($_GET['role']);
$result = mysql_query("Insert into  table1(`Username`,`Password`,`Role`) values ('$username', '$password','$role') ",$con);
if (!$result)
{
    die (mysql_error());
}
else
{
    echo "Record Inserted";
}
mysql_close($con);
}

SideNote

The ( mysql_* ) extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead,the MySQLi or PDO_MySQL extension should be used. Switching to PreparedStatements is even more better to ward off SQL Injection attacks !

For a INSERT query the return value isn't a resource, it's a TRUE on success or FALSE on error.

A resource is returned for a SELECT, SHOW, DESCRIBE or EXPLAIN query.

这是您的解决方案,将您的查询更改为

$result = mysql_query("Insert into table1(Username,Password,Role) values ('$username', '$password','$role') ",$con);

your query should be like this

$result = mysql_query("Insert into  table1(Username,Password,Role) values ('$username', '$password','$role') ",$con);

NOTE: mysql_* is deprecated use mysqli_* OR PDO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM