错误:数组到字符串转换错误

时间:2017-06-29 07:53:11

标签: php mysql sql arrays string

首先,我随机选择了我桌上的ID。那部分工作正常,但下一部分没有。下一部分是选择ID的行,例如如果ID为6,则应选择与6相关的所有字段。

我的桌子是这样的:

------------------------------
|ID|Name|Email      |Password|
------------------------------
|1 |Amy |H@gmail.com|jaaaaaaa|
------------------------------
|2 |Bob |1@gmail.com|haaukanm|
------------------------------
|3 |Bill|aa@mail.com|fsoji443|
------------------------------

这是我的代码:

<?php
include('connect.php');

//select a number between min id and max id
$v = "SELECT ID FROM `tblaccounts` ORDER BY RAND() LIMIT 1";
$result = mysqli_query($connection, $v);
$data2 = mysqli_fetch_array($result);
//var_dump($data2);

$c = "SELECT * FROM `tblaccounts` WHERE ID='$data2'";
$cresult = mysqli_query($connection, $c);
$data3 = mysqli_fetch_array($cresult);
var_dump($data3);
?>

3 个答案:

答案 0 :(得分:4)

问题在于:

$c = "SELECT * FROM `tblaccounts` WHERE ID='$data2'";

这里$data2不是单个值,它是一个数组,你试图在WHERE中将它与字符串进行比较,这就是错误的原因。而是尝试$data2['id']喜欢:

$c = "SELECT * FROM `tblaccounts` WHERE ID='".$data2['ID']."'";

$c = "SELECT * FROM `tblaccounts` WHERE ID=".$data2['ID'];  // Sinlge quote is not required if `ID` is `int`

答案 1 :(得分:1)

因为您的$data2是一个数组,所以应该可以使用

include('connect.php');

//select a number between min id and max id
$v = "SELECT ID FROM `tblaccounts` ORDER BY RAND() LIMIT 1";
$result = mysqli_query($connection, $v);
$data2 = mysqli_fetch_array($result);

//var_dump($data2);
$c = "SELECT * FROM `tblaccounts` WHERE ID='".$data2['ID']."'";
$cresult = mysqli_query($connection, $c);
$data3 = mysqli_fetch_array($cresult);
var_dump($data3);

答案 2 :(得分:0)

您在比较array时遇到了这个错误。 您的$ data是一个如下所示的数组

$data = array(
             'ID'=>2
             'Name'=>'Bob',
             'Email'=>'1@gmail.com',
             'Password'=>'haaukanm'

       );// say record with id 2 is fecthed

因此在where子句中使用$data['ID']