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
Related
I knew that there are several similar questions, also I am aware that best practice is to keep images on server but I was told to do this way... Well I am sending base64 string from android to php webservice. I am sending it right, also tested via Postman to be sure that problem is not android but service. I have error: 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 'oX?떧?=j?b?ED?Nϯ??=?|?pv??ёQv}gX?' at line 2
<?php
header('Content-Type: text/html; charset=utf-8');
// array for JSON response
$response = array();
// include db connect class
require_once '../config/db_connect.php';
$db = new DB_CONNECT();
$host_id = $_POST['host_id'];
$name = $_POST['event_name'];
$description = $_POST['event_description'];
$date = $_POST['date'];
$photo = $_POST['photo'];
// get all products from products table
$escaped = mysql_escape_string ($photo);
$photo_blob = base64_decode($escaped);
//echo $photo_blob;
$result = mysql_query(
'INSERT INTO dogadjaj (host_id, name, description, date, photo)
VALUES ("' . $host_id . '" ,"' . $name .'", "' . $description . '", "' . $date . '", "' . $photo_blob . '");')
or die(mysql_error());
?>
Use $photo_blob = base64_encode($escaped); instead of $photo_blob = base64_decode($escaped);. You would need the base64_decode when processing the base_64 read from the database.
i am very new at MYSQL and after i created this script to update a row in the table of a MYSQL Database and run it 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 '265'', Employer_VAT_number = ''45698'', Employer_Name = ''Namtax_Ltd'', Employer' at line 3
here is the code
// username and password sent from form
$Numb=$_POST["Numb"];
$VAT=$_POST["VAT"];
$Name=$_POST["Name"];
$Addr=$_POST["Addr"];
$PO=$_POST["PO"];
// To protect MySQL injection (more detail about MySQL injection )
$Numb = stripslashes($Numb);
$VAT = stripslashes($VAT) ;
$Name = stripslashes($Name) ;
$Addr = stripslashes($Addr) ;
$PO = stripslashes($PO) ;
$Numb = "'" . mysql_real_escape_string($Numb) . "'";
$VAT = "'" . mysql_real_escape_string($VAT) . "'";
$Name = "'" . mysql_real_escape_string($Name) . "'";
$Addr = "'" . mysql_real_escape_string($Addr) . "'";
$PO = "'" . mysql_real_escape_string($PO) . "'";
$sql=("UPDATE $tb1_name SET Employer_Registration_Number ='".$Numb."', Employer_VAT_number = '".$VAT."', Employer_Name = '".$Name."', Employer_Address = '".$Addr."', Employer_Postal_Address = '".$PO."' WHERE Employer_Name = '".$Name."' ");
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "Successfully Updated";
mysqli_close($con);
?>
</body>
This here:
$Numb = "'" . mysql_real_escape_string($Numb) . "'";
Firstly, that isn't proper syntax and you're using mysqli_ to connect with, least I sure hope you are.
Those different MySQL APIs do not intermix with each other.
That should read as:
$Numb = mysqli_real_escape_string($con,$Numb);
while doing the same for the rest of your variables, following the same method outlined here.
Footnotes:
Seeing you didn't post what $tb1_name is, doubt that would be causing an issue. But just for the sake of argument, wrap that variable in ticks, just so if your table name changes to something containing a hyphen or a space, or anything that MySQL will complain about.
UPDATE `$tb1_name` SET...
Plus, since you didn't mention which MySQL API you're using to connect with, make sure it is in fact mysqli_ and not mysql_ or PDO.
It doesn't look like it, but I have to be 100% sure.
Your connection should resemble something like this:
$con = mysqli_connect("yourhost","user","pass","your_DB")
or die("Error " . mysqli_error($con));
Again, those different MySQL APIs do not intermix with each other.
Consult (PHP: Choosing an API - Manual): https://php.net/mysqlinfo.api.choosing
"I am very new at MYSQL..."
Seeing you're new to this:
Use mysqli with prepared statements, or PDO with prepared statements.
Additional notes. (as an edit)
I noticed another question you posted earlier:
https://stackoverflow.com/q/30191388/
where you said "Thank you it worked " in the answer given https://stackoverflow.com/a/30191647/
I don't get that.
How could that possibly work where you're using if (!mysqli_query($con,$sql))?
You'll need to show us the way you're connecting with here.
If you truly want to see if your query was successful, use mysqli_affected_rows().
if(mysqli_affected_rows($con)){
echo "Successfully updated.";
}
else{
echo "Not updated.";
}
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
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']."')" ;
I seem to be missing something quite fundamental here and yet my code doesn't seem to be any different to any of the numerous online tutorials that I have looked at.
What I would like is for someone to look at this and say....Oh you have forgotten to...etc;
This is what I have on a separate update page which is intended to perform the update then cycle back to the main admin page:
require_once('../Connections/MyConn.php');
$sql_statement = "UPDATE skyscrapers SET ";
$sql_image = "Ad_image = '" . $_REQUEST['image'] . "', ";
$sql_expire = "Ad_Expires = '" . $_REQUEST['expire'] . "'";
$result = mysql_query($sql_statement . $sql_image . $sql_expire . " WHERE Ad_ID=" . $_REQUEST['ADID']);
if (!$result) {
echo("<p>Error performing query: " . mysql_error() . "</p>");
exit();
}
mysql_close ($MyConn);
header("location:Admin_skyscrapers.php");
However when I run this I get the following error:-
"Error performing query: No database selected"
Well, haven't I selected the database in the connection script which already works everywhere else?
I realise the code isn't very pretty and I am being naughty using the url to pass variables at the moment - I do promise to change this when I get it to work :)
So, any pointers would be helpful, thanks in advance.
Edit to add...
This is the connection script with the sensitive stuff redacted:-
# FileName="Connection_php_mysql.htm"
# Type="MYSQL"
# HTTP="true"
$hostname_MyConn = "*************.co.uk";
$database_MyConn = "db**********";
$username_MyConn = "dbo*********";
$password_MyConn = "*****";
$MyConn = mysql_pconnect($hostname_MyConn, $username_MyConn, $password_MyConn) or trigger_error(mysql_error(),E_USER_ERROR);
This may or may not be declared in your MyConn.php but all you need is a line:
mysql_select_db($db_name);
Where $db_name is the name of your database.
This should come before you attempt to execute the query.
For DB select you have to add mysql_select_db(DatabaseName); or
$dbconn=mysql_select_db($dbname,$MyConn);in MyConn.php
For update in Database you have to use connection variable which is in MyConn.php i.e.$MyConn as follows
$result = mysql_query($sql_statement . $sql_image . $sql_expire . " WHERE Ad_ID=" . $_REQUEST['ADID'],$MyConn);
or
$result = mysql_query($sql_statement . $sql_image . $sql_expire . " WHERE Ad_ID=" . $_REQUEST['ADID'],$dbconn);
respectively
Hope It Helps!!!!!!!
I am having trouble making this seemingly simple MySql query work. Can anyone spot the problem?
<?php
include "config.php";
$offerid = $_POST["offerid"];
$ip = $_SERVER["REMOTE_ADDR"];
mysql_query("INSERT INTO voted (offerid,ip) VALUES (".$offerid.",".$ip.")");
?>
You probably want some single quotes:
"INSERT INTO voted (offerid,ip) VALUES ('" . $offerid . "','" . $ip . "')"
You should also use intval and mysql_real_escape_string to avoid SQL injection vulnerabilities:
$sql = "INSERT INTO voted (offerid,ip) VALUES (" .
intval($offerid). ", '" .
mysql_real_escape_string($ip) . "')";
Another alternative which may be easier to read is to use sprintf:
$sql = sprintf("INSERT INTO voted (offerid, ip) VALUES (%d, '%s')",
$offerid, mysql_real_escape_string($ip));
To place a string value into query, you must perform 2 actions on it:
enclose it in quotes
and escape special characters.
So, query must be like this:
INSERT INTO voted (text) VALUES ('I\'m a programmer')
Armed with this knowledge, you can easily write a code to make valid query:
$offerid = mysql_real_escape_string($_POST["offerid"]);
$ip = mysql_real_escape_string($_SERVER["REMOTE_ADDR"]);
$sql = "INSERT INTO voted (offerid,ip) VALUES ('$offerid','$ip')"
mysql_query($sql) or trigger_error(mysql_error().$sql);
Note the trigger_error part.
It will provide you with comprehensive information on any error
my guess would be with quotes
mysql_query("INSERT INTO voted (offerid,ip) VALUES (\"".$offerid."\",\"".$ip."\")");
<?php
include "config.php";
$offerid = $_POST["offerid"];
$ip = $_SERVER["REMOTE_ADDR"];
mysql_query("INSERT INTO voted (offerid,ip) VALUES ('".mysql_real_escape_string ($offerid)."','".mysql_real_escape_string ($ip)."')");
?>
This adds the single quote marks around the strings you are inserting - as well as mysql_real_escape_string php function that will escape (add a backslash infront of) any security risk characters.
In addition to using intval(...) and mysql_real_escape_string(...) you could use parameterized statements (or placeholders) using PEAR::DB or PEAR::MDB2:
$dsn = "mysqli://testuser:testpass#localhost/test";
$conn =& DB::connect ($dsn); // using PEAR::DB, though it's been superseded
if (DB::isError ($conn)) {
die ("Cannot connect: " . $conn->getMessage () . "\n");
}
$result =& $conn->query ("INSERT INTO voted (offerid,ip) VALUES (?,?)", array($_POST["offerid"], $_SERVER["REMOTE_ADDR"]));
if (DB::isError ($result)) {
die ("INSERT failed: " . $result->getMessage () . "\n");
}
Using placeholders and parameters is pretty common on platforms other than PHP, so it's not a bad idea to understand the basic premise behind them.
If you're interested in using DB modules like these, I'd recommend checking out Writing Scripts with PHP's PEAR DB Module by Paul DuBois. Again, the module it describes is superseded, but I find it's nonetheless interesting and informative.