将数据插入带有数组的表中

时间:2014-04-12 19:49:30

标签: php arrays database

我正在使用数组将数据插入名为tPerson的表中。如果脚本成功完成了它的作用,它将回显:

  

SQL:   INSERT INTO tPerson(Salutation,FirstName,LastName,CompanyID)价值观(Mr,Morris,Sparrow,4)(Mrs,Mary,Haslett,2)(Ms,Gill,Hennesey,1)

     

是成功的。

它的工作并没有成功并且回应:

  

SQL:   INSERT INTO tPerson(Salutation,FirstName,LastName,CompanyID)价值观(Mr,Morris,Sparrow,4)(Mrs,Mary,Haslett,2)(Ms,Gill,Hennesey,1)

     

失败。

我的代码如下:

$hostname = "localhost";
$username = "root";
$password = "";

$databaseName = "alphacrm";

$dbConnected = @mysql_connect($hostname, $username, $password);
$dbSelected = @mysql_select_db($databaseName, $dbConnected);

$dbSuccess = true;
if ($dbConnected) {
    if (!$dbSelected) {
        echo "DB connection FAILED<br><br>";
        $dbSuccess = false;
    } else {
        echo "DB connection SUCCESSFUL<br><br>";
    }
} else {
    echo "MySql connection FAILED<br><br>";
}
}

// Execute code ONLY if connections were successful

if ($dbSuccess) {

{ // setup ARRAY of field names

    $personField = array(
        "Salutation" => "Salutation",
        "FirstName" => "FirstName",
        "LastName" => "LastName",
        "CompanyID" => "CompanyID"
    );
}

{ // setup ARRAY of data ROWS

    $personData[0] = array("Mr","Morris","Sparrow","4");
    $personData[1] = array("Mrs","Mary","Haslett","2");
    $personData[2] = array("Ms","Gill","Hennesey","1");

    $numRows = sizeof($personData);
}

{ // SQL statement with ARRAYS

    //Fieldnames part of INSERT statement

    $person_SQLinsert = "INSERT INTO tPerson (
        ".$personField["Salutation"].",
        ".$personField["FirstName"].",
        ".$personField["LastName"].",
        ".$personField["CompanyID"]."
        )";

// VALUES part of INSERT statement

$person_SQLinsert .= "VALUES ";

$indx = 0;
$person_SQLinsert .= "(
    ".$personData[$indx][0].",
    ".$personData[$indx][1].",
    ".$personData[$indx][2].",
    ".$personData[$indx][3]."
    )";

$indx++;
$person_SQLinsert .= "(
    ".$personData[$indx][0].",
    ".$personData[$indx][1].",
    ".$personData[$indx][2].",
    ".$personData[$indx][3]."
    )";

$indx++;
$person_SQLinsert .= "(
    ".$personData[$indx][0].",
    ".$personData[$indx][1].",
    ".$personData[$indx][2].",
    ".$personData[$indx][3]."
    )";

}

{ // Echo and execute the SQL and test for success

    echo "<strong><u>SQL:<br></u></strong>";
    echo $person_SQLinsert."<br><br>";

    if (mysql_query($person_SQLinsert)) {
        echo "was SUCCESSFUL.<br<br>";
    } else {
        echo "FAILED.<br><br>";
    }
}
} // END ($dbSuccess)

?>

所有的帮助都将受到赞赏,因为我很难理解为什么我的剧本不起作用。

1 个答案:

答案 0 :(得分:0)

就像@mysql_select_db用于@mysql_query而不是这个mysql_query一样。 还检查了你的mysql连接和数据库连接是否成功。

您对多行的查询必须采用此格式 &#34; INSERT INTO表(Column1,Column2)VALUES(Value1,Value2),(Value1,Value2);&#34;

打印您的查询并使用此语法进行检查。