Why does the following SELECT statement not run? [duplicate] - php

This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 3 years ago.
The following code intends to select a value from a table in a
database, use the selected value to change a variable, and then add
that variable to another table in the database. However, I cannot
figure out why it doesn't work - the $entry query runs, but the
application doesn't recognize the $sql query for some reason. Can
anyone help me, please?
$sql = "SELECT calories FROM food WHERE name = $food";
$result = $conn->query($sql);
if ($serving_size == 'Plate'){
$calories = $amount * $result;
}
if ($serving_size == 'Bowl'){
$calories = $amount * $result * 2/3;
}
$entry = $conn->prepare("INSERT INTO data (`Food/Exercise`, `Quantity`, `Calories_Burned_or_Consumed`, `Number_of_Calories`) VALUES (?, ?, ?, ?)");
$entry->bind_param("sssi", $food, $quantity, $consumed, $calories);
if($entry->execute()){
echo 'Inserted';
} else {
echo 'Not Inserted';
}

Is $food actually defined, and is it quoted? If there are no quotes around the string it will be considered a column name here and the query will not match anything.
This query actually is prone to SQL injections, params should be used just like you do below.

Related

PHP PDO mysql query to work with both column = '$var' and column IS NULL [duplicate]

This question already has an answer here:
Write a prepared statement with nullable values in conditions
(1 answer)
Closed 2 years ago.
I have a quite long mysql query, selecting data according to status field. I'm calling it for different statuses and it works well, but I have a scenario when I should get all records where status is null ONLY. Is there a way to do this without having to write 2 different sql queries?
Looks like I can't insert 'IS NULL' or '=' without it being rendered as a string.
I want to achieve this:
$sql = "SELECT name, surname FROM ...
...
WHERE status ?;";
$stmt = $pdo->prepare($sql);
$stmt->execute(array($status === 'undefined' ? 'IS NULL' : " = '$status'"));
After all, here's what I did:
$sql = "SELECT name, surname FROM ...
...
WHERE status <=> ?;";
$stmt = $pdo->prepare($sql);
$stmt->execute(array($status === 'unfinished' ? null : $status));
Using parameterised queries, as indicated, is a safer way of introducing user input into your SQL statements. However, it has the effect of treating all input as a parameter, and therefore will surroung any string literals with quotes - giving rise to the problem you have.
To deal with this issue, why not just modify the logic of the code:
$sql = "SELECT name, surname FROM ...
...
WHERE status";
if ($status === 'undefined') {
$sql .= " IS NULL";
$stmt = $pdo->prepare($sql);
$stmt->execute();
} else {
$sql .= " = ?"
$stmt = $pdo->prepare($sql);
$stmt->execute(array($status));
}
Edit
Updated to move the execution into the relevant part of the if statement becuase the parameters must not be specified if there is no placeholder in the SQL statement.

simple update and insert mysqli in php code can not be executed [duplicate]

This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 5 years ago.
This little piece of code should be very easy basic coding, yet it doesn't work. The problem is within the INSERT / UPDATE code, because if I delete those and just echo simple text inside of the if/else code everything works just fine.
This is the code I have, whichs gives a HTTP ERROR 500.
$sql2 = mysqli_query($mysqli, "SELECT * FROM koppel WHERE userid = ".$_GET['userid']." AND msgid = ".$_GET['msgid']."");
$row = mysqli_fetch_assoc($sql2);
$check = $_GET['check'];
$msgid = $_GET['msgid'];
$userid = $_GET['userid'];
$ja = 'ja';
$nee = 'nee';
$tabel_content = $row['check'];
$tabel_id = $row['id'];
if ($tabel_content == $ja){
$stmt = $mysqli->prepare("UPDATE koppel SET check = ? WHERE id = ?");
$stmt->bind_param('si',
$nee,
$tabel_id);
$stmt->execute();
$stmt->close();
} elseif ($tabel_content == $nee){
$stmt = $mysqli->prepare("UPDATE koppel SET check = ? WHERE id = ?");
$stmt->bind_param('si',
$ja,
$tabel_id);
$stmt->execute();
$stmt->close();
} else {
$stmt = $mysqli->prepare("INSERT INTO koppel(userid,
msgid,check) VALUES (?, ?, ?)");
$stmt->bind_param('iis', $userid,
$msgid,
$check);
$stmt->execute();
$stmt->close();
}
What am I missing?
I don't see any error there, but make sure $mysqli is a valid mysqli connection to your database.
To debug your problem, try checking your server error logs (they will show the cause of your 500 error, and in which line) or try removing each part of your code until you understand exactly which line is failing.
You can also move all your "execute" and "close" calls to be below the if/elseif/else structure, as it always gets executed, to avoid repeating code.
Also "tabel" should be spelled "table".

How to keep temporary mysqli table available in php during statement execution?

I am busy trying to execute a set of statements that involve the use of a temporary table.
My goal is to create the temporary table, insert values to it and then do a like comparison of the temporary tables contents to another table.
These statements are working perfectly in phpmyadmin when executed from RAW SQL, but I'm assuming that the table is not available when I try to insert the data.
Below is the code for my php function + mysqli execution:
function SearchArticles($Tags){
global $DBConn, $StatusCode;
$count = 0;
$tagCount = count($Tags);
$selectText = "";
$result_array = array();
$article_array = array();
foreach($Tags as $tag){
if($count == 0){
$selectText .= "('%".$tag."%')";
}else {
$selectText .= ", ('%".$tag."%')";
}
$count++;
}
$query = "CREATE TEMPORARY TABLE tags (tag VARCHAR(20));";
$stmt = $DBConn->prepare($query);
if($stmt->execute()){
$query2 = "INSERT INTO tags VALUES ?;";
$stmt = $DBConn->prepare($query2);
$stmt->bind_param("s", $selectText);
if($stmt->execute()){
$query3 = "SELECT DISTINCT art.ArticleID FROM article as art JOIN tags as t ON (art.Tags LIKE t.tag);";
$stmt = $DBConn->prepare($query3);
if($stmt->execute()){
$stmt->store_result();
$stmt->bind_result($ArticleID);
if($stmt->num_rows() > 0){
while($stmt->fetch()){
array_push($article_array, array("ArticleID"=>$ArticelID));
}
array_push($result_array, array("Response"=>$article_array));
}else{
array_push($result_array, array("Response"=>$StatusCode->Empty));
}
}else{
array_push($result_array, array("Response"=>$StatusCode->SQLError));
}
}else{
array_push($result_array, array("Response"=>$StatusCode->SQLError));
}
}else{
array_push($result_array, array("Response"=>$StatusCode->SQLError));
}
$stmt->close();
return json_encode($result_array);
}
The first statement executes perfectly, however the second statement gives me the error of:
PHP Fatal error: Call to a member function bind_param() on a non-object
If this is an error to do with the Temp table not existing, how do i preserve this table long enough to run the rest of the statements?
I have tried to use:
$stmt = $DBConn->multi_query(query);
with all the queries in one, but i need to insert data to one query and get data from the SELECT query.
Any help will be appreciated, thank you!
You have a simple syntax error use the brackets around the parameters like this
INSERT INTO tags VALUES (?)
This is not an issue with the temporary table. It should remain throughout the same connection (unless it resets with timeout, not sure about this part).
The error is that $stmt is a non-object. This means that your query was invalid (syntax error), so mysqli refused to create an instance of mysqli_stmt and returned a boolean instead.
Use var_dump($DBConn->error) to see if there are any errors.
Edit: I just noticed that your query $query2 is INSERT INTO tags VALUES ? (the ; is redundant anyway). If this becomes a string "text", this would become INSERT INTO tags VALUES "text". This is a SQL syntax error. You should wrap the ? with (), so it becomes INSERT INTO tags VALUES (?).
In conclusion, change this line:
$query2 = "INSERT INTO tags VALUES ?;";
to:
$query2 = "INSERT INTO tags VALUES (?);";
also note that you don't need the ; to terminate SQL statements passed into mysqli::prepare.

How to insert an array into database [duplicate]

This question already has answers here:
How do I insert an array of values into different columns of a mysql table?
(3 answers)
Closed 7 years ago.
$rate=[10,20,40,50,70];
How do I insert the value in below query?
$sql="INSERT INTO rental(day_1,day_3,day_7,day_15,day_30)
VALUES('{$rate[0]}','{$rate[1]}', '{$rate[2]}','{$rate[3]}','{$rate[4]}')";
$stmt =connection::$pdo->prepare($sql);
$stmt->execute();
I tried below but it inserts same value in all column for a record and creates new record for each new value:
foreach($rate as $key->$value)
{
$sql="INSERT INTO rental(day_1,day_3,day_7,day_15,day_30)
VALUES('{$value}','{$value}', '{$value}','{$value}','{$value}')";
$stmt =connection::$pdo->prepare($sql);
$stmt->execute();
Edited based on answer given
public function rentalRate()
{
$rate = implode("','",$this->rate);
$sql = "INSERT INTO rental(day_1,day_3,day_7,day_15,day_30)VALUES('$rate')";
$stmt =connection::$pdo->prepare($sql);
$stmt->execute();
unset($rate);
}
Simply use implode and that's it
$rate = [10,20,40,50,70];
$rate = implode("','",$rate);
$sql = "INSERT INTO rental(day_1,day_3,day_7,day_15,day_30)VALUES('$rate')";
echo $sql;
Foreach is not useful in this case, because you want to integrate more than one array element in one query and you do not have a multidimensional array. Just use your first query:
$sql = "INSERT INTO rental(day_1,day_3,day_7,day_15,day_30)VALUES('{$rate[0]}','{$rate[1]}', '{$rate[2]}','{$rate[3]}','{$rate[4]}')";
And - if you really want to use foreach:
$sql = "INSERT INTO rental(day_1,day_3,day_7,day_15,day_30)VALUES(";
foreach($rate as $value)
$sql .= "'$value', ";
$sql = rtrim($sql, ", ") . ")";
just simple (note implode will only work with integers, without need to quoate)
$rate=[10,20,40,50,70];
$r_sql = '';
foreach($rate as $r) {
$r_sql.="'$r',";
}
$r_sql = trim($r_sql,',');
$sql="INSERT INTO rental(day_1,day_3,day_7,day_15,day_30)VALUES(".$r_sql.")";
Normally arrays are inserted into a different table and all tools are geared towards this. It is usually better not to fight the tools or it is likely to run into unforseen problems.
If we add a
table rental_day(id(int), rental_id(int,fk), rate(money))
Then for all the items in the array we just insert the item into one row in rental_day
later when we need the info back we can query for it like
select * from rental_day d inner join rental r on d.rental_id=r.id where r.id=something
and you will get all the info from rental_day and rental in one query.

PDO:: Confusion [duplicate]

This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 7 years ago.
I have no idea why this is not returning anything. I'll show the code and talk through the steps I've taken.
if (isset($_GET['observation'])) {
require_once("../func/connect.php");
$query = "SELECT * FROM observations WHERE option = ?";
$stmt = $db->prepare($query);
$stmt->bindValue(1, $_GET['observation']);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
echo $row['question'];
} else {
echo 'nope';
}
$row dumps a false boolean, $row['question'] is null.
I've wrote about a million queries and don't have a clue why this doesn't work.
Database table observations consists of id, question & option and the bindValue is correct to match a string in the database.
However, it returns null.
option is a reserved word in mysql so you need to quote it with backticks:
$query = "SELECT * FROM observations WHERE `option` = ?";

Categories