MySQL Insert error - php

Ok, when trying to insert into the database I'm 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 '#email.com,
UT, 84505, NOW(), 69.169.186.192)' at
line 1"
I can't figure out the problem. Here is the code for my insert statement.
$insert_query = sprintf("INSERT INTO contacts (first_name, last_name, email, state, zip, date, ip) VALUES (%s, %s, %s, %s, %s, NOW(), %s)",
$fname,
$lname,
$email,
$state,
$zip,
$ip);
$result = mysql_query($insert_query, $connection) or die(mysql_error());
My table has the following structure:
id int(11)
first_name varchar(100)
last_name varchar(100)
email varchar(100)
state varchar(3)
zip int(10)
date datetime
ip varchar(255)

You need to quote all the string-type columns in the insert statement. Replace %s with '%s' in the sprintf format.
Please read about SQL Injection if you haven't done so already.

This may help you..
$insert_query = "INSERT INTO contacts set first_name = '$fname', last_name = '$lname', email = '$email', state = '$state', zip = '$zip', date = ". time() .", ip = '$ip')";
$result = mysql_query($insert_query, $connection) or die(mysql_error());
if you want to check query
echo $insert_query;

It would help if you could echo out the $insert_query, but it looks like you're not putting quotes around the parameters that are varchars.
$insert_query = sprintf("INSERT INTO contacts (first_name, last_name, email, state, zip, date, ip) VALUES ('%s', '%s', '%s', '%s', '%s', NOW(), '%s')",
$fname,
$lname,
$email,
$state,
$zip,
$ip);
By the way, you have an extra column in your insert - NOW doesn't appear related to a column.
I'm assuming ZIP is a varchar column, not a number, by the way.

Related

SQL syntax error MariaDB server version for the right syntax to use near ('$fname', '$lname')

require('config.php');
$sql = sprintf(
"INSERT INTO users (fname,lname,email,contact,pwd,isTeacher ) VALUES ('%s', '%s', '%s', '%s', '%s', '%s')",
$conn->real_escape_string($fname),
$conn->real_escape_string($lname),
$conn->real_escape_string($email),
$conn->real_escape_string($contact),
$conn->real_escape_string($pwd),
$isTeacher );
$conn->query($sql);
// $sql = "INSERT INTO users (fname, lname, email, contact, pwd, isTeacher) VALUES ('$fname, '$lname', '$email', '$contact, '$pwd', '$isTeacher')";
// $conn->query($sql);
if($conn=='true') { echo "Registered successfully";}
else{ echo "Issue entereing data" . $conn->error; }
}
I am trying to add data in users table. if I add data using sprintf, it works and adds just fine. but when I add using commented out syntax, it says check MariaDb syntax to use near '$fname'. What am I doing wrong in the second syntax. why do i have to use sprintf always.

MySQL not able to execute INSERT INTO [table]. Column count doesn't match value count at row 1

I'm trying to pull information from an HTML form and put this into a database using the following code:
$link = mysqli_connect("localhost", "user", "password", "MyDB");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "INSERT INTO interest (name, email, dob, address)
VALUES ('$fullname', '$email', '$dob' '$addr')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
}else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
mysqli_close($link);
It was working, and I've managed to get 2 test runs in, but now I'm getting the following error at the top of my submission page
ERROR: Could not able to execute INSERT INTO MyDB (name, email, dob,
address) VALUES ('test name', 'test#email.com', '2003-02-01'
'address'). Column count doesn't match value count at row 1
I have another variant of this which sends a PHP email, which is the file I'm using to base this database connection on.
There is also an autoincrement on ID column which is set as the primary key in the database if that makes a difference? SQL isn't my strong point unfortunately!
Given the syntax error you have in your query, being a missing comma in '$dob' '$addr'; you are open to an SQL injection and should be using a prepared statement.
Therefore, I am submitting this complementary answer for your own safety.
Here is an example of a prepared statement using the MySQLi API.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect('localhost', 'xxx', 'xxx', 'my_db');
if (!$link) {
die('Connect Error: ' . mysqli_connect_error());
}
// assuming these are the POST arrays taken from your HTML form if you're using one.
$fullname = $_POST['fullname'];
$email = $_POST['email'];
$dob = $_POST['dob'];
$addr = $_POST['addr'];
$sql = ("INSERT INTO interest (name, email, dob, address) VALUES (?, ?, ?, ?)");
$stmt = $link->prepare($sql) or die("Failed Execution");
$stmt->bind_param('ssss', $fullname, $email, $dob, $addr);
$stmt->execute();
echo $stmt->error;
echo "SUCCESS";
exit();
References:
How can I prevent SQL injection in PHP?
http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
http://php.net/pdo.prepared-statements
Foonotes:
If using the following failed because of the AI'd column:
$sql = ("INSERT INTO interest (name, email, dob, address) VALUES (?, ?, ?, ?)");
You may also try: (I used id as the AI'd column as an example)
$sql = ("INSERT INTO interest (id, name, email, dob, address) VALUES ('', ?, ?, ?, ?)");
This could be the case, as I have seen this type of SQL failure behaviour before.
You have missed comma here:
VALUES ('$fullname', '$email', '$dob' '$addr')
Thus (as it was clearly said in error text) column count doesn't mach values count.
It should be
VALUES ('$fullname', '$email', '$dob', '$addr')
You missed a comma
$sql = "INSERT INTO interest (name, email, dob, address)
VALUES ('$fullname', '$email', '$dob', '$addr')";
^here
You missed a comma:
VALUES ('$fullname', '$email', '$dob' '$addr')

INSERT results in DUPLICATE ENTRY '0' FOR KEY PRIMARY

I am using a simple php script to insert data into database but it's failing. The query just doesn't become successful without showing a single error which is why I am unable to figure out the problem. Some expert here help me please.
echo $name." ".$email." ".$pass." ".$phone." ".$area." ".$specialization." ".$city." ".$latitude." ".$longitude;
The result of echo is normal - without any null elements.
$query = mysqli_query($conn, "INSERT INTO users (name, email, pass, phone, area, specialization, hospital, city, latitude, longitude)
VALUES ('$name', '$email', '$pass', '$phone', '$area', '$specialization', '$hospital', '$city', '$latitude', '$longitude') ");
if ($query) {
echo "Status: Registeration Successful!";
// creating directory for user and storing dummy profile picture
//mkdir('../profiles/'.$email_trim, 0777);
//$result_copy = copy("img/dp.jpg.jpg", "../profiles/".$email_trim."/dp.jpg.jpg");
} else {
echo "Status: Err";
}
This "Status: Err" is always printed. I don't know why.
P.S I have double checked the database the field labels are fine.
UPDATE 1:
I added the
die(mysqli_error($conn));
statement and it says "DUPLICATE ENTRY '0' FOR KEY PRIMARY'.
PROBLEM AND SOLUTION:
The issue was that I had an 'id' field which was primary key of the table but it was not set to AUTO_INCREMENT. So, whenever I tried to insert a new record, I was actually inserting entries with duplicate PKs which was the issue. I change it to AUTO_INCREMENT and it solved the problem.
It seems you try to insert a new element with a PK = 0, but there is already a record with this key !
What is the primary key of your table ? Do you use an "id" field which is not shown in your insert statement ? Is this field AUTO_INCREMENT ?
It would be helpful to see the structure of your 'users' table.
Wild guess: looks like you may have defined an "id" column (or with whatever other name) which is primary key with default value "0", but it's not auto increment. That way you can insert 1 row and it will get "0" as "id" column's value, but you cannot insert another row because it will also try to use default value "0", which cannot happen as primary key has to be unique.
If that is the case, then please alter users table and make sure that the primary key column is also 'auto increment'.
Please check the proper error by adding below mentioned code inside else:
echo mysqli_errno($conn) . '----' . mysqli_error($conn);
<?php
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
$query = mysqli_query($conn, "INSERT INTO `users` (`name`, `email`, `pass`, `phone`, `area`, `specialization`, `hospital`, `city`, `latitude`, `longitude`)
VALUES ('$name', '$email', '$pass', '$phone', '$area', '$specialization', '$hospital', '$city', '$latitude', '$longitude') ") or die(mysqli_error());
$query = mysqli_query($conn, "INSERT INTO `users` (`name`, `email`, `pass`, `phone`, `area`, `specialization`, `hospital`, `city`, `latitude`, `longitude`)
VALUES ('$name', '$email', '$pass', '$phone', '$area', '$specialization', '$hospital', '$city', '$latitude', '$longitude') ");
use ` Tick maybe because there's some reserved word in your fields.
I think you doubled your close parenthesis and do not put $conn inside the query..
$query = "INSERT INTO users (name, email, pass, phone, area, specialization, hospital, city, latitude, longitude)
VALUES ('$name', '$email', '$pass', '$phone', '$area', '$specialization', '$hospital', '$city', '$latitude', '$longitude')";
mysqli_query($query, $conn);
Something like this. I hope this helps

You have an error in your SQL syntax Mysql

My sql query is :
"INSERT INTO
order customer_id = $customer_id
, firstname = '".$firstname."'
, lastname = '".$lastname."'
, email = '".$email."'
, telephone = '".$telephone."'
, fax = '".$fax."'
, ip = '".$ip."'
, date_added = NOW()
, date_modified = NOW()
";
I get the error
Notice: 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 'order customer_id =1,firstname ='kuldeep',lastname
='pathak',email ='kuldeep.pat' at line 1 Error No: 1064
You didnt understand how to write SQLs as it seems.
$sql = 'INSERT INTO `order` (customer_id, firstname, blablabla) VALUES ('.$custormer_id.','.$firstname.','.$blablabla.')';
Please look at some basic tutorials about SQL.
"INSERT INTO
`order` SET customer_id = " . $customer_id . "
, firstname = '".$firstname."'
, lastname = '".$lastname."'
, email = '".$email."'
, telephone = '".$telephone."'
, fax = '".$fax."'
, ip = '".$ip."'
, date_added = NOW()
, date_modified = NOW()
";
Should be alright. DonĀ“t forget to escape your data though.
Try
"INSERT INTO `Order` (customer_id, firstname, lastname, email, telephone, fax, ip, date_added, date_modified)
VALUES ($customer_id, '$firstname', '$lastname', '$email', '$telephone', '$fax', '$ip', NOW(), NOW())"
The right syntax is : INSERT INTO tablename (columns) VALUES (values);
If you're likely to have user submitted fields in the dataset or appostrophes or anything else that could cause problems for any reason you'd want something more like
$query = sprintf("INSERT INTO `table` (`Name`, `Email`, `AnotherField`) VALUES ('%s', '%s', '%s'",
mysql_real_escape_string( $_POST['Name'] ),
mysql_real_escape_string( $_POST['Email'] ),
mysql_real_escape_string( $_POST['AnotherField'] )
);
This will sanitise your inputs as well
Use prepared statement to avoiding sql injection.
$custormer_id = "2000";
$firstname = "first name";
$etc = "some other values";
$mysqli = new mysqli('localhost', 'user', 'password', 'database');
$stmt = $mysqli->prepare("INSERT INTO order(customer_id, firstname, etc) VALUES (?, ?, ?)");
$stmt->bind_param('iss', $custormer_id, $firstname, $etc);
// first parameter is corresponding variable type of inserting values,eg i=interger, s=string
$stmt->execute();
$stmt->close();
http://php.net/manual/en/mysqli-stmt.bind-param.php

PHP Wrong Parameters

I'm trying to make a registration page but PHP is telling me that I have the wrong parameters, which doesn't make sense unless I need to add a parameter for the auto-incremental primary ID key.
Here's my SQL query call:
mysql_query("INSERT INTO Users (username, password, fname, lname, email) VALUES ('%s', '%s', '%s', '%s, '%s')",
mysql_real_escape_string($username),
mysql_real_escape_string($password),
mysql_real_escape_string($first),
mysql_real_escape_string($last),
mysql_real_escape_string($email)) or die(mysql_error());
It gives me the wrong paramater count on the last line in this code block. Any ideas? I copied and pasted the row-names straight from my database.
my table is as follows:
id - int(11) - auto-incrementing
username - varchar(20)
password - varchar(20)
fname - varchar(35)
lname - varchar(35)
email - varchar(254)
You have formatted the SQL query as a sprintf() call, but don't call sprintf()
mysql_query(sprintf("INSERT INTO Users (username, password, fname, lname, email) VALUES ('%s', '%s', '%s', '%s', '%s')",
mysql_real_escape_string($username),
mysql_real_escape_string($password),
mysql_real_escape_string($first),
mysql_real_escape_string($last),
mysql_real_escape_string($email))) or die(mysql_error());
// also note some parentheses out of place ^^^^^^^^^^^^^^^^^^^^^^^^
It's PHP that's telling you off about parameters, not MySQL.
You've tried to use mysql_query like sprintf, which it is not. mysql_query accepts an optional database resource identifier, and the query string. Two parameters. That is all.
If you do want to use sprintf, then go for it:
mysql_query(
sprintf(
"INSERT INTO Users (username, password, fname, lname, email) VALUES ('%s', '%s', '%s', '%s, '%s')",
mysql_real_escape_string($username),
mysql_real_escape_string($password),
mysql_real_escape_string($first),
mysql_real_escape_string($last),
mysql_real_escape_string($email)
)
) or die(mysql_error());
But remember that the first argument to mysql_query is just a string. No magic.
mysql_query(
sprintf("INSERT INTO Users (username, password, fname, lname, email) VALUES ('%s', '%s', '%s', '%s, '%s')",
mysql_real_escape_string($username),
mysql_real_escape_string($password),
mysql_real_escape_string($first),
mysql_real_escape_string($last),
mysql_real_escape_string($email)))
or die(mysql_error()); // sprintf to build a final string of your query by given format and "or die statement" is outside the mysql_query function call.

Categories