无法使用php中的prepare和execute语句动态地在数据库中插入数据

时间:2018-06-04 19:48:28

标签: php mysql

我想使用PHP prepare和execute语句在包含外键的数据库中动态添加值。我已经连接了SQL“SELECT”查询的变量但是它给了我以下错误Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting '-' or identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in C:\xampp\htdocs\app\php\setCity.php on line 6 这是我的源代码:

//index1.php
<?php 
include 'php/connect.php';
include 'php/setState.php';
include 'php/setCity.php';
?>

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Welcome | Admin panel</title>
</head>
<body>
    <form action="index1.php" method="POST">
        <br><b>Enter State Name: </b><input type="text"     name="state_name"><br>
        <br><b>Enter City Name: </b><input type="text" name="city_name"><br>
        <input type="submit" name="submitNames" value="Update to database">
    </form>
</body>
</html>


//setCity.php

<?php
include 'connect.php';

if (isset($_POST['submitNames'])) 
{
    $stateid = "SELECT state_id FROM state WHERE state_name =            .$_POST['state_name'].;";
    $cityname = mysqli_real_escape_string($_POST['city_name']);
    $sql = "INSERT INTO city (state_id, city_name) VALUES (?,?);";
    $stmt = mysqli_stmt_init($conn);
    if (!mysqli_stmt_prepare($conn, $sql)) 
    {
        echo "SQL ERROR OCCURED";
    }
    else
    {
        mysqli_stmt_bind_param($stmt, "is", $stateid ,$cityname);
        mysqli_stmt_execute($stmt);
    }
}

?>

//setState.php

<?php
include 'connect.php';

if (isset($_POST['submitNames'])) 
{
    $data = mysqli_real_escape_string($conn, $_POST['state_name']);
    $sql = "INSERT INTO state(state_name) VALUES (?);";
    $stmt = mysqli_stmt_init($conn);
    if (!mysqli_stmt_prepare($stmt, $sql)) 
    {
        echo "SQL ERROR.";
    }
    else
    {
        mysqli_stmt_bind_param($stmt, "s", $data);
        mysqli_stmt_execute($stmt);
    }
}
?>

注意:在第6行的'setCity.php'页面中,它给连接的SQL查询带来错误。

0 个答案:

没有答案