我有一些例子,但我无能为力。我有下面的代码,回声工作,但插入没有。我相信我应该爆炸这些?不确定,但也许有人可以给我一个有关我自己的例子的提示。

$con=mysqli_connect(localhost,"username","password","db");


// Check connection
if (mysqli_connect_errno())
 {
 echo "Failed to connect to MySQL: " . mysqli_connect_error();
 }

$deletetable = $con->prepare('TRUNCATE TABLE twitch_streams');
$deletetable->execute();
$deletetable->close();

$result = $con->prepare("SELECT field_value
FROM xf_user_field_value
WHERE field_id = 'twitch'
AND field_value != ''");

$result->bind_result($twitchfield);

while($result->fetch())
{
printf("%s\n", $twitchfield);
$username[] = $twitchfield;
$data =    json_decode(file_get_contents('http://api.justin.tv/api/stream/l   ist.json?channel=' . $username[0]));
$viewer[] = $data[0]->channel_count;


$insert = $con->prepare("INSERT INTO twitch_streams (twitchuser, viewercount)
VALUES (?, ?)");
$insert = bind_param('si', $twitchuser, $viewercount);

$twitchuser = $username[0];
$viewercount = $viewer[0];

$insert->execute();

echo $twitchuser;
echo $viewercount;
$insert->close();
  }

$result->close();$deletetable = $con->prepare('TRUNCATE TABLE twitch_streams');
$deletetable->execute();
$deletetable->close();

$result = $con->prepare("SELECT field_value
FROM xf_user_field_value
WHERE field_id = twitch
AND field_value != ''");

$result->bind_result($twitchfield);

while($result->fetch())
  {
   printf("%s\n", $twitchfield);
   $username[] = $twitchfield;
   $data =    json_decode(file_get_contents('http://api.justin.tv/api/stream/l   ist.json?      channel=' . $username[0]));
$viewer[] = $data[0]->channel_count;


$insert = $con->prepare("INSERT INTO twitch_streams (twitchuser, viewercount)
VALUES (?, ?)");
$insert = bind_param('si', $twitchuser, $viewercount);

$twitchuser = $username[0];
$viewercount = $viewer[0];

$insert->execute();

echo $twitchuser;
echo $viewercount;
$insert->close();
  }

$result->close();
mysqli_close($con);

最佳答案

您在字符串值周围缺少引号:

"INSERT INTO twitch_streams (twitchuser, viewercount)
VALUES ($username[0], $viewer[0])"


应该

"INSERT INTO twitch_streams (twitchuser, viewercount)
VALUES ('$username[0]', '$viewer[0]')"


如果将错误处理添加到代码中,则很容易发现此错误。查看使用mysqli_error()

$result = mysqli_query($con,"INSERT INTO twitch_streams (twitchuser, viewercount)
VALUES ('$username[0]', '$viewer[0]')");
if (!result) {
    // This should be done better than this
    echo mysqli_error();
    exit;
}


由于我无法从您的代码中分辨出$data[0]->channel_count的来源,因此我也将提到您至少应使用mysqli_real_escape_string()转义插入变量。更好的是使用prepared statements

关于php - 数组到MYSQL,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22252413/

10-11 10:47