简体   繁体   English

SQL从数组插入值

[英]SQL Insert value from array

So I am working on some code that inserts a piece of text and an id into a table. 因此,我正在研究一些将一个文本和一个id插入表中的代码。 I send the code the text and the user's name. 我向代码发送文本和用户名。 I want to take the username, and select the id that corresponds to it from the users table. 我要使用用户名,然后从用户表中选择与其对应的ID。 I then insert that into the text table. 然后,我将其插入文本表。

I have tried this: 我已经试过了:

$id = mysql_query("SELECT users.id FROM users WHERE name='$username'");

mysql_query("INSERT INTO `shouts` (`id`, `user`, `text`, `datetime`) VALUES (NULL, '$id', '$text', '$datetime');");

But it does not work, because the variable $id holds sql data. 但这不起作用,因为变量$id保存sql数据。 How can i turn that data into and integer? 如何将数据转换为整数?

From the manual : 手册

The returned result resource should be passed to mysql_fetch_array(), and other functions for dealing with result tables, to access the returned data. 返回的结果资源应传递到mysql_fetch_array()和其他用于处理结果表的函数,以访问返回的数据。

Also from the manual: 同样从手册中:

Use of this extension is discouraged. 不鼓励使用此扩展名。 Instead, the MySQLi or PDO_MySQL extension should be used. 相反,应使用MySQLi或PDO_MySQL扩展。

To answer your question, try this: 要回答您的问题,请尝试以下操作:

$id = mysql_query("SELECT users.id FROM users WHERE name='$username'");
$id = mysql_fetch_assoc($id);
mysql_query("INSERT INTO `shouts` (`id`, `user`, `text`, `datetime`) VALUES (NULL, '". $id['id']."', '$text', '$datetime');");

Although this is a Bad Idea™ and you should really look into using PDO . 尽管这是一个Bad Idea™,但您应该真正考虑使用PDO It's really not that hard. 其实并不难。 It will provide you with the ability to prepare your SQL statements, making you really be able to sleep easier at night knowing that you're not going to be a victim of SQL injection. 它将为您提供准备SQL语句的能力,从而使您知道自己不会成为SQL注入的受害者,从而真正能够在晚上轻松入睡。 The code you have is ambiguous at best whether or not you already are a victim yourself. 无论您是否已经成为受害者,您拥有的代码充其量都是模棱两可的。

try $id = addslashes($id); 尝试$id = addslashes($id); or any other method of encoding the sql string 或任何其他编码sql字符串的方法

$id $ id

is going to contain your results you need to get the id and put that into a variable. 要包含您的结果,您需要获取ID并将其放入变量中。 Check out the mysql_fetch_row function I think that will get you what you want. 签出mysql_fetch_row函数,我认为这将为您提供所需的东西。 mysql_fetch_row syntax mysql_fetch_row语法

mysql_query never returns a normal variable, only a result resource. mysql_query从不返回普通变量,仅返回结果资源。 Try mysql_fetch_assoc to get the data out of the select query. 尝试mysql_fetch_assoc从选择查询中获取数据。 Also, the MySQL php extension is deprecated and you are encouraged to move to MySQLi or PDO. 另外,不建议使用MySQL php扩展,建议您改用MySQLi或PDO。

this should work 这应该工作

   $sql = mysql_query("SELECT users.id FROM users WHERE name='$username'");
    $id = mysql_fetch_array($sql)['id'];

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

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