INSERT with mysqli - php

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.

Related

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')

Can't insert data to MySQL using PHP

I have been trying to get my form data to database through PHP code but it is not working and I have looked at the code a thousandth times for a possible error but couldn't find one as a beginner. The form will actually submit but nothing gets to the database.
Any fast help would be deeply appreciated. Here is the code:
$conn = #mysqli_connect('localhost', 'root', 'aboki');
if (mysqli_connect_error()) {
die('Connect Error: ' . mysqli_connect_error());
}
$qry = "INSERT INTO users (email, firstName, surname, userName, password, birthday) values ($email, $firstName, $surname, $userName, $password, $userDOB)";
$result = mysqli_query($conn, $qry);
try this
$qry = "INSERT INTO users (email, firstName, surname, userName, password, birthday)
values ('$email', '$firstName', '$surname', '$userName', '$password', '$userDOB')";
Firstly, you are not quoting the values which is why it is not inserting...
This will fix it (But I strongly recommend you do not use this method!):
$qry = "INSERT INTO users (email, firstName, surname, userName, password, birthday) values ('$email', '$firstName', '$surname', '$userName', '$password', '$userDOB')";
The Correct Method
You would be better off making the most of the predefined functions that mysqli offers and binding these parameters in a prepared statement like so:
mysqli_prepare($conn,"INSERT INTO users (email, firstName, surname, userName, password, birthday) values (?, ?, ?, ?, ?, ?)");
mysqli_stmt_bind_param($conn, 'TYPES_HERE',$email, $firstName, $surname, $userName, $password, $birthday)
I have solution for data Insert , You can try it out.
$conn= mysqli_connect("localhost", "root", "my_password", "world");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "INSERT INTO users
(email, firstName, surname, userName, password, birthday) VALUES
($email, $firstName, $surname, $userName, $password, $userDOB)";
mysqli_query($conn, $query);
printf ("New Record has id %d.\n", mysqli_insert_id($link));
mysqli_close($link);
As you having mysqli in Query the syntax quite different,
Feel free to ask further Question.
Thanks
example:
$stmt = mysqli_prepare($conn, "SELECT District FROM City WHERE Name=?")) {
$stmt->bind_param("s", $city);
$stmt->execute();

PHP connected to db can't use insert function

I've been sitting on the same small problem now for over 10 hours, so it's time to ask stackoverflow! I'm connected to the database but when calling mysqli_stmt_bind_param I get "invalid object or resource".
I've tried the insert statement in the console and it works fine..
<?php
$con=mysqli_connect("127.0.0.1:3306", "myUsername", "password");
mysqli_select_db($con, "webshop");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query= mysqli_stmt_init($con);
mysqli_stmt_prepare($query, "INSERT INTO user (name, email, hash, address, tel) VALUES (?, ?, ?, ?, ?)");
mysqli_stmt_bind_param($query, "ssssi", $name, $email, $hash, $address, $tel);
if(mysqli_stmt_execute($query))
{
mysqli_close($con);
}
?>
Thankful for any help at all!
You have to use the statement object returned by mysqli_stmt_prepare()
$stmt = mysqli_stmt_prepare($con, "INSERT INTO user (name, email, hash, address, tel) VALUES (?, ?, ?, ?, ?)");
mysqli_stmt_bind_param($stmt, "ssssi", $name, $email, $hash, $address, $tel);
if(mysqli_stmt_execute($stmt))
Also, the mysqli_stmt_init($con) call is not needed (I think).
mysqli_stmt_init is needed as you are accessing mysqli using the procedural style.
This returns an object of type mysqli_stmt, which then acts as a container for the query you are building. As such, you should pass this as the first parameter to mysqli_stmt_prepare, mysqli_stmt_bind_param and mysqli_stmt_execute.
So your code would look like:
<?php
$con=mysqli_connect("127.0.0.1:3306", "myUsername", "password");
mysqli_select_db($con, "webshop");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$stmt = mysqli_stmt_init($con);
$query = "INSERT INTO user (name, email, hash, address, tel) VALUES (?, ?, ?, ?, ?)";
mysqli_stmt_prepare($stmt, $query);
mysqli_stmt_bind_param($stmt, "ssssi", $name, $email, $hash, $address, $tel);
if(mysqli_stmt_execute($stmt))
{
mysqli_close($stmt);
}
?>
One, unrelated point - you appear to be requiring that your tel field (which I presume to be a telephone number) is an integer. This might be a bad idea if you have to handle telephone numbers starting with 0 (common in the UK for example) at any point.

MySQL error, new to SQL

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);
}

Fatal error: Call to a member function bind_param() on a non-object line 52 [duplicate]

This question already has answers here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(2 answers)
Closed 2 years ago.
I have seen numorous questions similar to this, however I still can't seem to resolve the problem, so sorry if this may be a duplicate.
Anyway here is the code:
$email = $_POST['emailAddress'];
$username = $_POST['userName'];
$dob = $_POST['dobYear'] . "-" . $_POST['dobMonth'] . "-" . $_POST['dobDay'];
$fname = $_POST['firstName'];
$sname = $_POST['lastName'];
$country = $_POST['country'];
$squestion = $_POST['secretQuestion'];
$sanswer = $_POST['secretAnswer'];
require('db_connect.php');
$insert_stmt = $mysqli->prepare("INSERT INTO users (username, email, password, salt, fname, sname, country, dob, squestion, sanswer) VALUES (:username, :email, :password, :salt, :fname, :sname, :country, :dob, :squestion, :sanswer)");
var_dump($mysqli->error);
$insert_stmt->bind_param(':username', $username); // error is here
$insert_stmt->bind_param(':email', $email);
$insert_stmt->bind_param(':password', $password);
$insert_stmt->bind_param(':salt', $random_salt);
$insert_stmt->bind_param(':fname', $fname);
$insert_stmt->bind_param(':sname', $sname);
$insert_stmt->bind_param(':country', $country);
$insert_stmt->bind_param(':dob', $dob);
$insert_stmt->bind_param(':squestion', $squestion);
$insert_stmt->bind_param(':sanswer', $sanswer);
$insert_stmt->execute();
And this is the output of var_dump:
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 ':username, :email, :password, :salt, :fname, :sname, :country, :dob, :squestion,' at line 1"
I know that there must be a problem on the prepare line but, I am really not seeing it.
Here is the db_connect.php just in case anyone wants to see though, this file is working fine:
define("HOST", "localhost"); // The host you want to connect to.
define("USER", "sec_user"); // The database username.
define("PASSWORD", "eKcGZr59zAa2BEWU"); // The database password.
define("DATABASE", "secure_login"); // The database name.
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
Again, sorry if this is a duplicate or if I'm missing something blatent and obvious.
The class mysqli_stmt does not support named SQL-parameters. Also, the first parameter to mysql_stmt::bind_param() is not the name of the SQL-parameter (because the class mysqli_stmt does not support named SQL-parameters).
$insert_stmt = $mysqli->prepare("INSERT INTO users (username, email, password, salt, fname, sname, country, dob, squestion, sanswer) VALUES (?, ?,?, ?, ?, ?, ?, ?, ?, ?)");
change your bind accordingly

Categories