Error while doing PHP mysqli insert into table - php

I have table column log_id as primary_key auto_increment.
Do I need to specify it within INSERT INTO statement or no?
I am getting next error while trying to insert values into my database:
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 '(log_session,log_ip,log_vrijeme,log_model) my_log VALUES ('270043ae1526e4' at line 1 INSERT INTO (log_session,log_ip,log_vrijeme,log_model) my_log VALUES ('270043ae1526e44967889b4382ff69fd','93.142.54.135','2018-11-23 14:06:15','1402')
My code is:
<?php
$_SESSION['compare_hash'] = "270043ae1526e44967889b4382ff69fd";
$log_session = $_SESSION['compare_hash'];
$log_ip = $_SERVER['REMOTE_ADDR'];
$log_vrijeme = date("Y-m-d H:i:s");
$log_model = "1402";
$con = mysqli_connect("localhost","user","password","databse");
$sql = "
INSERT INTO (log_session,log_ip,log_vrijeme,log_model) my_log
VALUES ('$log_session','$log_ip','$log_vrijeme','$log_model')
";
$rez = mysqli_query($con, $sql) or die(mysqli_error($con)."<br>$sql");
mysqli_close($con);
?>
Table structure:
Field Type Null Key Default Extra
log_id int(11) NO PRI NULL auto_increment
log_session varchar(42) NO MUL NULL
log_ip varchar(15) NO NULL
log_vrijeme datetime NO MUL NULL
log_model int(11) NO MUL NULL
Thank you for help.

You should put my_log right after INSERT INTO:
<?php
$_SESSION['compare_hash'] = "270043ae1526e44967889b4382ff69fd";
$log_session = $_SESSION['compare_hash'];
$log_ip = $_SERVER['REMOTE_ADDR'];
$log_vrijeme = date("Y-m-d H:i:s");
$log_model = "1402";
$con = mysqli_connect("localhost","user","password","databse");
$sql = "
INSERT INTO my_log (log_session,log_ip,log_vrijeme,log_model)
VALUES ('$log_session','$log_ip','$log_vrijeme','$log_model')
";
$rez = mysqli_query($con, $sql) or die(mysqli_error($con)."<br>$sql");
mysqli_close($con);
?>
However, your code has several drawbacks, I'll describe them a bit later.
1. Don't pass unescaped variables into query
Until you have no other way. Use mysqli_real_escape_string($con, $your_var) to prevent SQL injection and using PDO would make it even better.
2. Use HEREDOC syntax to ensure query consistency during future edits
In this way even if you of someone will put " into query it would still work as expected.
3. Omit closing tag on the end of your PHP files if you don't have any content below
This will prevent surprising errors from happening.
<?php
$_SESSION['compare_hash'] = "270043ae1526e44967889b4382ff69fd";
$con = mysqli_connect("localhost","user","password","databse");
$log_session = mysqli_real_escape_string($con, $_SESSION['compare_hash']);
$log_ip = mysqli_real_escape_string($con, $_SERVER['REMOTE_ADDR']);
$log_vrijeme = mysqli_real_escape_string($con, date("Y-m-d H:i:s"));
$log_model = mysqli_real_escape_string($con, "1402");
$sql = <<<SQL
INSERT INTO my_log (log_session,log_ip,log_vrijeme,log_model)
VALUES ('${log_session}','${log_ip}','${log_vrijeme}','${log_model}')
SQL;
$rez = mysqli_query($con, $sql) or die(mysqli_error($con)."<br>$sql");
mysqli_close($con);

Related

MySQL error 1064 while using PHP variables in query

<?php
session_start();
$con = mysqli_connect("localhost","root","12369","medical");
$data1 = $_SESSION["symp1"];
$data2 = $_SESSION["symp2"];
$data3 = $_SESSION["symp3"];
$data4 = $_SESSION["symp4"];
$finalData = implode(' ', array($data1, $data2, $data3, $data4));
$userinput = $_REQUEST["answer"];
$dname=$_SESSION["dname"];
$dname = str_replace(' ', '_', $dname);
echo $dname." <br>";
$sql = " UPDATE diseases SET UserInput = $finalData WHERE Name = $dname ";
if($userinput=='yes'){
if(mysqli_query($con,$sql)){
echo "Values inserted";
$_SESSION["info"] = "yes";
header('Location: http://localhost/medical/last.php');
}else{
echo mysqli_errno($con);
$_SESSION["info"] = "no";
//header('Location: http://localhost/medical/last.php');
}
}
?>
I'm getting error 1064? I already read answers to similar question, but my code doesn't work. My table schema is:
CREATE TABLE IF NOT EXISTS `diseases` (
`ID` int(50) NOT NULL AUTO_INCREMENT,
`Name` varchar(255) NOT NULL,
`Symptoms` varchar(255) NOT NULL,
`Medicines` varchar(255) NOT NULL,
`Description` varchar(255) NOT NULL,
`Tags` varchar(255) NOT NULL,
`UserInput` varchar(255) NOT NULL,
PRIMARY KEY (`ID`)
)
What's wrong in my code? Thanks
Change:
$sql = " UPDATE diseases SET UserInput = $finalData WHERE Name = $dname ";
to:
$sql = "UPDATE `diseases` SET `UserInput` = '$finalData' WHERE `Name` = '$dname'";
Add single quotes around variables that contain a string.
Add backticks around columns and table to prevent mysql reserved words error
It would be even better to use mysqli_prepare do the following:
$stmt = mysqli_prepare($con, "UPDATE `diseases` SET `UserInput` = ? WHERE `Name` = ?");
mysqli_stmt_bind_param($stmt, "ss", $finalData, $dname);
mysqli_stmt_execute($stmt);
As the error message should state, you have an error in your SQL syntax:
MySQL Error 1064: You have an error in your SQL syntax
Surround your data by single quotes and you are good to go. Furthermore, Name is a reserved keyword in MySQL. You can still use it in your query, though, but you should consider escaping table names with backticks:
$sql = " UPDATE diseases SET `UserInput` = '$finalData' WHERE `Name` = '$dname' ";
Add single qoutes around your data:
$sql = " UPDATE diseases SET UserInput = '$finalData' WHERE Name = '$dname' ";
or better use prepared statements

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use

Im facing this problem when inserting a SQL query:
Error: 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 '30000001'', NULL, 'Pending', NULL, NULL)' at line 1
The code is:
<?php
// Connecting to the MySQL server
include "connection.php"; // Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "SELECT * FROM meet ORDER BY meetid DESC LIMIT 1"; $result =
mysqli_query($con,$query) or die(mysqli_error($con)); $last_val =
mysqli_fetch_array($result); // print_r($last_val); $last_val1 =
$last_val[0];
$query = "SELECT * FROM hdr_student WHERE Stud_NO = '$stud_no'";
$result = mysqli_query($con,$query) or die(mysqli_error($con));
$check_over = mysqli_fetch_array($result);
$null = 'sss'; $validateon = '0000-00-00 00:00:00.000000';
$supprephour = '0';
if(!empty($check_over['c_supervisor']))
{
if(!empty($check_over['p_supervisor']))
{
$check_supp = $check_over['p_supervisor'];
$check_supp1 = var_export($check_supp,true);
$query = "INSERT INTO supervisorattendance (meetid, sup_no, supnote, supvalidate, supprephour, validateon) VALUES ('$last_val1', '$check_supp1', NULL, 'Pending', NULL, NULL)";
if (!mysqli_query($con,$query))
{
die('Error: ' . mysqli_error($con));
}
}
$check_supc = $check_over['c_supervisor'];
$check_supc1 = var_export($check_supp,true);
$query = "INSERT INTO supervisorattendance (meetid, sup_no, supnote, supvalidate, supprephour, validateon) VALUES ('$last_val1', '$check_supc1', NULL, 'Pending', NULL, NULL)";
if (!mysqli_query($con,$query))
{
die('Error: ' . mysqli_error($con));
}
}
?>
you problem is about single quotes in your variable used in mysql
so escape them like this before use in mysql
$check_supc = $check_over['c_supervisor'];
$check_supc1 = var_export($check_supp,true);
$last_val1 = mysqli_real_escape_string($con, $last_val1); // use this line
$check_supc1 = mysqli_real_escape_string($con, $check_supc1); // use this line
$query = "INSERT INTO supervisorattendance (meetid, sup_no, supnote, supvalidate, supprephour, validateon) VALUES ('$last_val1', '$check_supc1', NULL, 'Pending', NULL, NULL)";
var_export tries to generate a string that's valid as PHP code. Among other things, this means that if your content is a string, it'll get quotes around it. Since you're also adding quotes while you're cobbling your SQL, you end up with something like ...''$check_supp1'', NULL, 'Pending', NULL, NULL).
Unless you have a good reason for using var_export here (and i'm about 94% certain you don't), get rid of it. Use mysqli_real_escape_string to make stuff safer for a MySQL query.
Or, if there's nothing but that number, you can use intval to make sure it's always a number.
Or, learn to use prepared statements. :P They can handle most of this stuff automatically.

Error in SQL INSERT INTO query

I have following code written in PHP:
$q = mysql_query("INSERT INTO logowania ('user','udane','ip') VALUES ($uid,0,'".ip()."')"); echo mysql_error();
Values of $uid and ip() are correct, you can trust me.
Structure of logowania table:
1 idlogowania int(11)
2 user int(11)
3 udane tinyint(1)
4 data timestamp on update CURRENT_TIMESTAMP CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
5 ip text utf8_polish_ci
I don't know where is the error in the statement. MySQL gives:
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 ''user','udane','ip') VALUES (1,0,'79.184.7.44')' at line 1
I tried to debug that, but without successful ending. I know that could be very simple mistake, but human's vision isn't infallible...
Use back ticks for column name,otherwise they are treated as strings.
(`user`,`udane`,`ip`)
Take out '' from the column names.
$q = mysql_query("INSERT INTO logowania ('user','udane','ip') VALUES ($uid,0,'".ip()."')"); echo mysql_error();
should be
$q = mysql_query("INSERT INTO logowania (user,udane,ip) VALUES ($uid,0,'".ip()."')"); echo mysql_error();
OR use back-tics for the col names
$q = mysql_query("INSERT INTO logowania (`user`,`udane`,`ip`) VALUES ($uid,0,'".ip()."')"); echo mysql_error();
Alternative version:
$q = mysql_query("INSERT INTO logowania SET `user` = '" . $uid . "', `udane` = 0, `ip` = '" . ip() . "'"); echo mysql_error();

mysql_insert_id not working

Apologies for the vague title, here's my problem:
The goal of my code is to insert a new row into a table that has an auto-increment field. After the insert, I want to get the value of the auto-increment field that has just been generated.
Here's my table defintion:
CREATE TABLE `EventComments` (
`CommentID` int(11) NOT NULL AUTO_INCREMENT,
`EventID` int(11) NOT NULL,
`OwnerID` int(11) NOT NULL,
`Comment` varchar(512) NOT NULL,
`DateTime` datetime NOT NULL,
PRIMARY KEY (`CommentID`)
) ENGINE=MyISAM AUTO_INCREMENT=68 DEFAULT CHARSET=latin1;
I'm trying to get the value of the CommentID field.
So, here is the php code that issues the insert query and then attempts to get the CommentID value.
<?php
session_start();
ob_start();
include_once 'lib/functions.php';
if(isset($_SESSION['uid'])) {
$eventID = $_GET['evid'];
$ownerID = $_SESSION['uid'];
$comment = $_GET['comment'];
$comment = trim($comment);
$dateTime = date('Y-m-d H:i:s');
$db_connection = database_connect();
if($eventID != null && !empty($comment)) {
$query = "INSERT INTO meetup.EventComments (EventID, OwnerID, Comment, DateTime)
VALUES (" . $eventID . ", " . $ownerID .", '" . $comment . "', '". $dateTime ."')";
mysqli_query($db_connection, $query) or die(mysqli_error($db_connection));
$id = mysql_insert_id();
$commentHtml = generateCommentFromData($db_connection, $ownerID, $comment, $dateTime, $id);
echo $commentHtml;
}
}
ob_end_flush();
?>
This code issues the following error in the php logs:
mysql_insert_id() [<a href='function.mysql-insert-id'>function.mysql-insert-id</a>]: A link to the server could not be established...
I also tried explicitly passing the database link. But that gives the following error:
mysql_insert_id(): supplied argument is not a valid MySQL-Link resource...
As a final note, the insert query works. It is definitely inserting a new row with the expected data!
Any insight here would be appreciated!
Thanks
You are using the mysqli extension to connect and run your query, but then you use the mysql (notice the lack of i at the end) extension to get your inserted id, that can't work. While they are both extensions that provide access to mysql, they are also two very different libraries and can't share a connection between each other.
For the record, mysqli is the one you should be using, mysql is the "old" version that does not support new features of mysql >= 4.1
In other words, the solution is to use mysqli_insert_id()
Also, please escape your parameters properly, you can't put the content of $_GET and $_POST variables inside your query unsecured like that. At the very least use mysqli_real_escape_string()
$query = "INSERT INTO meetup.EventComments (EventID, OwnerID, Comment, DateTime)
VALUES (" . mysqli_real_escape_string($eventID)." [...]
For more infos on this, have a look to the numerous questions on this subject, for example this one: How to properly escape a string via PHP and mysql
You probably want to use the mysqli extension equivalent: mysqli_insert_id()
It might work as it is by passing the connection resource but even if it did, it's not good to mix methods from two separate connection classes:
$id = mysql_insert_id($db_connection);
DATETIME is a Data Type in MySQL that's why INSERT query is not working. Use backtick ` instead.
$query = "INSERT INTO meetup.EventComments (`EventID`, `OwnerID`, `Comment`, `DateTime`)
VALUES (" . $eventID . ", " . $ownerID .", '" . $comment . "', '". $dateTime ."')";

mysql update query (containing 'where' syntax) not working

I have a mysql table like this (sql):
CREATE TABLE IF NOT EXISTS silver_and_pgm (
_metal_name varchar(30) NOT NULL,
_bid varchar(30) NOT NULL,
_change varchar(30) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data for table silver_and_pgm
INSERT INTO silver_and_pgm (_metal_name, _bid, _change) VALUES
('Silver\r\n', '555', '-0.22\r\n'),
('Platinum\r\n', '555', '-9.00\r\n'),
('Palladium\r\n', '555', '0.00\r\n'),
('Rhodium\r\n', '555', '0.00\r\n');
and i am using the following code to update a row which contains metal_name as Silver
<?php
$username = "root";
$password = "1234";
$database = "kitco";
$con=mysql_connect(localhost,$username,$password);
mysql_select_db($database) or die( "Unable to select database");
$bid = '101010';
$metal_name = 'Silver';
$query = "update silver_and_pgm set _bid='$bid' where _metal_name='$metal_name'";
//$query2 = "update silver_and_pgm set _bid='444'";;
echo $query."<br>";
$result = mysql_query($query);
if(!$result)echo "error";
?>
but $query doesn't work . it works fine if I use $query2 . If I use the same query directly in SQL of phpmyadmin result is same.
what is the problem with $query . I think its correct.
Would anybody please find the bug ??
It looks like you have a line break in your _metal_name in the database, the SQL query says Silver\r\n.

Categories