I want to dynamically add the values in database which contains the foreign key, using PHP prepare and execute statement. I have concatenated the variable of SQL "SELECT" query but it gives me following error, 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
.
Here is my source code:
//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);
}
}
?>
Note: It gives error to concatenated SQL query, in 'setCity.php' page on line no 6.