mysql error :error in sql syntax [duplicate] - php

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 7 years ago.
i want to insert some lines of text(paragraph) in database that is coming from wikipedia page..but mysql is showing this error when i try to insert the data in db:
"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 capital." can anyone help me to fix this problem..
here is what i have done so far...
<?php
$loc=$_POST["new"];
$url1 ="https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=".$loc;
$opf = file_get_contents($url1);
$data = json_decode($opf, true);
$titles = array();
foreach ($data['query']['pages'] as $page) {
$des = $page['extract'];
}
$con = mysql_connect("localhost","root","");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("location", $con);
$url = "http://upload.wikimedia.org/wikipedia";
echo $sql="INSERT INTO `search`(`id`, `name`, `text`) VALUES ('$loc', '$des');";
mysql_query($sql) or die(mysql_error());
echo "1 record added";
mysql_close($con);
?>

Ideally you should escape data before entering it into a database. The problem you have is the apostrophe is ending the SQL query on '$loc' so the query actually reads:
... VALUES ('Giant's Capital',
Syntax highlight should indicate why that's a problem :)
Use something like: mysql_real_escape_string() to escape your $_POST data before inputting.
$loc = mysql_real_escape_string($_POST['new']);

Doesn't explain why it should work
You have 3 fields and 2 values.
doesn't fix their error
Yes, it does.
uses obsolete code, and is wide open to SQL injections
It isn’t my code. I am adapting OPs code, I am not trying to write it from scratch. Also, I guess, you forgot to mention that mysql function is deprecated since 5.5
Further, although the fact that the code is SQL injectable is good to mention it does not in my opinion constitute an actual answer. It's a comment at best. ie. "hey btw did you know you misspelled a word?" or some such. An editorial nitpick. If questions are going to be closed as duplicates of SQL injection questions then 80% of the questions here would have to be closed as dupes.
If the OPs wants to know about SQL injection please refer to this site
Oh, btw,this is the code:
<?php
$loc=$_POST["new"];
$url1 ="https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=".$loc;
$opf = file_get_contents($url1);
$data = json_decode($opf, true);
$titles = array();
foreach ($data['query']['pages'] as $page) {
$des = $page['extract'];
}
$con = mysql_connect("localhost","root","");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("location", $con);
$url = "http://upload.wikimedia.org/wikipedia";
echo $sql="INSERT INTO `search`(`name`, `text`) VALUES ('$loc', '$des');";
mysql_query($sql) or die(mysql_error());
echo "1 record added";
mysql_close($con);
?>

Related

Error in an update mysql query execution with php and mysqli [duplicate]

This question already has an answer here:
mysqli insert error incorrect syntax [duplicate]
(1 answer)
Closed 3 years ago.
I am trying to do a small project. My task to create an update form with HTML and PHP. But I am getting this error given below:
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 standard dummy text ever since the 1500s, when an unknown printer.' , exp_time' at line 1
I am using Laragon for php and HeidiSQL 9.5 for mysql server.
My database connection is okay. I can fetch data from the database using the SELECT query in the same file. I think something is wrong in my code. So please help me the code is given below:
<?php
require('auth.php');
require('db.php');
$id=$_REQUEST['id'];
$query = "SELECT * FROM experience where expid='".$id."'";
$result = mysqli_query($con,$query) or die ( mysqli_error($con));
$row = mysqli_fetch_assoc($result);
$status = "";
if(isset($_POST['new']) && $_POST['new']==1)
{
$exp_title = $_REQUEST['exp_title'];
$exp_description = $_REQUEST['exp_description'];
$exp_time = $_REQUEST['exp_time'];
$update="UPDATE experience SET exp_title='".$exp_title."' , exp_description='".$exp_description."' , exp_time='".$exp_time."'
WHERE expid='".$id."'";
mysqli_query($con, $update) or die ( mysqli_error($con));
$status = "Record Updated Successfully. </br></br>
<a href='dashboard.php'>View Updated Record</a>";
echo '<p style="color:#FF0000;">'.$status.'</p>';
}else {
?>
You need to escape the single quotes using php's str_replace, e.g.:
$exp_title = str_replace("'", "\'", $_REQUEST['exp_title']);
$exp_description = str_replace("'", "\'", $_REQUEST['exp_description']);
$exp_time = $_REQUEST['exp_time'];
$update="UPDATE experience SET exp_title='".$exp_title."' , exp_description='".$exp_description."' , exp_time='".$exp_time."'
WHERE expid='".$id."'";
However, you should really really use preparedstatements instead of concatenating strings and escaping characters, e.g.:
$exp_title = $_REQUEST['exp_title'];
$exp_description = $_REQUEST['exp_description'];
$exp_time = $_REQUEST['exp_time'];
$stmt = $conn->prepare("UPDATE experience SET exp_title= ?, exp_description = ?, exp_time = ? WHERE expid = ?");
$stmt->bind_param("types", $exp_title, $exp_description, $exp_time, $id);

mysqli_query() generating query error [duplicate]

This question already has answers here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
How can I prevent SQL injection in PHP?
(27 answers)
Closed 5 years ago.
I am trying to store form data into database using mysqli but it is generating query error my code is given below....
When ever I try to submit the database connection is generating.. the $_POST is working perfectly.. the error only generating by mysqli_query..
<?php
$name = $_POST["firstname"] . " " . $_POST["lastname"];
$email = $_POST["email"];
$happen = $_POST["whendidhappen"];
$howlong = $_POST["howlong"];
$howmany = $_POST["howmany"];
$describe = $_POST["describe"];
$whattheydid= $_POST["whattheydid"];
$seenmycat = $_POST["seenmycat"];
$anythingelse = $_POST["anythingelse"];
$dbc = mysqli_connect('localhost','root','','abductionreport')
or die('Database connection error');
$query = "INSERT INTO abductionform (firstname, lastname, email,whendidhappen, howlong, describe, whattheydid, seenmycat,anythingelse)VALUES('$name','$name','$email','$happen','$howlong', '$howmany','$describe','$whattheydid', '$seenmycat','$anythingelse')";
$result = mysqli_query($dbc,$query) or die ("Query Error");
mysqli_close($dbc);
?>
<h3>Aliens Abducted Me - Report an Abduction</h3>
<p>Thanks for Submiting the form.</p>
<?php
echo "$name it happend to you on $happen it take $howlong <br>";
echo "Number of aliens: $howmany<br>";
echo "Describe: $describe<br>";
echo "What they did to you: $whattheydid<br>";
echo "Have you seen my cat: $seenmycat<br>";
echo "Anything else : $anythingelse<br>";
echo "Your Email Address is : $email<br>";
?>
DESCRIBE is a mysql keyword. Wrap the column name in backticks. For that matter wrap your table and all columns in backticks. Always check that $_POST elements exist with isset () before trying to access them. Use mysqli prepared statements with placeholders for improved security. Always perform error checking BEFORE posting to SO.
You also have 9 columns and 10 values in your query - this will cause a failure every time.

How would I fetch variables from an URL and put it into my Database? [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 5 years ago.
So I've looked up many tutorials on how to get variables like http://example.net/pb.php?id=1&affsub=stringhere&key=123abc and then when that page is accessed I want it to be put into my database. But I have tried doing so by using this piece of code. And when accessing the page using ?id=1&affsub=stringhere&key=123abc it doesn't show any errors on the page and it also doesn't put it in the database as well. Now I'm not sure what is happening or what I need to do for that to work.
<?
if( $_POST )
{
$con = mysql_connect("localhost","user","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("tbl", $con);
$id = $GET['id'];
$affsub = $_GET['affsub'];
$key = $_GET['key'];
$id = mysql_real_escape_string($id);
$affsub = mysql_real_escape_string($affsub);
$key = mysql_real_escape_string($key);
$query = "
INSERT INTO `tbl`.`users` (`id`, `affsub`, `key`) VALUES ('$id',
'$affsub', '$key');";
mysql_query($query);
echo "<h2>User added to system.</h2>";
mysql_close($con);
}
?>
Everything is inside if ($_POST) so you need to to retrieve the data from $_POST[] instead of $_GET[] (and the typo. error $GET['id']). In addition, the parameters should not be in the URL - that would normally indicate a form using the get method but for updating a database you normally want to use method="post" in your form.

Invalid query: You have an error in your SQL syntax

<?php
mysql_connect("mysql6.000webhost.com","a6124751_murali1","***");
$db= mysql_select_db("a6124751_signup");
$topic=$_GET["Topic"];
$question=$_GET["Question"];
$company =$_GET["Company"];
$query = "INSERT INTO questions (topic, question, company) VALUES ($topic, $question, $company)";
$sql1=mysql_query($query);
if (!$sql1) {
die('Invalid query: ' . mysql_error());
}
?>
this is my php code in server where there is a table named 'questions' and i am trying to insert the data into it from the input got from the GET method using form at front end, i can figure out that data is coming properly from the client which i have checked using echo. I am getting an error as
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 'name, type your question here, company)' at line 1
Don't know what is the error in the query. anyone find it out asap. thank you
You need to quote your values
('$topic', '$question', '$company')
since those are strings.
Plus, you should escape your data for a few reasons. Not let MySQL complain about certain characters such as hyphens etc., and to protect against SQL injection.
Use prepared statements:
https://en.wikipedia.org/wiki/Prepared_statement
Reference(s):
https://en.wikipedia.org/wiki/SQL_injection
How can I prevent SQL injection in PHP?
http://php.net/manual/en/function.mysql-real-escape-string.php
Edit:
As an example using your present MySQL API:
$topic = mysql_real_escape_string($_GET['topic']);
$question = mysql_real_escape_string($_GET['question']);
$company = mysql_real_escape_string($_GET['company']);
I don't know what your inputs are called, so that's just an example.
You mentioned about using $_GET for debugging but using a POST method.
Change all $_GET to $_POST above.
Try this
<?php
$db = mysqli_connect('mysql6.000webhost.com', 'a6124751_murali1', 'default#123', 'a6124751_signup');
if (!$db) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
$topic = $_GET["Topic"];
$question = $_GET["Question"];
$company = $_GET["Company"];
$query = "INSERT INTO questions (topic, question, company) VALUES ('$topic', '$question', '$company')";
$sql1=mysqli_query($db, $query);
if(!$sql1)
{
die('Invalid query: ' . mysqli_error($db));
}
?>
Fixes in your code
The mysql extension is deprecated and will be removed in the future:
use mysqli or PDO instead
You need to quote your values ('$topic', '$question', '$company')
You have to put the values in single qoutes, if that are char types:
$query = "INSERT INTO questions (topic, question, company) VALUES ('$topic', '$question', '$company')";
But you should not longer use the deprecated mysql_*API. Use mysqli_* or PDO with prepared statements.

PHP attempt to update a MySQL database doesn't update anything

I have my code below to update a my MySQL database, it's running but is not updating the database when I check rcords using phpmyadmin. plae hlp me.
$database = "carzilla";
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$manufacturerTable = $_POST[vehicleManufacturer];
$numberToSearch = $_POST[vehicleIdNo];
$engineType = $_POST[engineType];
$engineCC = $_POST[engineCC];
$year = $_POST[year];
$numberofDoors = $_POST[numberofDoors];
$tireSize = $_POST[tireSize];
$chasisNumber = $_POST[chasisNumber];
$vehicleMake = $_POST[vehicleMake];
$price=$_POST[price];
mysql_select_db("$database", $con);
$sql = mysql_query("UPDATE $manufacturerTable SET username='vehicleMake',
engineType='$engineType', engineCC='$engineCC', year='$year', chasisNo='$chasisNumber', numberOfDoors='$numberofDoors' ,numberOfDoors='$numberofDoors', tireSize='$tireSize', price='$price' WHERE `index` ='$id'");
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo 'record has been successfuly';
mysql_close($con);
?>
Take a good look at your query. You are referring to PHP variables in several different fashions in the same statement. In the query $manufacturerTable is just $manufacturerTable, you encase a few others in single quotes, some of which you remove the $ from, others you do not. I know I preach this far too often, but you should really look into using prepared statements. They take all the guess work out of using variables in your queries, and they prevent you from being victimized by injection hacks. But the short answer here is that you are not referencing your variables correctly in the query.
Sometimes putting the variables directly in the syntax can cause issues. Have you tried to use concatenation for the query.
$query = "UPDATE ".$manufacturerTable." SET username='vehicleMake', engineType='."$engineType."', engineCC='".$engineCC."', year='".$year."', chasisNo='".$chasisNumber."', numberOfDoors='".$numberofDoors."' ,numberOfDoors='".$numberofDoors."', tireSize='".$tireSize."', price='".$price."' WHERE index =".$id;
$sql = mysql_query($query); # this should be put in the if else
If index is number based you do not need the '' surrounding it. Plus is username='vehicleMake' or is it a variable. if it is a variable, add the $ or use concatenation like the rest. Your SQL check should be something like follows.
if (mysql_query($query))
{
echo 'record has been successfuly';
} else {
die('Error: ' . mysql_error() . ' | ' . $query);
}
The reason you export the query is so you can try it manually to make sure it works and what error you may be getting. phpMySQL can show a different error then the mysql_error() at times
Plus you should be escaping all input that is user entered using mysql_escape_string() or mysql_real_escape_string()

Categories