$tran = "START TRANSACTION;";
$tran_res = mysql_query($tran);
$qry_1 = "INSERT INTO docList (doc_ip , doc_country , doc_ref) VALUES ('$ip' , '$country' , '$http_ref');";
$res_1 = mysql_query($qry_1);
if(!$res_1)
die ("qry1 fail " . mysql_error() );
$ins_id = mysql_insert_id();
if(!$ins_id)
die ("ins id fail " . mysql_error() );
echo "<b>$ins_id</b>";
$qry_2 = "INSERT INTO docContent (doc_id , cont_date , cont_title , cont_aim , cont_obj , cont_theory , cont_sw , cont_code) VALUES ('$ins_id' , '$dt' , '$title' , '$aim' , '$obj' , '$th' , '$sw' , '$code');";
$res_2 = mysql_query($qry_2);
if(!$res_2)
die("qry2 fail " . mysql_error() ); `
The execution of above is returning the following error:
2 qry fail 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 'login'); if($query->num_rows()>0) return $query->result_array(); } ' at line 1
In effect the execution of $qry_2 is failing, but I am perplexed by the error it is showing (there is no such code on line 1 as mentioned in the error note). Moreover, the query ($qry_2) executes properly in the MySql console.
Output the contents of $qry_2 to see the actual SQL statement be executed. Most likely you've got SQL injection vulnerabilities, and one of the variables you're inserting contains at least ' somewhere, causing the syntax error.
e.g. if you have
$var = "O'Reilly";
$sql = "INSERT INTO names (name) VALUES ('$var')";
you'll end up with
INSERT INTO names (name) VALUES ('O'Reilly');
which will be interpreted as:
'O' - string containing the letter "O"
Reilly - a field named "Reilly", with no operator between this "field" and the "O" previous
'); - a weird unterminated string, also with no operator between this and the previous field.
To get around this, you MUST pass your variables through mysql_real_escape_string(), which will prevent such errors from occuring. It'll turn O'Reilly into O\'Reilly, which is "safe" to use in your query.
You haven't posted the real query as received by the MySQL server, but I'd dare say you haven't used mysql_real_escape_string() to inject your data into your SQL.
(Are you trying to insert PHP code in the database?)
Related
php/mysql
I keep getting this 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 '1' at line 1".
I'm trying hard to make this query to happen. It works, it inserts into the mysql database but this error appears every time. I've tried to use everything in the same line, changed double quotes to single quotes, removed all the whitespaces inserting everything in the samen line, changing the way I pass the variables({$variable} to '.$variable.') and everything else. I've seen a couple of stackoverflow questions related to this but with different solutions.
I know that we can't pass '' in a numeric fields.
I think I'm out of options now. Need help!
This error keeps showing but the data is correctly inserted in my table
here is the code:
$user_id = get_current_user_id();
$prescription_name = $_POST['prescription_name'];
$date_created = date('Y-m-d');
$last_updated = date('Y-m-d');
$right_eye_sphere = $_POST['right_eye_sphere'];
$left_eye_sphere = $_POST['left_eye_sphere'];
$right_eye_cylinder = $_POST['right_eye_cylinder'];
$left_eye_cylinder = $_POST['left_eye_cylinder'];
$right_eye_axis = $_POST['right_eye_axis'];
$left_eye_axis = $_POST['left_eye_axis'];
$pd = $_POST['pd'];
$date_of_birth = $_POST['date_of_birth'];
$file_path = $_POST['file_path'];
$add_query = "INSERT INTO wew_prescription (
prescription_id,
user_id,
prescription_name,
date_created,
last_updated,
right_eye_sphere,
left_eye_sphere,
right_eye_cylinder,
left_eye_cylinder,
right_eye_axis,
left_eye_axis,
pd,
date_of_birth,
file_path
) Values (
NULL,
{$user_id},
'{$prescription_name}',
'{$date_created}',
'{$last_updated}',
'{$right_eye_sphere}',
'{$left_eye_sphere}',
'{$right_eye_cylinder}',
'{$left_eye_cylinder}',
'{$right_eye_axis}',
'{$left_eye_axis}',
'{$pd}',
'{$date_of_birth}',
'{$file_path}'
)";
$sql = $dbCon->query($add_query);
if (!mysqli_query($dbCon,$sql)){
die('Error: ' . mysqli_error($dbCon));
}else{
mysqli_query($dbCon,$sql);
echo "dados atualizados!";
}
The error is coming from this line:
if (!mysqli_query($dbCon,$sql)){
$sql contains the result of
$dbCon->query($add_query);
Since that query was successful, $sql contains TRUE. mysqli_query() requires the second argument to be a string, so TRUE becomes "1", so you're effectively doing:
if (!mysqli_query($dbCon, "1")) {
That's not a valid query, so you get an error.
I think what you really meant to do was:
if (!$sql) {
die('Error: ' . $dbCon->error);
} else {
echo "dados atualizados!";
}
You don't need to keep calling mysqli_query() repeatedly.
You should also learn to code using prepared statements instead of substituting variables into the query, to prevent SQL injection.
I am trying to insert a url to mysql(through php) column but unable to do it.
I am getting the following error
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 '%2F%2Flocalhost%2Fclient%2Fsave_file.php%3Ffilename%3D9 WHERE queryid='29'' at line 1
The code snippet :
$_POST['url1']="//localhost/client/save_file.php?filename=9";
$_POST['query_id']=29;
$var=$_POST['url1'];
$query_id=$_POST['query_id'];
// echo "$var";
$var=rawurlencode($var);
//echo "$var";
$sql1 = "UPDATE query_audio SET query_content=$var WHERE queryid='".$query_id."' ";
if (!mysql_query($sql1)) {
die('Error: ' . mysql_error($connection));
}
You have a fundamental misunderstanding of how to defend against SQL injection attacks You need to use mysql_real_escape_string(), not urlencode().
Plus, you forgot to quote your $var variable, so your query is litterally:
... SET query_content=http:%2F%2Fetc...
Without quotes around that url, mysql is free to interpret the http: portion as an (invalid) field name.
Try
$var = mysql_real_escape_string($_POST['url1']);
$query_id = mysql_real_escape_string($_POSt['query_id']);
$sql = "UDPATE ... SET query_content='$var' WHERE queryid='$query_id';";
^----^-- note these quotes.
The code below is used when the user enters a youtube url it get the youtube id from the url. It then get the title for that video with that id. That is then inserted into a database and recalled to display the image of the video associated with that id.
if i use this youtube url http://www.youtube.com/watch?v=p64tAbP-nHE or and other youtube url. If the title of that youtube url contains a ' ie(2013 Ravens Rock Rally - Jonathan O'Callaghan & Gavin Sheehan - Stage 3) i get the error
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 'Callaghan & Gavin Sheehan - Stage 3'' at line 1
Any help would be great, thanks in advance.
Here is my code:
<?php
include 'dataconnection.php';
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
$url = $_POST['set_video'];
parse_str( parse_url( $url, PHP_URL_QUERY ), $my_array_of_vars );
$youtube_id = $my_array_of_vars['v'];
$info = $_POST['set_desc'];
$id = $my_array_of_vars['v'];
$xmlData = simplexml_load_string(file_get_contents("http://gdata.youtube.com/feeds/api/videos/{$id}?fields=title"));
$title = (string)$xmlData->title;
$sql="INSERT INTO videodetails SET id='null',youtube_id='$youtube_id',info='$title'";
if (!mysqli_query($connection,$sql))
{
die('Error: ' . mysqli_error($connection));
}
echo "<div id='pageheader'>
1 record added<span id='logout'>Return to <a href='contributors_login.html'>Contributors Login</a></span>
</div>";
echo '<div id="setvideo"><img src="http://i4.ytimg.com/vi/'.$my_array_of_vars['v'].'/default.jpg" style="border:solid 2px white;"><p>'.$title.'</p></div>';
mysqli_close($connection);
?>
Use mysqli_real_escape_string in your INSERT INTO ... part.
You open single quotes. But the title contains also single quotes so they get closed. MySQL doesn't know this and thinks the text that follows is a MySQL keyword.
Your yourTube name has a quote in it, so the SQL line
$sql="INSERT INTO videodetails SET id='null',youtube_id='$youtube_id',info='$title'
becomes this
INSERT INTO videodetails SET id='null',
youtube_id='2013 Ravens Rock Rally - Jonathan O'Callaghan & Gavin Sheehan - Stage 3'
which MySQL sees as
INSERT INTO videodetails SET id='null',
youtube_id='2013 Ravens Rock Rally - Jonathan O',Callaghan & Gavin Sheehan - Stage 3'
and MySQL doesn't understand Callaghan & Gavin Sheehan - Stage 3'
The case of strings that contain quotes is why mysqli_real_escape_string() exists, to find those quotes and insert a \ before them so they count as literal quote characters, instead of terminating the quoted string.
. . .
$youtube_id = mysqli_real_escape_string($my_array_of_vars['v']);
$info = mysqli_real_escape_string($connection, $_POST['set_desc']);
$sql="INSERT INTO videodetails SET id='null',youtube_id='$youtube_id',info='$title'";
if (!mysqli_query($connection,$sql))
. . .
But the best practice is to use query parameters, so you don't need to worry about those embedded quotes. Any place you have a variable in your SQL string in place of a literal value, use a query parameter placeholder. These placeholders don't work in place of table names, column names, or SQL expressions or keywords -- they only work where you would normally put a single scalar value in your SQL.
$sql="INSERT INTO videodetails SET id='null',youtube_id=?,info=?";
if ($stmt = mysqli_prepare($connection, $sql)) {
mysqli_stmt_bind_param($stmt, 'ss', $youtube_id, $title);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
}
This is safer, and makes your SQL more readable. Notice that the ? placeholder itself doesn't go inside quotes, even if the value you bind to it is a string.
PS: I question your use of the quoted string 'null' where you may mean the SQL keyword NULL.
Your insert query is not valid sql. The keyword "set" is used with update queries. Insert queries look like this:
insert into atable
(f1, f2, etc)
values
(val1, val2, etc)
or this
insert into atable
(f1, f2, etc)
select val1, val2, etc
from someOtherTables
<?php
mysql_connect("localhost","root","");
mysql_select_db("hftwmvirtualdb");
$Booknum = mysql_real_escape_string($_POST['Booknum']);
$Chapternum = mysql_real_escape_string($_POST['Chapternum']);
$Versenum = mysql_real_escape_string($_POST['Versenum']);
$sql = mysql_query("SELECT `VERSETEXT` FROM `booktable` WHERE `BOOKID` = $Booknum AND `CHAPTERID` = $Chapternum AND `VERSENO` = $Versenum");
echo mysql_error();
while($row=mysql_fetch_assoc($sql));
print(json_encode($row));
mysql_close();
?>
I am trying to use posted data from an android application to trigger a query and retrieve the results from the mysql database. The Table has 4 columns, and I'm trying to retrieve the value in the third column by defining the values in the first 3 columns. Each time i clicked the button, I get the parsing error to find out my PHP script was not processing the SQL query. When running the scriptthrough the browser I get the messages:
Undefined index: Booknum in C:\wamp\www\GetVerse.php on line 4
Undefined index: Chapternum in C:\wamp\www\GetVerse.php on line 5
Notice: Undefined index: Versenum in C:\wamp\www\GetVerse.php on line 6
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 'AND CHAPTERID = AND VERSENO =' at line 1
Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in C:\wamp\www\GetVerse.php on line 9.
I understand i get the warning messages 1-3 is because I did not submit the post data but the latter I don't know how to fix as I have tried using the correct syntax, I tried removing "=" for "like" and that failed also. What is the problem?.
The undefined index errors are, as you specified, occurring because you did not submit the post data. This, in turn, is causing the variables $Booknum, $Chapternum, and $Versenum to be empty.
With the empty variables, the MySQL query is being generated with a WHERE clause like:
WHERE `BOOKID` = AND `CHAPTERID` = AND ...
The missing values are causing invalid MySQL, hence your error. Additionally, as you've specified (in a comment) that the POST-values are strings (and not integers which is what I would have assumed based on their usage and names), you have to wrap the values in quotes in your MySQL query too. If you do not wrap the values in quotes, even valid strings may cause the query to fail.
To fix this, try something like:
$Booknum = isset($_POST['Booknum']) ? mysql_real_escape_string(trim($_POST['Booknum'])) : null;
$Chapternum = isset($_POST['Chapternum']) ? mysql_real_escape_string(trim($_POST['Chapternum'])) : null;
$Versenum = isset($_POST['Versenum']) ? mysql_real_escape_string(trim($_POST['Versenum'])) : null;
if (!empty($Booknum) && !empty($Chapternum) && !empty($Versenum)) {
$sql = mysql_query("SELECT `VERSETEXT` FROM `booktable` WHERE `BOOKID` = '" . $Booknum . "' AND `CHAPTERID` = '" . $Chapternum . "' AND `VERSENO` = '" . $Versenum . "'");
echo mysql_error();
while($row=mysql_fetch_assoc($sql));
print(json_encode($row));
mysql_close();
}
This will verify that the values are properly set - if not, they will be set to null. If all three values are not empty, via PHP's empty(), your query will be executed.
This is what your SQL query will look like when the variables are substituted in:
SELECT `VERSETEXT` FROM `booktable` WHERE `BOOKID` = AND `CHAPTERID` = AND `VERSENO` =
When the variables contain no content (as they won't if you submit no data), the query is meaningless: the syntax is malformed.
Check whether the data is posted before doing the query. Moreover, it will also profit you to start using parameterised queries (using MySQLi or PDO) for security and convenience.
The "undefined index" messages you're getting are because those variables are not set. Check that you're actually posting those to the script.
The empty variables are why your query is wrong and you get an error.
Consider using PDO as the "mysql_" commands are deprecated. You should check your inputs before passing them to the query. isset() will work for that.
CHeck whether the Post data is coming or not, undefined index it is because, there is no data for the variables you have used. SO first verify it and then execte the SQL query.
if(isset($_POST['Booknum']) && isset($_POST['Chapternum']) && isset($_POST['Versenum']))
{
$Booknum = mysql_real_escape_string($_POST['Booknum']);
$Chapternum = mysql_real_escape_string($_POST['Chapternum']);
$Versenum = mysql_real_escape_string($_POST['Versenum']);
$sql = mysql_query("SELECT `VERSETEXT` FROM `booktable` WHERE `BOOKID` = $Booknum AND `CHAPTERID` = $Chapternum AND `VERSENO` = $Versenum");
echo mysql_error();
while($row=mysql_fetch_assoc($sql));
print(json_encode($row));
}
else
{
echo "No post data";
}
I'm having problems inserting a form $_POST variable to MySQL!
I know it's a single quote problem but simply cannot resolve it.
Code is:
$naziv_db = $_POST["naziv"];
$naziv_db = mysql_real_escape_string($naziv_db);
$query = "INSERT INTO items (title) VALUES ('$naziv_db')";
$stmt = mysql_query($query) or die("MySQL error: " . mysql_error());
If I enter a value containing " it inserts correctly, but if it contains ' then the error appears!
For example if my input is Milky's
error is: MySQL 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 's
If my input is "Milkys" everything goes well...
I'm new here, so can't post an answer to my own question so i have to edit!
Christian's solution was the right one!
I have changed the code:
$query = "INSERT INTO items (title) VALUES ('$naziv_db')";
to:
$query = 'INSERT INTO `items` (`title`) VALUES ("'.$naziv_db.'")';
and now it accepts both " and ' without error!
Thank you guys, you're the best :D
To avoid this entirely, you'd be best using a prepared statement.
There's a good example in the answer to this question.
Converted for your case, you get:
$db = new mysqli("host","user","pw","database");
$stmt = $db->prepare("INSERT INTO items (title) VALUES (?)");
$stmt->bind_param('s', $_POST["naziv"]);
$stmt->execute();
$stmt->close();
It's quite impossible to get such an error from your code.
Most likely there is a typo somewhere in it.
May be you're escaping wrong variable or it's another query producing this error
Are you sure you posted the code you actually running? is it exact code or some sketch?
change your mysql_query string to this one
mysql_query($query) or trigger_error(mysql_error()." ".$sql);
and paste it's output please.
or, even change whole code:
ini_set('display_errors',1);
error_reporting(E_ALL);
$naziv_db = $_POST["naziv"];
$naziv_db = mysql_real_escape_string($naziv_db);
$query = "INSERT INTO items (title) VALUES ('$naziv_db')";
var_dump($_POST["naziv"]);
echo "<br>\n";
var_dump($naziv_db);
echo "<br>\n";
var_dump($query);
echo "<br>\n";
mysql_query($query) or trigger_error(mysql_error()." ".$sql);
this is called "debugging" and usually helps.
Try addslashes - it's made for parsing strings into database-friendly content.