为什么我的mysqli_fetch_assoc没有抓取行信息,所以我可以在我的表中插入细节?

时间:2017-04-29 08:30:03

标签: php mysqli

首先,我知道sql注入并且我的代码不是万无一失,容易注入等等。接下来会继续工作。

现在:从我的Android应用程序到我的PHP文件,我提交了一个JSON数组的电话号码,如:

[{"phone_number":"+12345678"},
 {"phone_number":"+23456789"},
 {"phone_number":"34567890"},
 {"phone_number":"45678901"} 
 etc... etc...

这些是我的应用用户手机中的联系人。如果这些联系人也是我的应用的用户,那么我想将这些数字插入我的contacts表格。

但我无法让它发挥作用。 mysqli_fetch_assoc无法正常运作。我不知道为什么。

在我的contacts表中,我有3列 - auto incrementuser_idcontact_id。前两个值已正确插入,但contact_id始终输入为' 0',这是错误的。

这是我的代码:

require('dbConnect.php');

//this is me, +567890123, my user_id in the user table
$user_id = '20';

//post all contacts in my phone as a JSON array
$json  = $_POST['phonenumber'];
$array = json_decode($json);

foreach ($array as $value) {
    $phonenumber = $value->phone_number;

    $sql      = "SELECT username FROM user WHERE username = '$phonenumber'";
    $result   = mysqli_query($con, $sql);
    $num_rows = mysqli_num_rows($result);

    if ($num_rows > 0) {
        echo "phonenumber is " . $phonenumber . "<br>";

        // we want to put $phonenumber in the contacts table, as one of +567890123 contacts
        // In the user table get the associated rows of $phonenumber
        while ($row = mysqli_fetch_assoc($result)) {
        // get the associated user_id in that row, that's what we want to put into the contacts table
            $contact_id                   = $row['user_id'];
            $insert_into_contacts_command = "INSERT INTO contacts VALUES(NULL, '$user_id','$contact_id')";
            $insert_into_contacts_table   = mysqli_query($con, $insert_into_contacts_command);
        }

    } //if +353864677745 is NOT in the user table...
    else {

        echo 'not a match.';
    }
}

2 个答案:

答案 0 :(得分:2)

$contact_id = $row['user_id'];

此处$contact_id将为null,因为您尝试访问$row['user_id']的现有字段$row

实际上,您指定的结果集中只有一个字段username

$sql = "SELECT username FROM user WHERE username = '$phonenumber'";

尝试将您的查询更改为:

$sql = "SELECT user_id, username FROM user WHERE username = '$phonenumber'";

答案 1 :(得分:1)

您的查询会选择username列,而不是userid

您尚未发布有关表格user的任何内容,因此很难建议新的查询,但我想其中包含以下内容:

$stmt = mysqli_prepare($con, "SELECT userid FROM user WHERE username = ?");
$stmt->bind_param("s", $phonenumber);
$stmt->execute();
$stmt->bind_result($userid);

while ($stmt->fetch()) {
    // Work with $userid
}

您将注意到这使用带有绑定参数的预准备语句。这样,您的代码就不容易进行SQL注入。