The following is my code:
Note: CONNECTDATA is valid data, substituted for security reasons.
$con = mysqli_connect(CONNECTDATA);
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$username = mysql_real_escape_string($_POST["username"]);
$email = mysql_real_escape_string($_POST["email"]);
$igname = mysql_real_escape_string($_POST["gamename"]);
$pass = crypt($_POST["password"]);
if(!mysqli_query($con, "INSERT INTO users (username, email, igname, password) VALUES ($username, $email, $igname, $pass)")){
die('Error' . mysqli_error($con));
}
I am new to SQL and this is a learning experiment project, i am getting this error: ErrorYou have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '#mail.com, alphabravo, $1$dg1.iu3.$oZIgB6gFwjAcywv/zadG3/)' at line 1
I dont understand whats wrong with my syntax, help is much appreciated.
The reason this is happening is because you have to quote your string values e.g.
INSERT INTO users (username, email, igname, password) VALUES ('$username', '$email', '$igname', '$pass')
Even better would be to use prepared statements to prevent SQL injection and negate the need for using mysqli_real_escape_string
$con = mysqli_connect(CONNECTDATA);
...
$stmt = mysqli_prepare($con, "INSERT INTO users (username, email, igname, password) VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($stmt, 'ssss', $username, $email, $igname, $pass);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
As andrewsi says on comment you need to use quotation marks when sending strings to the database.
So your sqlquery should be:
if(!mysqli_query($con, "INSERT INTO users (username, email, igname, password) VALUES ('$username', '$email', '$igname', '$pass')")){
If you want to pass an INTEGER (or other numerical values) then you dont need to use quotation marks (as long as the database field is numerical aswell).
Your SQL syntax is wrong.
A string have to be always quoted and escaped.
Proper function for escaping have to be used.
$username = mysqli_real_escape_string($con, $_POST["username"]);
$email = mysqli_real_escape_string($con,$_POST["email"]);
$igname = mysqli_real_escape_string($con,$_POST["gamename"]);
$pass = mysqli_real_escape_string($con,crypt($_POST["password"]));
$sql = "INSERT INTO users (username, email, igname, password)
VALUES ('$username', '$email', '$igname', '$pass')"
mysqli_query($con, $sql) or trigger_error($con->error);
Don't mix mysqli with mysql, use this with mysqli
$username = mysqli_real_escape_string($_POST["username"]);
$email = mysqli_real_escape_string($_POST["email"]);
$igname = mysqli_real_escape_string($_POST["gamename"]);
Edit
Use prepared statement like this
if(($stmt = mysqli_prepare($con, "INSERT INTO users (username, email, igname, password)
VALUES (?,?,?,?)"))) {
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "s", $username);
mysqli_stmt_bind_param($stmt, "s", $email);
mysqli_stmt_bind_param($stmt, "s", $igname);
mysqli_stmt_bind_param($stmt, "s", $pass);
/* execute query */
mysqli_stmt_execute($stmt);
}
Related
I'm writing PHP code to send user input to the database. And http://fwtest.ga/register.php is my URL. every time I click the URL or check the JSON data in JSONLint website I get "mysqli_stmt_bind_param(): "Number of variables doesn't match a number of parameters in prepared statement" here is Mycode
<?php
$con = mysqli_connect("hostname", "username", "password", "dbname");
$first_name = $_POST["first_name"];
$last_name = $_POST["last_name"];
$email = $_POST["email"];
$password = $_POST["password"];
$user_id = $_POST["user_id"];
$statement = mysqli_prepare($con, "INSERT INTO `user` (first_name, last_name, email, password) VALUES
('$first_name', '$last_name', '$email', '$password')");
mysqli_stmt_bind_param($statement, 'ssss', $first_name, $last_name, $email, $password);
mysqli_stmt_execute($statement);
$response = array();
$response["success"] = true;
echo json_encode($response);
?>
You are injecting the params and you are preparing the query at the same time, use ? to tell mysql where to place the data,remove the variables from the sql string
$statement = mysqli_prepare($con, "INSERT INTO `user` (first_name, last_name, email, password) VALUES
(?, ?, ?, ?)");
I declared the five variables after a $con, and use only four of them mysqli_prepare function. Now it's working.
I want bind input from user befor add data to database , I wrote this code but I don't know how I complete it
$con=mysqli_connect('localhost', 'root', '', 'user');
$con->set_charset("utf8");
$result = mysqli_query($con,("INSERT INTO users(name, email, user_phone_number, password) VALUES (?,?,?,?)");
user input $name , $email , $user_phone_number , $password this pramter I don't want add directly to my database for that I used ????
in PDO I use bindValue but here what I should do ?
You don't use mysqli_query() with prepared statements, you use mysqli_prepare().
$stmt = mysqli_prepare($con, "INSERT INTO users(name, email, user_phone_number, password) VALUES (?,?,?,?)");
mysqli_stmt_bind_param($stmt, "ssss", $name, $email, $user_phone_number, $password);
$result = mysqli_stmt_execute($stmt);
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')
I am new to using MySQLi. I try to use MySQLi in order to insert data in my database. But does not work. Where may be the error?
echo 'connected';
$con = mysqli_connect("localhost",$username,$password,$database);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// mysqli_select_db($con,"kraus");
$firstname = $_POST['uname'];
$lastname = $_POST['address'];
$age = $_POST['pass'];
$sql = "INSERT INTO registration('uname', 'address', 'password') VALUES ('$firstname', '$lastname', '$age')";
mysqli_query($con,$sql);
echo "1 record added";
mysqli_close($con);
Why is line this commented out? You are selecting the database in mysqli_connect("localhost","root","root","kraus") but it makes no sense why that is there:
// mysqli_select_db($con,"kraus");
Should you not have that commented like this?
mysqli_select_db($con,"kraus");
Also there is no space here between registration and the fields in (…) as well as the quotes around your fields:
$sql = "INSERT INTO registration('uname', 'address', 'password') VALUES ('$firstname', '$lastname', '$age')";
That should be like the following with a space added between the table name & the fields. And since there should just be no quotes around your field names so the final query should be this:
$sql = "INSERT INTO registration (uname, address, password) VALUES ('$firstname', '$lastname', '$age')";
Or perhaps have back ticks like this:
$sql = "INSERT INTO registration (`uname`, `address`, `password`) VALUES ('$firstname', '$lastname', '$age')";
Also, you should really refactor & cleanup your whole codebase like this:
// Set the connection or die returning an error.
$con = mysqli_connect("localhost","root","root","kraus") or die(mysqli_connect_errno());
echo 'connected';
// Select the database.
// mysqli_select_db($con, "kraus");
$post_array = array('uname','address','pass');
foreach ($post_array as $post_key => $post_value) {
$$post_key = isset($_POST[$post_value]) && !empty($_POST[$post_value]) ? $_POST[$post_value] : null;
}
// Set the query.
$sql = "INSERT INTO registration (uname, address, password) VALUES (?, ?, ?)";
// Bind the params.
mysqli_stmt_bind_param($sql, 'sss', $uname, $address, $pass);
// Run the query.
$result = mysqli_query($con, $sql) or die(mysqli_connect_errno());
// Free the result set.
mysqli_free_result($result);
// Close the connection.
mysqli_close($con);
echo "1 record added";
Note how I am using mysqli_stmt_bind_param and also setting an array of $_POST values & rolling throughout them. Doing those two basic things at least enforce some basic validation on your input data before it gets to the database.
You have quotes around the column names in your query. Maybe you meant to use backticks instead:
(`uname1`, `address`,...)
You are also vulnerable to sql injection. Look into mysqli prepared statements.
I have a register page which inserts the registration data into a database.
It goes along the lines of this:
if ($_POST['password'] == $_POST['conf_pass']){
$user = $_POST['username'];
$pass = $_POST['password'];
$hash = md5(rand(0,1000));
$accres = mysqli_query($connection, "INSERT INTO accounts (street1, suburb, city, postcode, username) VALUES($address, $suburb, $city, $postcode, $username)");
$account_id = mysqli_insert_id($accres);
$peopleres = mysqli_query($connection, "INSERT INTO people (lastname, firstname, accounts_id, birthdate, phonenumber, username, password, email, hash) VALUES($lastname, $firstname, $account_id, $birthdate, $phonenumber, $username, $password, $email, $hash)");
$peoplerows=mysqli_fetch_assoc($peopleres);
$person_id=$peoplerows[0];
mysqli_query("INSERT INTO PeopleToRole (role_id) VALUES(1)");
$email = $_SESSION['email'];
$p->addContent("User Registered");
}
I originally programmed all of this using postgres (while hosted locally on an apache server) but had to change to mysqli because the host website was already working with mysqli.
So, this code returns the User Registered on the page, therefore the if statement is working. But for some reason the insert statement won't insert anything into the database.
Do i have some sort of formatting error? or something small that i've missed?
Any and all help would be appreciated.
Thanks
You forgot the quotes in the query, for example, you should change:
"INSERT INTO accounts (street1, suburb, city, postcode, username) VALUES($address, $suburb, $city, $postcode, $username)"
to:
"INSERT INTO accounts (street1, suburb, city, postcode, username) VALUES('$address', '$suburb', '$city', '$postcode', '$username')"
That said, working like this makes your code vulnerable to sql injection (as cfreak mentioned in the comments above).
Here's a small example from the manual that shows how you can use bind_param() to make the code more secure:
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $mysqli->prepare("INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
$stmt->bind_param('sssd', $code, $language, $official, $percent);
$code = 'DEU';
$language = 'Bavarian';
$official = "F";
$percent = 11.2;
/* execute prepared statement */
$stmt->execute();
printf("%d Row inserted.\n", $stmt->affected_rows);
/* close statement and connection */
$stmt->close();
A common problem: you're not bothering to check your queries for errors, so when something goes wrong you don't know what's happened.
Check the return value of mysqli_query() for FALSE, and if you find it, check mysqli_error($connection) for an error message.
For example:
$accres = mysqli_query($connection, "INSERT INTO accounts (street1, suburb, city, postcode, username) VALUES($address, $suburb, $city, $postcode, $username)");
if ($accres === false) {die(mysqli_error($connection));}
Do something similar for your other queries. When you have an error message, fix it, or come back and ask again.