无法从PHP插入Mysql数据库

时间:2015-08-16 22:08:01

标签: php mysqli

以下代码为变量$ insertStatement生成一些整数值,所以insert语句失败我已经尝试了很长时间但无法弄清楚问题的原因任何人都会感激:)

<?php
$con=mysqli_connect("localhost","root","","loadtest");

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

if( $_GET["value"] != null ||  $_GET["value"]!="" )
{
    $rand=uniqid();
    $insertStatement="";
    date("m-d-y");
    for($i=0;$i<$_GET["value"];$i++){
        $insertStatement +="insert into test values('"+$date+"','"+$rand+"','column1','column2','column3','column4','column5','column6','column7','column8','column9','column10');";
    }
    echo $insertStatement;
    mysqli_query($con,$insertStatement)or die("cannot insert");
    mysqli_close($con);
    echo "<p style=\"color:Green\">Inserted</p>";
}

else{
    echo "couldn't insert";
}
?>

2 个答案:

答案 0 :(得分:1)

改变这个:

$insertStatement +="insert into test values('"+$date+"','"+$rand+"','column1','column2','column3','column4','column5','column6','column7','column8','column9','column10');";

对此:

$insertStatement .="insert into test values('" . $date . "','" . $rand . "','column1','column2','column3','column4','column5','column6','column7','column8','column9','column10');";

要在PHP中连接字符串,请使用.

echo "a" + "b"; // outputs 0
echo "a" . "b"; // outputs "ab"

阅读:http://php.net/manual/en/language.operators.string.php

答案 1 :(得分:0)

作为Barriel状态,您必须使用.运算符而不是+将php中的字符串连接起来。 除了他的答案,你可能想要为变量$date分配一些东西。我假设您可能还想为每个条目更改$rand的值?

$date = date("m-d-y");
for ($i=0; $i<$_GET["value"]; $i++) {
    $rand = uniqid();
    $insertStatement .= "insert into test values('" . $date . "','" . $rand . "','column1','column2','column3','column4','column5','column6','column7','column8','column9','column10');";
}

另外,检查$_GET['value']内容的if条件没有多大意义。考虑将其改为

if (is_numeric($_GET['value'])) { ...