insert into table error [closed] - php

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
here is my code
<?php
require '../connect/conn.php';
$quest = $_POST['domanda'];
$a1 = $_POST['risposta1'];
$a2 = $_POST['risposta2'];
$a3 = $_POST['risposta3'];
$a4 = $_POST['risposta4'];
$ins = "INSERT INTO melaraider SET domanda = '$quest',riposta1 = '$a1',riposta2 = '$a2',riposta3 = '$a3',riposta4 = '$a4'";
$result = mysqli_query($con, $ins);
if(!$result){
die("query error $ins:" . mysql_error());
}
mysql_close();
echo "all done!";
?>
everytime I execute that code I get a query error:
query error INSERT INTO melaraider SET domanda = 'quanto fa 2 +2?',riposta1 = '4',riposta2 = '6',riposta3 = '9',riposta4 = '2':
I really don't understand what is my mistake...
can someone please help me out?
Its a local test so I cant show a live version.

Try this code:
<?php
require '../connect/conn.php';
$quest = $_POST['domanda'];
$a1 = $_POST['risposta1'];
$a2 = $_POST['risposta2'];
$a3 = $_POST['risposta3'];
$a4 = $_POST['risposta4'];
$ins = "INSERT INTO melaraider (domanda, riposta1, riposta2, riposta3, riposta4) VALUES('" . $quest . "','" . $a1 . "','" . $a2 . "','" . $a3 . "','" . $a4 . "')";
$result = mysqli_query($con, $ins);
if(!$result){
die("query error $ins:" . mysql_error());
}
mysql_close();
echo "all done!";
?>

I believe your syntax is a little off. If using all the fields just specify just the data:
$ins = "INSERT INTO melaraider VALUES ('$quest','$a1',$a2','$a3','$a4')";
or specify the fields then data
$ins = "INSERT INTO melaraider (domanda,riposta1,riposta2,riposta3,riposta4)
VALUES ('$quest','$a1',$a2','$a3','$a4')";
http://www.w3schools.com/php/php_mysql_insert.asp
EDIT: Not quite fast enough!

You are using a combination of INSERT + UPDATE code, you can see here the full insert options.
In your case you should use
$ins = "INSERT INTO melaraider('domanda', 'riposta1', 'riposta2', 'riposta3', 'riposta4') VALUES('$quest','$a1','$a2','$a3','$a4');";
Cheers!

You are using the wrong syntax for an INSERT query.
Here are the docs:
http://dev.mysql.com/doc/refman/5.6/en/insert.html
Your query should look like:
INSERT INTO melaraider (domanda, riposta1, riposta2, riposta3, riposta4) VALUES ('$quest', '$a1', '$a2', '$a3', '$a4');
However, before you go any further with this code, you need to look into properly sanitizing your inputs. You should never directly put POST data into a query. See: What's the best method for sanitizing user input with PHP?

You should use Mysqli and not Mysql, you mixed them togheter.
Your insert query syntax was also wrong.
<?php
require '../connect/conn.php';
$quest = $_POST['domanda'];
$a1 = $_POST['risposta1'];
$a2 = $_POST['risposta2'];
$a3 = $_POST['risposta3'];
$a4 = $_POST['risposta4'];
$ins = "INSERT INTO melaraider (domanda, riposta1, riposta2, riposta3, riposta4)
VALUES ('$quest', '$a1', $a2', '$a3', '$a4')";
$result = mysqli_query($con, $ins);
if(!$result){
echo "query error $ins:" . mysqli_error($con); //Changed from mysql_error(). Changed from die() to echo, because you always should do mysqli_close()
} else {
echo "all done!";
}
mysqli_close($con); //changed from mysql_close()
?>
Like #patsweet said, you should think about sanitize the data before executing the query.

Change
$ins = "INSERT INTO melaraider SET domanda = '$quest',riposta1 = '$a1',riposta2 = '$a2',riposta3 = '$a3',riposta4 = '$a4'";
to this:
$ins = "INSERT INTO melaraider(domanda, riposta1, riposta2, riposta3, riposta4) VALUES('$quest','$a1', '$a2', '$a3', '$a4')";
NB: You only use SET when you are updating a value on the database.
For Example:
$ins = "UPDATE melaraider SET domanda = '$quest' WHERE mel_id = some_id";

Related

Error 500 when using variables to instert to SQL database [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 5 years ago.
I got this code, and it gives me an error 500.
I probaly got something wrong here, but i really need some help.
Here's my code
<?php include('index.php'); ?>
<?php include('config.php'); ?>
<?php
$fornavn = $_POST['fornavn'];
$efternavn = $_POST['efternavn'];
$postnummer = $_POST['postnummer'];
$alder = $_POST['alder'];
$sql = INSERT INTO medlemmer (fornavn, efternavn, postnummer, alder)
VALUES ('$fornavn', '$efternavn', '$postnummer', '$alder');
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
The POST tag is the same in index.php and so.
Please help.
Thanks in advance!
You need to put your query in string "" first
<?php include('index.php'); ?>
<?php include('config.php'); ?>
<?php
$fornavn = $_POST['fornavn'];
$efternavn = $_POST['efternavn'];
$postnummer = $_POST['postnummer'];
$alder = $_POST['alder'];
$sql = "INSERT INTO medlemmer (fornavn, efternavn, postnummer, alder)
VALUES ('$fornavn', '$efternavn', '$postnummer', '$alder');";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Also use prepared statement to prevent from sql injection
Turn PHP error ON so that you can get errors. Add following line in your PHP file
ini_set('display_errors',1);
error_reporting(E_ALL);
to first see any more possible errors, as it may help to find the problem type this at the beginning:
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
Personally as I always used "" around the SQL-Query, and I see you haven't done it, maybe you should add them too so make it:
$sql = "INSERT INTO medlemmer (fornavn, efternavn, postnummer, alder)VALUES
('$fornavn', '$efternavn', '$postnummer', '$alder')";
Also I assume $conn is defined in your config.php?
As mentioned in comments first make sure you have error reporting enabled error_reporting(E_ALL); and ini_set('display_errors',1).
Also look at this SQL query string which hasn't been wrapped in quotes.
$sql = INSERT INTO medlemmer (fornavn, efternavn, postnummer, alder)
VALUES ('$fornavn', '$efternavn', '$postnummer', '$alder');
Should be
$sql = "INSERT INTO medlemmer (fornavn, efternavn, postnummer, alder)
VALUES ('$fornavn', '$efternavn', '$postnummer', '$alder')";

MySQL insert errors

It's pretty much one of my first times working with MYSQL, and I can't seem to fix this one error I keep getting. I'm trying to store data to a table which has an auto_increment on its id (first column).
The error I keep getting is this:
"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 'voorletters ='asd', tussenvoegsel ='', achternaam ='', roepnaam ='', adres ='', ' at line 1"
I just filled the textboxes with a little bit of rubish, there are no columns that require data either. Here is the code I use:
if(isset($_POST['save']))
{
$voorletters = $_POST['voorletters'];
$tussenvoegsel = $_POST['tussenvoegsel'];
$achternaam = $_POST['achternaam'];
$roepnaam = $_POST['roepnaam'];
$adres = $_POST['adres'];
$postcode = $_POST['postcode'];
$plaats = $_POST['plaats'];
$geslacht = $_POST['geslacht'];
$emailadres = $_POST['emailadres'];
$telefoonnummer = $_POST['telefoonnummer'];
$mobielenummer = $_POST['mobielenummer'];
$geboortedatum = $_POST['geboortedatum'];
$bsn = $_POST['bsn'];
mysql_query("INSERT INTO `naw` "
. "voorletters ='$voorletters', "
. "tussenvoegsel ='$tussenvoegsel', "
. "achternaam ='$achternaam', "
. "roepnaam ='$roepnaam', "
. "adres ='$adres', "
. "postcode ='$postcode', "
. "plaats ='$plaats', "
. "geslacht ='$geslacht', "
. "emailadres ='$emailadres', "
. "telefoonnummer ='$telefoonnummer', "
. "mobielenummer ='$mobielenummer', "
. "geboortedatum ='$geboortedatum', "
. "bsn ='$bsn' "
. "WHERE id = '$id'")
or die(mysql_error());
If this isn't enough information, please tell me. I've tried a lot of things, but I can't seem to figure it out.
You mix up insert and update syntax. Replace
INSERT INTO `naw` voorletters ='$voorletters'...
with
UPDATE `naw` set voorletters ='$voorletters'....
And you should really use Prepared Statements to avoid syntax errors and SQL injections due to user input.
You have a wrong syntax
The INSERT syntax is
INSERT INTO `YourTableName`(`Field1`, `Field2`, `Field3`, `Field4)
VALUES ('value-1','value-2','value-3','value-4')
The UPDATE syntax is
UPDATE `YourTableName`
SET `Field1`='value-1',`Field2`='value-2',`Field3`='value-3',`Field4`='value-4'
WHERE YourConditions
Just use following code. Make sure that you are inserting data for every field sequentially-
mysql_query("INSERT INTO `naw` VALUES(
'".$voorletters."',
'".$tussenvoegsel."',
'".$achternaam."',
'".$roepnaam."',
'".$adres."',
'".$postcode."',
'".$plaats."',
'".$geslacht."',
'".$emailadres."',
'".$telefoonnummer."',
'".$mobielenummer."',
'".$geboortedatum."',
'".$bsn."')")
or die(mysql_error());
You should remove the `` around naw, it's ok in phpmyadmin but quite messy almost every where else.
And you souldn't concatenate every line, do it in one "..." and use backspace to make it more readable.
So:
mysql_query("INSERT INTO naw
VALUES('$voorletters',
'$tussenvoegsel',
... ,
WHERE id = '$id'");//you can't do that, maybe you should use an UPDATE

PHP SQL syntax error MYSQL UPDATE [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 7 years ago.
So for a long time this code worked but now all of the sudden i get this 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 ''j_users' SET patient = '', year = '', gender = '', age = '', height = 'Select a' at line 1
HELP!
define('DB_NAME', 'DATABASE');
define('DB_USER', 'USERNAME');
define('DB_PASSWORD', 'PASSWORD');
define('DB_HOST', 'localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
if (!$db_selected) {
die('Can\'t use ' . DB_NAME . ': ' . mysql_error());
}
$value = htmlspecialchars($_POST['patient']);
$value4 = htmlspecialchars($_POST['year']);
$value5 = htmlspecialchars($_POST['gender']);
$value6 = htmlspecialchars($_POST['age']);
$value7 = htmlspecialchars($_POST['height']) . '.' . htmlspecialchars($_POST['height_inch']);
$value8 = htmlspecialchars($_POST['weight']);
$value9 = htmlspecialchars($_POST['foot_length']);
$value10 = htmlspecialchars($_POST['sheight']) . '.' . htmlspecialchars($_POST['sheight1']);
$value11 = htmlspecialchars($_POST['Amputation']);
$value13 = htmlspecialchars($_POST['Side']);
$value16 = htmlspecialchars($_POST['Flesh']);
$value18 = htmlspecialchars($_POST['Activity']);
$value21 = htmlspecialchars($_POST['practitioner']);
$value22 = htmlspecialchars($_POST['phone']);
$value23 = htmlspecialchars($_POST['email']);
$value24 = htmlspecialchars($_POST['Account']);
$value25 = htmlspecialchars($_POST['companyname']);
$value26 = htmlspecialchars($_POST['streetaddress']);
$value27 = htmlspecialchars($_POST['city']);
$value28 = htmlspecialchars($_POST['state']);
$value29 = htmlspecialchars($_POST['zip']);
$value30 = htmlspecialchars($_POST['companyname2']);
$value31 = htmlspecialchars($_POST['streetadress2']);
$value32 = htmlspecialchars($_POST['city2']);
$value33 = htmlspecialchars($_POST['state2']);
$value34 = htmlspecialchars($_POST['zip2']);
$value35 = htmlspecialchars($_POST['foot']);
$value39 = htmlspecialchars($_POST['purchaseorder']);
$value40 = htmlspecialchars($_POST['radio']);
$value41 = htmlspecialchars($_POST['lightflesh2']);
$value42 = htmlspecialchars($_POST['darkfleah2']);
$value43 = htmlspecialchars($_POST['foamcalf']);
$value44 = htmlspecialchars($_POST['additional']);
$value45 = htmlspecialchars($_POST['Sock1']);
$value46 = htmlspecialchars($_POST['Sock2']);
$value47 = htmlspecialchars($_POST['Sock3']);
$value48 = htmlspecialchars($_POST['day']);
//$sql = "INSERT INTO order_form (patient, newamputee, yearamputee, year, gender, age, height, weight, foot_length, sheight, ak, bk, left1, right1, bilateral, light_flesh, dark_flesh, k2, k3, k4, k4_extrme, practitioner, email, Account, companyname, streetaddress, city, state, zip, companyname2, streetaddress2, city2, state2, zip2, UltraStride, ActiveStride, NaturalStride, K2_ComfortStride, purchaseorder, radio, lightflesh2, darkfleah2, foamcalf, additional, Sock1, Sock2, Sock3, ground, thirdday, twoday, nextday) VALUES ('$value', '$value2', '$value3', '$value4', '$value5', '$value6', '$value7', '$value8', '$value9', '$value10', '$value11', '$value12', '$value13', '$value14', '$value15', '$value16', '$value17', '$value18', '$value19', '$value20', '$value21', '$value22', '$value23', '$value24', '$value25', '$value26', '$value27', '$value28', '$value29', '$value30', '$value31', '$value32', '$value33', '$value34', '$value35', '$value36', '$value37', '$value38', '$value39', '$value40', '$value41', '$value42', '$value43', '$value44', '$value45', '$value46', '$value47', '$value48', '$value49', '$value50', '$value51')";
$update = "UPDATE 'j_users'
SET patient = '$value', year = '$value4', gender = '$value5', age = '$value6', height = '$value7', weight = '$value8', foot_length = '$value9', sheight = '$value10', Amputation = '$value11', Side = '$value13', Flesh = '$value16', Activity = '$value18', practitioner='$value21', phone='$value22', email='$value23', Account = '$value24', companyname = '$value25', streetadress='$value26', city='$value27', state='$value28', zip='$value29', companyname2='$value30', streetadress2='$value31', city2='$value32', state2='$value33', zip2='$value34', foot='$value35', purchaseorder='$value39', radio='$value40', lightflesh2='$value41', darkfleah2='$value42', foamcalf='$value43', foamcalf='$value44', Sock1='$value45', Sock2='$value45', Sock3='$value46', day='$value47'
WHERE user_login = '" . $user . "'";
if (!$update) {
die('Invalid query: ' . mysql_error());
}
mysql_query($update, $link);
if (!mysql_query($update)) {
die('Error: ' . mysql_error()) ;
mysql_close();
}
The immediate cause of the error, as pointed out by Uueerdo in the comment is the incorrect symbol (single-quote instead of a backtick) in the quoting of the name of the table - which in this case does not need to be quoted at all as it is fixed and contains no special characters.
There are other issues in the code which we will leave alone for now as they do not immediately affect the issue, but I will update the answer if OP is interested in other things that would be good to fix.
UPDATE - things to fix:
As pointed out by Drew and Uueerdo in the comments, migrate from the deprecated mysql_ interface to mysqli_ or PDO.
The values entered by the user should be escaped with mysql_real_escape_string() (with the current interface), mysqli_escape_string() or via PDO parameter holders (?) depending on the interface, but not with htmlspecialchars(). If HTML escaping is needed, it should be done immediately before the HTML is to be displayed, not at the time it is stored in the database.
Note that most of your input names match the database column names. Thus you might be better off fetching the fields from the database via SHOW FIELDS once into a hard-coded array, editing it to exclude the irrelevant ones (another option to fetch it dynamically and fix up the array once it is fetched), and adding some logic to deal with the exceptions like height and height_inches as you iterate through the array and generate your query in a loop. The code thus becomes more flexible and easier to maintain.
Create some wrapper interface for your database access rather than directly accessing MySQL API. This way should a need arise to change the interface (e.g. mysql_ to mysqli) it is a matter of fixing a few calls in just one module rather than a major code change. You are also able to add things like query logging, automatic query EXPLAIN in trace mode, performance timing, and whatever else you might think of with regard to your queries, rather easy.

INSERT INTO in php and SQL syntax error [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
Im self learning mySQL and php few days and now Im stuck on this error and cant help myself. Can you look at code, Thanks!
this is 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 ')' at line 7
here is the page
switch($_GET['action']) {
case 'add':
switch($_GET['type']) {
case 'movie':
$query = 'INSERT INTO
movie
(movie_name, movie_year, movie_type)
VALUES
("' . $_POST['movie_name'] . '",
' . $_POST['movie_year'] . ',
' . $_POST['movie_type'] . ')';
break;
}
break;
}
if (isset($query)) {
$result = mysql_query($query, $db) or die(mysql_error($db));
}
I think problem may be in here
<td><select name='movie_type'>
<?php
$query = 'SELECT movietype_label FROM movietype ORDER BY movietype_id';
$result = mysql_query($query, $db) or die (mysql_error($db));
while ($row = mysql_fetch_assoc($result)) {
foreach ($row as $value) {
echo '<option value="' . $row['movietype_id'] . '">';
echo $row['movietype_label'] . '</option>';
}
}
?>
</select></td>
and here is print_r on
Array(
[movie_name] => asd
[movie_type] =>
[movie_year] => 2015
[submit] => ADD)
Shouldn't you be using a double quote " instead of single quote ' like below. You are mixing single and double quote.
$query = "INSERT INTO
movie
(movie_name, movie_year, movie_type)
VALUES
('" . $_POST['movie_name'] . "',
'" . $_POST['movie_year'] . "',
'" . $_POST['movie_type'] . "')";
Granted this is ugly, but would be surprised if it fails.
$query = "INSERT INTO
movie (movie_name, movie_year, movie_type)
VALUES
('"
. $_POST['movie_name'] . "','"
. $_POST['movie_year'] . "','"
. $_POST['movie_type'] . "')";
Also, you need to cleanse your data. Data acted upon directly from user without cleansing, or sent through proper separation of code, can, and someday will, contain sql injection.
Ugly code like the above starts to take on some beauty with mysqli and pdo, plus the parameters are safely separated, and all the moaning about injection goes away.

Database insertion error [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 9 years ago.
The below echo statement,
$statement = "INSERT INTO $tbl_name VALUES(" . $_GET['username'] . "," . $_GET['password'] . "," . $_GET['PasswordHintQuestion'] . "," . $_GET['PasswordHintAnswer'] . "," . $_GET['firstname'] . "," . $_GET['lastname'] . "," . $_GET['genderSelect'] . "," . $_GET['date_in_format'] . "," . $_GET['nationality'] . "," . $_GET['refEmail'] . ")" ;
echo $statement;
gave the ouput as,
INSERT INTO ge_user_table VALUES([object HTMLInputElement],[object HTMLInputElement],[object HTMLInputElement],[object HTMLInputElement],[object HTMLInputElement],[object HTMLInputElement],[object NodeList],[object HTMLSelectElement]/[object HTMLSelectElement]/[object HTMLSelectElement],[object HTMLInputElement],[object HTMLInputElement])Database Insertion fault on registration
But during insertion into database I got the 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 '[object HTMLInputElement],[object HTMLInputElement],[object
HTMLInputElement],[o' at line 1
But, the below query is working fine.
INSERT INTO ge_user_table VALUES('Muthu2','1234','Who are you?','Iam Indian','Muthu','Ganapathy','MALE','1991-12-21','Indian','abc#abc.com');
EDIT :
I have changed the code to,
$username = mysql_escape_string($_GET['username']);
$password = mysql_escape_string($_GET['password']);
$hintQues = mysql_escape_string($_GET['PasswordHintQuestion']);
$hintAns = mysql_escape_string($_GET['PasswordHintAnswer']);
$firstname = mysql_escape_string($_GET['firstname']);
$hintQues = mysql_escape_string($_GET['lastname']);
$gender = mysql_escape_string($_GET['genderSelect']);
$date = mysql_escape_string($_GET['date_in_format']) ;
$nationality = mysql_escape_string($_GET['nationality']) ;
$email = mysql_escape_string($_GET['refEmail']) ;
$statement = "INSERT INTO $tbl_name VALUES('$username' ,'$password','$hintQues' ,'$hintAns','$firstname' ,'$lastname' ,".
"'$gender' ,'$date','$nationality','$email')" ;
But,the database has entry as,
Final Solution:
I have passed form.username in html instead of form.username.value. Now Got it correct.
It look like you have error in javascript. you send html DOM Node instead of value.
Also you should escape your get variables like
mysql_real_escape_string($_GET['username']);
TRY THIS
$username = mysql_escape_string($_GET['username']);
$password = mysql_escape_string($_GET['password']);
$hintQues = mysql_escape_string($_GET['PasswordHintQuestion']);
$hintAns = mysql_escape_string($_GET['PasswordHintAnswer']);
$firstname = mysql_escape_string($_GET['firstname']);
$hintQues = mysql_escape_string($_GET['lastname']);
$gender = mysql_escape_string($_GET['genderSelect']);
$date = mysql_escape_string($_GET['date_in_format']) ;
$nationality = mysql_escape_string($_GET['nationality']) ;
$email = mysql_escape_string($_GET['refEmail']) ;
$statement = "INSERT INTO $tbl_name VALUES('$username' ,'$password','$hintQues' ,'$hintAns','$firstname' ,'$lastname' ,".
"'$gender' ,'$date','$nationality','$email')" ;
echo $statement;
Always try to keep the statement as readable as possible .. also whenever string needs to be inserted .. it should be propery quoted Also always use mysql_escape_string() to avoid sql injection.
Possible problem can be ..you are passing html element itself instead of its value
Your sql syntax is wrong you can use mysql_real_escape_string but you also need to care about how you are passing values to sql.
In above query you symply passed text without quotes.
$statement = "INSERT INTO $tbl_name VALUES('".$_GET['username']."', '".$_GET['password']."', '".$_GET['PasswordHintQuestion']."', '".$_GET['PasswordHintAnswer']."', '".$_GET['firstname']."', '".$_GET['lastname']."', '".$_GET['genderSelect']."', '".$_GET['date_in_format']."', '".$_GET['nationality']."', '".$_GET['refEmail']."')" ;

Categories