Reputation: 285
In my app data is fetched from a database. For that a variable is passed to a php script and should be used in the query later. I tried it using $var = $_POST['name']
in the query, but it seems like the passed variable is empty.
To test it, I inserted the variable into a table and used the isset()
method as well. The first part works as it should, the variable is set and inserted, but in the second part with the query to fetch the data it doesn’t seem to be set since the variable returns the value „a“. Why is the value not set and not taken from above?
The php code:
<?php
include Connection.php;
$conn = new mysqli($servername, $username, $password, $dbname);
if(isset($_POST['name'])){
$query = "INSERT INTO TestTable (name) VALUES ('$_POST[name]')";
if(mysqli_query($conn,$query)){
echo 'Data Submit Successfully';
}
else{
echo 'Try Again';
}
}
if(!isset($_POST['name'])){
$var = "a";
}
$query = "SELECT * FROM TestTable WHERE name = '$var'";
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_assoc($result)) {
$array[] = $row;
}
header('Content-Type:Application/json');
echo json_encode($array);
mysqli_close($conn);
?>
Upvotes: 2
Views: 86
Reputation: 1374
Your query string is incorrect, fix by this:
//...
$query = "INSERT INTO TestTable (name) VALUES ('".$_POST['name']."')";
//...
To fix SELECT
query you should initialize $var in case isset($_POST['name'])
returns true
//...
$var = "a";
if(isset($_POST['name'])){
$var = $_POST['name'];
}
$query = "SELECT * FROM TestTable WHERE name = '$var'";
Upvotes: 2
Reputation: 792
In the code
if(!isset($_POST['name'])){
$var = "a";
}
$query = "SELECT * FROM TestTable WHERE name = '$var'";
change this to
$var = "";
if(!isset($_POST['name'])){
$var = "a";
}
$query = "SELECT * FROM TestTable WHERE name = '$var'";
Upvotes: 2