简体   繁体   中英

How do I store the results of an SQL call in a php array

I have been trying to create a sign up form for a website and I keep struggling with trying to check if a user's username had been used by someone else who signed up for the website in the past. I am using a Mysql database to store information and am trying to access past usernames through it using php. This specific part of my code keeps returning an error.

$query = "SELECT username FROM users";
$records = mysql_query("SELECT username FROM users");
$result = mysql_query($records);

$result_array = array();
while($row = mysql_fetch_assoc($result))
{
    $result_array[] = $row['username'];
}

The error messages I am receiving are:

  1. Warning: mysql_query() expects parameter 1 to be string, resource given in ...
  2. Warning: mysql_fetch_assoc() expects parameter 1 to be resource, null given in... thank you so much!

The problem is you are doing mysql_query twice one on the $records variable and then on resultlike so:

$records = mysql_query("SELECT username FROM users");
$result = mysql_query($records);

What you need to do is this:

$records = "SELECT username FROM users";
$result = mysql_query($records);

I hope the answer by Jack Smith was helpful. I'll just add that try to use mysqli_query as mysql is deprecated and may be removed in a newer version of php. You would also need to use mysqli_connect('host','usrname','password','database') instead of mysql_connect.

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