简体   繁体   English

如何将SQL调用的结果存储在php数组中

[英]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. 我正在使用Mysql数据库存储信息,并尝试使用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 ... 警告:mysql_query()期望参数1为字符串,资源在...
  2. Warning: mysql_fetch_assoc() expects parameter 1 to be resource, null given in... thank you so much! 警告:mysql_fetch_assoc()期望参数1为资源,在其中给出null……非常感谢!

The problem is you are doing mysql_query twice one on the $records variable and then on resultlike so: 问题是您在$records变量上执行了mysql_query两次,然后在resultlike上进行了两次:

$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. 我将添加尝试使用mysqli_query的信息,因为不推荐使用mysql,并且可能在较新版本的php中将其删除。 You would also need to use mysqli_connect('host','usrname','password','database') instead of mysql_connect. 您还需要使用mysqli_connect('host','usrname','password','database')代替mysql_connect。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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