I got mysqli error 1064 but i don't know why - php

I want to post this data from android client and i tested it with postman and status code was 200. But i have a mysqli error and it's:
Error:
((1064) You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'WHERE id=' at line 1)
i don't know what is my codes problem and SELECT part works correctly
<?php
$id = $_POST['id'];
$isLiked = $_POST['isLiked'];
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$connection = mysqli_connect($host, $username, $password, $database);
$query = "SELECT likes FROM posts WHERE id=$id";
$result = mysqli_query($connection, $query);
$array = mysqli_fetch_assoc($result);
$likes = $array['likes'];
if ($isLiked == true) {
$updateQuery = "UPDATE posts SET likes=" . $likes++ . " WHERE id=$id";
} else {
$updateQuery = "UPDATE posts SET likes=" . $likes-- . " WHERE id=$id";
}
if (!$connection->query($updateQuery)) {
echo "query failed: (" . $connection->errno . ") " . $connection->error;
}
mysqli_query($connection, $updateQuery);
if (!$connection->query($updateQuery)) {
echo "query failed: (" . $connection->errno . ") " . $connection->error; // It returns that 1064 error
}
mysqli_query($connection, $updateQuery);

I see 3 possible mistakes.
First mistake, the $id can be empty.
And 2nd mistake can be $likes++ need be ++$likes, because you doesn't sum it with ++ after of the variable, im referring too to --$likes.
The 3rd mistake is your code is vulnerable to MySQL injection, i recommend make a prepared statement.
Link to prepared statement example and explanation: https://www.w3schools.com/php/php_mysql_prepared_statements.asp

Related

PHP and Mysql error "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version"

I am trying to code a little log thing for my Home automations script but then I got this error:
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 2
My SQL is:
INSERT INTO
logsa (timeb, msg, actionb)
VALUES
('12-05-2018 02:29:38pm',
'Succesfully send a trigger to https://maker.ifttt.com/trigger/test/with/key/xxxxxxxxxxxxxxxxxxxxxxxx With name test',
'https://maker.ifttt.com/trigger/test/with/key/xxxxxxxxxxxxxxxxxxxxxxxx'
and my code is:
$logmsg = ("Succesfully send a trigger to " . $row["actiona"] . " With name " . $row["namea"]);
date_default_timezone_set("Europe/Stockholm");
$date = date("d-m-Y");
$time = date("h:i:sa");
$fulldate = ($date . " " . $time);
$actiona = $row["actiona"];
$sql = "INSERT INTO logsa (timeb, msg, actionb)
VALUES ('$fulldate', '$logmsg', '$actiona'";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Change the timeb data value $fulldate to use a valid date time format like this
$fulldate = date('Y-m-d H:i:s');
MySQL and mariaDB expect DATETIME columns to be stored in a very specific format and yours was invalid.
Also you should be using prepared and parametrised queries [link] to avoid SQL Injection attacks like this
$logmsg = ("Succesfully send a trigger to " .
$row["actiona"] .
" With name " .
$row["namea"]);
date_default_timezone_set("Europe/Stockholm");
$fulldate = date('Y-m-d H:i:s');
$actiona = $row["actiona"];
$sql = "INSERT INTO logsa (timeb, msg, actionb) VALUES (?,?,?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param('sss', $fulldate, $logmsg, $actiona );
$result = $stmt->execute();
if ($result) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

MAMP - All MySQL Queries Return Null

I recently installed MAMP. But my I can't successfully execute MySQL queries from php. I can connect to MySQL from php, but all my queries come back as NULL. I don't get any error message or other message that would help me diagnose the problem.
Oddly, I can successfully query MySQL with phpMyAdmin and MySQLWorkbench.
Here is my code:
<?php
$link = mysqli_init();
$con = mysqli_real_connect($link, 'localhost', 'root', 'root', 'mrmk', 8889);
$db = 'mrmk';
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
echo "Host information: " . mysqli_get_host_info($link) . PHP_EOL;
$sql = "SHOW TABLES FROM `$db`";
$result = mysqli_query($con, $sql);
echo "</br>" . "1. MySQL Error: " . mysqli_error();
echo "</br>" . "result: ";
var_dump($result);
$sql = "SHOW TABLES FROM $db";
$result = mysqli_query($con, $sql);
echo "</br></br>2. MySQL Error: " . mysqli_error();
echo "</br>" . "result: ";
var_dump($result);
$sql = "SELECT * FROM `transactionTable` WHERE `attorneyName` LIKE \'%howard%\'";
$result = mysqli_query($con, $sql);
echo "</br></br>3. MySQL Error: " . mysqli_error();
echo "</br>" . "result: ";
var_dump($result);
if (!$result) {
echo "</br></br>" . "4. MySQL Error: " . mysqli_error();
exit;
} else {
echo "we should have results.";
}
while ($row = mysqli_fetch_row($result)) {
echo "Table: {$row[0]}\n";
}
mysqli_free_result($result);
?>
When I access the page through localhost I get this:
Host information: Localhost via UNIX socket
1. MySQL Error:
result: NULL
2. MySQL Error:
result: NULL
3. MySQL Error:
result: NULL
4. MySQL Error:
When I execute the same queries from phpMyAdmin, they execute successfully and return non-NULL results.
I have two questions:
What code can I add to help diagnose this problem?
Do I have a error in my code that is causing me to get NULL results.
Have you enabled mysqli extension in PHP? Check apache error log. Look at this question for example. mysqli is disabled by default, you need to uncomment line
extension=php_mysqli
in php.ini file.
To answer question #1, you might find it helpful to echo your $sql variables, to make sure your queries are valid and what you intended them to be.

Mysql Query Update From php

Hi to everyone i have a problemn with a query in PHP to Update records.
<?php
include('../webcgo/script/cox.php');
$query = $cox->query("SELECT cf_id FROM offerte;");
while ($idx = mysqli_fetch_array($query)) {
$check = '<button class="uk-button" onclick="location.href=\'http://localhost/chartscript/remRegola.php?dis=2&id=' . $idx['cf_id'] . '\'">OK</button>';
$query_check = 'UPDATE offerte SET check=\'' . $check . '\' WHERE cf_id=' . $idx['cf_id'].';';
if ($queryx = $cox->query($query_check) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $cox->error;
}
}
mysqli_close($cox);?>
The result:
Error updating record: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'check='
check is a MySQL reserved keyword. If you're going to use it in your query you must wrap it in backticks:
$query_check = 'UPDATE agoragroup_chronoforms_data_inserimento_offerte_prod SET `check`=\'' . $check . '\' WHERE cf_id=' . $idx['cf_id'].';';

Need help fetching an array from a prepared statment

I am new to using prepared statement with PHP. I am trying to get the value of "full_name"... So far I am stuck over here. Can anyone please help figure this out? Thanks!
if($db->connect_error){
echo "Connection Error";
}
$id = 834;
$stmnt = $db->prepare("SELECT * FROM checkout_page where id = ?");
$stmnt->bind_param("i", $id);
if (!$stmnt->execute()) {
echo "Execute failed: (" . $stmnt->errno . ") " . $stmnt->error;
}
$row = $stmnt->fetch();
You need to use bind_result to bind variables to the columns you want. Then each time you call fetch(), those variables will be updated with the next row's values. fetch() with mysqli does not return you the row/result.
This means you cannot use SELECT *. You need to specify which fields you want.
if($db->connect_error){
echo "Connection Error";
}
$id = 834;
$stmnt = $db->prepare("SELECT full_name FROM checkout_page where id = ?");
$stmnt->bind_param("i", $id);
if (!$stmnt->execute()) {
echo "Execute failed: (" . $stmnt->errno . ") " . $stmnt->error;
}
$stmnt->bind_result($full_name);
$stmnt->fetch();
echo $full_name;
Or, if you have the mysqlnd driver installed, you can use get_result() to get a result set just like if you had ran a normal query, not a prepared statement.
if($db->connect_error){
echo "Connection Error";
}
$id = 834;
$stmnt = $db->prepare("SELECT * FROM checkout_page where id = ?");
$stmnt->bind_param("i", $id);
if (!$stmnt->execute()) {
echo "Execute failed: (" . $stmnt->errno . ") " . $stmnt->error;
}
$result = $stmnt->get_result();
$row = $result->fetch_assoc();
echo $row['full_name'];

Prepared Statement getting Commands out of sync; you can't run this command now

I have read everything I can think of to get an explanation but nothing seems to help. If someone might be able to point out the obvious or give me a slight idea of what is wrong. I have read through php.net and the mysqli tag and can't seem to figure this out. Everything I read says you can't send two queries but I am only trying one. Any help would be much appreciated.
This->https://stackoverflow.com/a/9649149/1626329 - States that maybe I have multiple result sets but I am not sure that makes much sense or what I can do to get more detail on the inner workings of prepared statements.
My Code:
class mydb {
public function __construct() {
// Connect to Database
$this->mydb = new mysqli('****', '***', '***', '***');
if ($this->mydb->connect_errno) { // Error on connection failure
echo "Failed to connect to MySQL in Construct: (" . $this->mydb->connect_errno . ") " . $this->mydb->connect_error;
}
}
public function choose ($select, $from, $config = 0, $options = NULL) {
if ($config === 0) { /** Configure statement for prepare depending on options */
$stmt = 'SELECT ' . $select . ' FROM ' . $from;
} elseif ($config === 1) {
$stmt = 'SELECT ' . $select . ' FROM ' . $from . ' WHERE ' . $options['where_comp'] . ' LIKE ?';
} elseif ($config === 2) {
$stmt = 'SELECT ' . $select . ' FROM ' . $from . ' WHERE ' . $options['where_comp'] . ' = ?';
} /** End if/elseif Prepare statemenet */
$mydb = $this->mydb->prepare($stmt);
if ($config === 1 || $config === 2) {
$mydb->bind_param("s",$options['where_value']);
}
if ($mydb->execute()) { /** If execute is good then get results */
$result = $mydb->get_result();
$payload = array();
while ($row = $result->fetch_array(MYSQLI_NUM)) {
$payload[] = $row;
}
return $payload;
} /** End if results */
} /** End choose class method */
} /** End mydb Class */
$myDB = new mydb();
$agentArray = $myDB->choose('*','`agent`');
Used the php.net example and modified it to show a better example:
$mysqli = new mysqli('host', 'database', 'user', 'pass');
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
if (!($stmt = $mysqli->prepare("SELECT ? FROM ?"))) {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
if (!($res = $stmt->get_result())) {
echo "Getting result set failed: (" . $stmt->errno . ") " . $stmt->error;
}
for ($row_no = ($res->num_rows - 1); $row_no >= 0; $row_no--) {
$res->data_seek($row_no);
var_dump($res->fetch_assoc());
}
$res->close();
The very first result from the "Related" section on this page (Means it was offered to you while you were in struggle writing your question) offers a solution.
As a general rule, it is quite easy to find an answer to a question based on the error message. Only you need is not to stop at the very first search result but proceed a bit more.
However, on this function choose() of yours. I find it quite impractical, unsafe, and useless:
impractical because it doesn't let you to use SQL, but a very limited subset of it.
and also it makes your code extremely hard to understand.
unsafe because it does offer no protection for all the dynamical parts but where value only
useless because it can save you not that much to worth a mess.
Look, you think you saved yourself 2 words - SELECT and FROM.
$agentArray = $myDB->choose('*','`agent`',1,
array('where_comp' => 'name', 'where_value' -> "%bob%"));
yet you made this code hard to understand, hard to maintain and unable to run ever simplest JOIN. Why not to make it. Not to mention that actual code become longer than conventional SQL query:
$sql = 'SELECT * FROM `agent` WHERE name LIKE ?';
$agentArray = $myDB->query($sql, "%bob%");
which one is easier to read?
Adding an if statement to show the error correctly actually gives a mysql error response that can be used:
if (!($stmt = $mysqli->prepare("SELECT ? FROM ?"))) {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
Error response:
Prepare failed: (1064) You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?' at line 1
-- You can't pass identifiers through prepared-statements and you should only use it for values passed from user input.

Categories