Syntax wrong in my SQL query - php

Upon using this SQL query:
if($count2==0){
//If No Data For Current AF And Date Exists
$sql="INSERT INTO `workhours` (`Date`, `AFNumber`, `Name`, `IN`, `OUT`, `WorkingHours`, `Overtime`, `Status`, `Location`) VALUES('$expldate[1]/$expldate[0]/$expldate[2]', '$afnbr', '$name', '$firstin[0]:$firstin[1]', '$lastout[0]:$lastout[1]', '$totalworkhours:$totalworkmins', '$overtime[0]:$overtime[1]', '$status', '$location')";
if ($con->query($sql) === TRUE) {
echo "Data inserted<br>";
}else {
echo "Error: " . $sql . "<br>" . $con->error."";
}
}else{
//If There Exists Data For Current AF And Date
$sql="UPDATE workhours SET Date='$expldate[1]/$expldate[0]/$expldate[2]', AFNumber='$afnbr', Name='$name', IN='$firstin[0]:$firstin[1]', OUT='$lastout[0]:$lastout[1]', WorkingHours='$totalworkhours:$totalworkmins', Overtime='$overtime[0]:$overtime[1]', Status='$status', Location='$location' WHERE AFNumber='$afnbr'";
if ($con->query($sql) === TRUE) {
echo "Record updated successfully<br>";
} else {
echo "Error updating record: " . $con->error;
}
}
I'm receiving this error:
Notice: Undefined variable: location in
C:\xampp\htdocs\pp\login\code\upload.php on line 284 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 'IN=':', OUT=':', WorkingHours='0:0', Overtime='Check
Schedule:Error', Status='Ch' at line 1AF1110:07/09/2015
Any help plese?
I received the error after adding IN and OUT

IN, OUT are reserved keywords. Try with -
`IN`='$firstin[0]:$firstin[1]', `OUT`=':', ...

Related

Fail to insert data into mysql using php

Checking with phpcodechecker not showing the error but can't insert data into mysql.
PHP version: 5.6
Server type: MariaDB
here the code
header('Access-Control-Allow-Origin: *');
include "config.php";
$dblink = mysqli_connect($host,$dbu,$dbp,$db);
if (!$dblink) {
error_log( "Error: Unable to connect to MySQL." . PHP_EOL);
error_log("Debugging errno: " . mysqli_connect_errno() . PHP_EOL);
error_log("Debugging error: " . mysqli_connect_error() . PHP_EOL);
exit;
}
if (isset($_GET['name']) &&isset($_GET['score'])){
$name = strip_tags(mysqli_real_escape_string($dblink, $_GET['name']));//get data from column USER
$score = strip_tags(mysqli_real_escape_string($dblink, $_GET['score']));//get data from column HIGHscore
$sql=("SELECT * FROM scores WHERE name='$name';");//choose userdata table from database where column USER
$result = $dblink->query($sql);//execute database
if ($result->num_rows > 0){ //if result > 0, if any data on tables
$row = $result->fetch_assoc();
if ((int)$row['score'] < (int)$score){ //score on database less than score input will execute database
$sql=("INSERT scores SET name='$name', score='$score' ;"); //Update score
if ($dblink->query($sql) === TRUE) {
echo "Success";//this is if success
}
else
{
echo "Error updating record: " . $dblink->error;//this is if failed or error
}
}
}
}
// echo not effect
mysqli_close($dblink);
whether the use of .htaccess affects data insert ?
SOLVED
Delete this code if ($result->num_rows > 0) {
The format of your INSERT query is wrong (you have used the UPDATE form). You should use:
INSERT INTO scores (name, score) VALUES('$name', '$score')
See the manual...
In PHP:
$sql = "INSERT INTO scores (name, score) VALUES('$name', '$score')";

MySql transaction works only in console

When i paste this into MySql console
START TRANSACTION;
INSERT INTO `orders` (customer_id) VALUES ('2');
SET #lastid=LAST_INSERT_ID();
INSERT INTO `transactions`
(order_id,product_id,product_quantity,price,ammount,customer_id)
VALUES (#lastid,'3','2','4','4','2');
INSERT INTO `transactions`
(order_id,product_id,product_quantity,price,ammount,customer_id)
VALUES (#lastid,'1','3','5','4','2');
COMMIT;
it works fine, when i try to do the same via php
$sql = "START TRANSACTION;";
$sql .="INSERT INTO `orders` (customer_id) VALUES ('$customer_id_form');";
$sql .="SET #lastid=LAST_INSERT_ID();";
foreach ($product_id_form as $key => $product){
$sql .= "INSERT INTO `transactions`
(order_id,product_id,product_quantity,price,ammount,customer_id)
VALUES
(#lastid,'$product','$quantity_form[$key]',
'$price_form[$key]','$amount_form[$key]','$customer_id_form');";
}
$sql .= "COMMIT;";
//$sql = "INSERT INTO products (`product_name`,`curent_price`,`product_quota`) VALUES ('$productname_form','$productprice_form','$productquote_form')";
if ($con->query($sql) === TRUE) {
echo "New record created successfully";
header("Location: order.php");
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}
mysqli_close($con);
it does not work error shown is
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 'INSERT INTO orders (customer_id) VALUES ('2');SET
#lastid=LAST_INSERT_ID();INS' at line 1
Perform the queries one at a time; do not try to send them all at once to the server. The START...COMMIT will determine the transactional semantics.
I think you need multi_query, to execute multiple queries

UPDATE displays error but is successful

I'm attempting to UPDATE a table and it displays an SQL syntax error but it properly updates the table. I'm not really sure what the reasoning is behind it and I just don't want to turn off the error completely.
Error: 1
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 '1' at line 1
This is the function:
function logTime($time){
$sql1 = mysqli_query($this->con, "UPDATE `pilots` SET `active`='0',`total_time`='".$time."' WHERE username = '".$this->whoMe()."'");
if (mysqli_query($this->con, $sql1)) {
header('Location: index.php?pausedtime');
die();
}
else {
echo "Error: " . $sql1 . "<br>" . mysqli_error($this->con);
}
}
That's because you're using mysqli_query() twice... $sql1 line should be enough. Try this:
function logTime($time){
$sql1 = mysqli_query($this->con, "UPDATE `pilots` SET `active`='0',`total_time`='".$time."' WHERE username = '".$this->whoMe()."'");
if($sql1){
header('Location: index.php?pausedtime');
die();
} else {
echo "Error: " . $sql1 . "<br>" . mysqli_error($this->con);
}
}
Also note, that such queries should be executed with prepared statements for security reasons (at least).

Return ID of column from table with mysql_insert_id

$sql="INSERT INTO survey (user, title, description, opta, optb,optc,optd,time) VALUES ('$user','$title', '$dis', '$a' , '$b', '$c', '$d','timespan')";
if (mysqli_query($con,$sql))
{
echo "Success";
}
else
{
echo "Error: " . mysql_error();
}
echo $id = mysql_insert_id();
mysqli_close($con);
I want to return id of column from table, but it returns 0. why? and also how can i fix this problem? thanks in advance
You're mixing mysql and mysqli functions. Change:
echo $id = mysql_insert_id();
to
echo $id = mysqli_insert_id($con);
You also need to change mysql_error() to mysqli_error()
Not doing so, will not signal any possible errors found.

MySQL Syntax error on Insert Query from PHP

I'm getting a non-descriptive syntax error on a MYSQL query from PHP. If I "echo" the text of the query and paste it into a MySQL query window, the code works. Here is the SQL for the query, the error code, and the error message...
INSERT INTO ADVERTISEMENTS (`user_id`, `ad_name`, `click_url`, `img_url`, `bg_color`, `start_date`, `end_date`, `timer_delay`, `add_date`) VALUES (2, 'Test New Ad', 'http://www.google.com', 'red_arrow.png', '#000000', '1980-05-11 00:00:00', '2020-05-01 00:00:00', 5, '2013-07-14 22:21:59');
Error Code: 1064
Error Msg: 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
Here is the PHP code I am using...
$link = mysqli_connect($UM_Settings["database_options"]["server_name"], $UM_Settings["database_options"]["username"], $UM_Settings["database_options"]["password"], $UM_Settings["database_options"]["database_name"]);
$advertisementNameNew = mysqli_real_escape_string($link, $_POST['advertisementNameNew']);
$destinationURLNew = mysqli_real_escape_string($link, $_POST['destinationURLNew']);
$dropboxUploadFile = mysqli_real_escape_string($link, $_POST['dropboxUploadFile']);
$backgroundColorNew = mysqli_real_escape_string($link, $_POST['backgroundColorNew']);
$bannerStartDateNew = DateStringToMySQL($_POST['bannerStartDateNew']);
$bannerEndDateNew = DateStringToMySQL($_POST['bannerEndDateNew']);
$bannerSetTimerNew = intval($_POST['bannerSetTimerNew']);
$tmpUserID = UM_GetCookie("UM_UserID");
$tmpAddDate = DateStringToMySQL('now');
echo "INSERT INTO ADVERTISEMENTS(`user_id`, `ad_name`, `click_url`, `img_url`, `bg_color`, `start_date`, `end_date`, `timer_delay`, `add_date`) VALUES ($tmpUserID, '$advertisementNameNew', '$destinationURLNew', '$dropboxUploadFile', '$backgroundColorNew', '$bannerStartDateNew', '$bannerEndDateNew', $bannerSetTimerNew, '$tmpAddDate');<br />";
if (!mysqli_query($link, "INSERT INTO ADVERTISEMENTS(`user_id`, `ad_name`, `click_url`, `img_url`, `bg_color`, `start_date`, `end_date`, `timer_delay`, `add_date`) VALUES ($tmpUserID, '$advertisementNameNew', '$destinationURLNew', '$dropboxUploadFile', '$backgroundColorNew', '$bannerStartDateNew', '$bannerEndDateNew', $bannerSetTimerNew, '$tmpAddDate');")) {
printf("Error Code: %s\n", mysqli_errno($link));
echo "<br />";
printf("Error Msg: %s\n", mysqli_error($link));
}
I know that the database connection is working. I am able to select and update tables. I can also insert into other tables with different queries.
I am open to any suggestions.
Thank you in advance for your help!
I see a few errors in your query strings.
First, all your variables are passed as literal strings: "... VALUES ($tmpUserID, '$advertisementNameNew', ..." should be "... VALUES (".$tmpUserID.", '".$advertisementNameNew."', ...".
Second, I see missing quotes around $bannerSetTimerNew.
Third, there is an extra ;.
here's how I would write the query:
if (!mysqli_query($link, "INSERT INTO ADVERTISEMENTS (user_id, ad_name, click_url, img_url, bg_color, start_date, end_date, timer_delay, add_date) VALUES (".$tmpUserID.", '".$advertisementNameNew."', '".$destinationURLNew."', '".$dropboxUploadFile."', '".$backgroundColorNew."', '".$bannerStartDateNew."', '".$bannerEndDateNew."', '".$bannerSetTimerNew."', '".$tmpAddDate."')")) { ...
I didnt test it though.
hope this helps.
I see a ; at the end of the query. Are you sure that should be there?
There are two things
1. Remove the ; from at the end of the query.
2. I hope timer_delay field has datatype "Int" if its a VARCHAR then you will have to include quotes for that field value.
I hope this will help.
Passerby, thank you for your comment. This was my first experience with using mysqli, I changed my query to use the "bind_param" method, and everything works now. For anyone else with a similar problem, here is the corrected code...
$mysqli = new mysqli($UM_Settings["database_options"]["server_name"], $UM_Settings["database_options"]["username"], $UM_Settings["database_options"]["password"], $UM_Settings["database_options"]["database_name"]);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$advertisementNameNew = $_POST['advertisementNameNew'];
$destinationURLNew = $_POST['destinationURLNew'];
$dropboxUploadFile = $_POST['dropboxUploadFile'];
$backgroundColorNew = $_POST['backgroundColorNew'];
$bannerStartDateNew = DateStringToMySQL($_POST['bannerStartDateNew']);
$bannerEndDateNew = DateStringToMySQL($_POST['bannerEndDateNew']);
$bannerSetTimerNew = intval($_POST['bannerSetTimerNew']);
$tmpUserID = UM_GetCookie("UM_UserID");
$tmpAddDate = DateStringToMySQL('now');
/* Prepared statement, stage 1: prepare */
if (!($stmt = $mysqli->prepare("INSERT INTO `ADVERTISEMENTS` (`user_id`, `ad_name`, `click_url`, `img_url`, `bg_color`, `start_date`, `end_date`, `timer_delay`, `add_date`) VALUES (?,?,?,?,?,?,?,?,?)"))) {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
if (!$stmt->bind_param("issssssis",$tmpUserID, $advertisementNameNew, $destinationURLNew, $dropboxUploadFile, $backgroundColorNew, $bannerStartDateNew, $bannerEndDateNew, $bannerSetTimerNew, $tmpAddDate)) {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
$_GET['ad_id'] = $stmt->insert_id;
$stmt->close();

Categories