PHP connected to db can't use insert function - php

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.

Related

Mysqli bind parameters not working

I'm trying to use prepared statements to enter data in a database. The unprepared statement works but this prepared statement does not. I can't find out why.
Prepared version:
$stmt = $mysqli->prepare("INSERT INTO videos (file_name, upload_by, date, path)
VALUES (?, ?, ?, ?)");
$stmt->bind_param('ssss', $newstring, $id, $date->format('Y-m-d'), $location);
$stmt->execute();
Unprepared version:
$sql = "INSERT INTO videos (file_name, upload_by, date, path) VALUES ('$newstring', '$id', '
$date', 'Nominator/$location$newstring')";
mysqli_query($mysqli, $sql);
Replace $stmt-execute(); with $stmt->execute();
Also, don't use date and path in query. Rename them with some other name like date1 and path1.
Update your Query like below that will surely work (Tested Offline):
<?php
$mysqli = new mysqli('localhost', 'root', '', 'test2');
if ($mysqli->errno) {
printf("Connect failed: %s\n", $mysqli->error);
exit();
}
$stmt = $mysqli->prepare("INSERT INTO videos (file_name, upload_by, date1, path1) VALUES (?, ?, ?, ?)");
$stmt->bind_param('ssss', $file_name, $upload_by, $date1, $path1);
$date1 = date("Y-m-d");
$file_name = "test.jpg";
$upload_by = "amit";
$path1 = "test";
if ($result = $stmt->execute()){
echo "success";
$stmt->free_result();
} else {
echo "error";
}
$stmt->close();
?>
You are binding your parameter twice, if you are using only ?, don't bind parameter again just execute directly.
//Prepare your query first
$stmt = $mysqli->prepare("INSERT INTO videos (file_name, upload_by, date, path)
VALUES (?, ?, ?, ?)");
//Just pass your argument and execute directly without binding the parameter (The parameter is binded already)
$stmt->execute('ssss', $newstring, $id, $date->format('Y-m-d'), $location);

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

INSERT with mysqli

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.

Mysqli Procedural Insert Into Table not working

I am trying to insert into a table with Procedural Mysqli. It is not posting any errors nor is it posting the information to the database. Here is my code:
$query = "INSERT INTO Accounts (FirstName, LastName, Username, Password, Access) VALUES ({$_POST['FirstNameTbx']}, {$_POST['LastNameTbx']}, {$_POST['UsernameTbx']}, {$_POST['PasswordTbx']}, {$_POST['AccessDDL']})";
mysqli_query($link, $query);
mysqli_close($link);
$Error .= "$query";
Update:
I changed to prepared statement, now I am getting:
Warning: mysqli_stmt::bind_param() [mysqli-stmt.bind-param]: Number of elements in type definition string doesn't match number of bind variables in /home/bryantrx/public_html/ec/add_user.php on line 19
There are only 5 variables that need to be bound, and the UserID auto increments, so it doesn't need to be bound or referenced in the statement..
if ($stmt = $link->prepare("INSERT INTO Accounts (FirstName, LastName, Username, Password, Access) VALUES (?, ?, ?, ?, ?)")){
$stmt->bind_param($_POST['FirstNameTbx'], $_POST['LastNameTbx'], $_POST['UsernameTbx'], $_POST['PasswordTbx'], $_POST['AccessDDL']);
$stmt->execute();
$Error .= "success";
$stmt->close();
} else {
echo $link->error;
}
To get an error message you need to call mysqli_error:
$error = mysqli_error($link);
You would also make life easier (and more secure) for yourself if you built your queries using prepare and parameters:
$query = "INSERT INTO Accounts (FirstName, LastName, Username, Password, Access)
VALUES ( ?, ?, ?, ?, ?)";
if ($stmt = mysqli_stmt_prepare($link, $query)) {
mysqli_stmt_bind_param($stmt, "sssss",
$_POST['FirstNameTbx'],
$_POST['LastNameTbx'],
$_POST['UsernameTbx'],
$_POST['PasswordTbx'],
$_POST['AccessDDL']);
if (!mysqli_stmt_execute($stmt)) {
$error = mysqli_stmt_error($stmt);
}
mysqli_stmt_close($stmt);
} else {
$error = mysqli_error($link);
}
mysqli_close($link);
UPDATE - ok, you've swapped to OO which is fine. When using bind_param the first parameter describes the data you are binding. In this case if it is five strings, you would put 5 "s" like so:
$stmt->bind_param("sssss",
$_POST['FirstNameTbx'],
$_POST['LastNameTbx'],
$_POST['UsernameTbx'],
$_POST['PasswordTbx'],
$_POST['AccessDDL']);

Categories