Inserting Data in Table with mySQLi - php

I am trying to INSERT data into a table from a form using MySQLi. I have my database connection on a separate include file before including the form that will INSERT the data. my connection looks like so:
#$DB = new mysqli($mysqlHost,$mysqlUser,$mysqlPass,$mysqlDB);
if($DB ->connect_errno >0){
echo 'Could not connect to the server at this time. Please try again later.';
exit;
}
Now i want to execute a query that will store the users information into a table called users. When i run the query in phpMyAdmin it works fine, so i'm guessing its something to do with the syntax or my logic. Here is my insert code:
if($stmt = $DB->prepare("INSERT INTO `users`(`email`, `password`) VALUES ('value1', 'value2')")){
$stmt->execute();
$stmt->close();
}
echo 'Data INSERTED INTO table.';
Here is the error i am receiving:
Warning: mysqli::prepare(): Couldn't fetch mysqli in C:\xampp\htdocs\Phpclass\Website\includes\register.php
If you need additional information please let me know, i have been working on this for sometime now and it is very frustrated.

Change
$stmt = $DB->prepare("INSERT INTO `users`(`email`, `password`) VALUES ('value1', 'value2')");
To
if ($stmt = $DB->prepare("INSERT INTO `users`(`email`, `password`) VALUES (?, ?)"))
{
$stmt->bind_param("ss", 'value1', 'value2');
$stmt->execute();
$stmt->close();
}
You have you bind the parameters if you use prepared statements. Prepared statements can be used to re-use an SQL query repetitively, to import large chunks of data.
If you're not requiring to import large chunks of data I would recommend using the following instead:
$q = $DB->query("INSERT INTO `users`(`email`, `password`) VALUES ('value1', 'value2')");

You need to remove # before $DB, also check error like below ;
$DB = #new mysqli($mysqlHost,$mysqlUser,$mysqlPass,$mysqlDB);
if($DB->connect_errno){
echo 'Could not connect to the server at this time. Please try again later.';
exit;
}
$stmt = $DB->prepare("INSERT INTO `users`(`email`, `password`) VALUES ('value1', 'value2')")
if ($stmt === FALSE) {
die($DB->error);
}
$stmt->execute();
$stmt->close();
$DB->close();
echo 'Data INSERTED INTO table.';

Related

Unable to insert data into MySQL database using PHP

I am unable to insert data into MySQL database. I do not know the reason since no error is triggered. I am using XAMPP on windows to run local server. Here is the code. It would be great if someone could help.
I am always getting "Values not inserted" output. I also tried printing the $query when I got exact values I entered through a form in the VALUES ('$email', ...) part of the SQL query.
<?php
$dbconnect = mysqli_connect("localhost","root","","id3626001_login_details");
if (!$dbconnect)
{
die("Connection Failed" .mysqli_connect_error());
}
if (!mysqli_select_db($dbconnect, "id3626001_login_details"))
{
echo "Could not connect to Database";
}
if (isset($_REQUEST['username']) && ($_SERVER["REQUEST_METHOD"] == "POST")){
$username = $_REQUEST['username'];
$email = $_REQUEST['email'];
$password = $_REQUEST['password'];
// Inserting values into the database through a query
$query = "INSERT INTO user_registration (ID, email, username, password) VALUES ('$email', $username', '".md5($password)."')";
if (!mysqli_query($dbconnect, $query))
{
echo "Values not inserted";
}
$result = mysqli_query($dbconnect, $query);
if($result){
echo "Registration Successful";
}
}
?>
there is a problem in your query,
1) your column counts and count of values you are passing are not the same (must be same
2) you forgot to put ' (quote befor $username')
change your query to
// Inserting values into the database through a query
$query = "INSERT INTO user_registration ( email, username, password) VALUES ('$email', '$username', '".md5($password)."')";
When you are testing you should not only print only query, you should also copy that query and run it directly into database through [(localhost/phpmyadmin)> select your databse > SQL ] and see what error are displaying there when firing a query.
UPDATE
for #Akintunde 's suggestion
for security concerns you should not be using these kind of insertion methods which is fully open to SQL injections you must follow some rule to avoid to get your script being target of sql injection
use Prepared Statements instead for database operations
Here in your query you forgot to put upper quote '-> $username',
$query = "INSERT INTO user_registration (email, username, password) VALUES ('$email', '$username', '".md5($password)."')";
Here we are not passing Id as a param so you need to make id auto increment in database for that table.
and why are to passing your query twice into mysqli_query() you can check for once like,
$result = mysqli_query($dbconnect, $query);
if ($result)
{
echo "Registration Successful";
}
else{
echo "Values not inserted";
}

$mysqli->prepare with SQL Transactions

I am pretty new to SQL Transactions and tried to execute following statement which did unfortunately not work...
$stmt = $mysqli->prepare("
BEGIN;
INSERT INTO groups (group_name, group_desc, user_id_fk) VALUES ("'.$groupName.'","'.$groupDesc.'","'.$user_id.'");
INSERT INTO group_users (group_id_fk, user_id_fk) VALUES (LAST_INSERT_ID(), "'.$username.'");
COMMIT;
") or trigger_error($mysqli->error, E_USER_ERROR);
$stmt->execute();
$stmt->close();
Is this even possible what I am trying here or is it completely wrong?
I appreciate every response, thank you!
You are using prepare() wrong way. There is absolutely no point in using prepare() if you are adding variables directly in the query.
This is how your queries have to be executed:
$mysqli->query("BEGIN");
$sql = "INSERT INTO groups (group_name, group_desc, user_id_fk) VALUES (?,?,?)";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("ssi",$groupName,$groupDesc,$user_id);
$stmt->execute();
$sql = "INSERT INTO group_users (group_id_fk, user_id_fk) VALUES (LAST_INSERT_ID(), ?)";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s",$username);
$stmt->execute();
$mysqli->query("COMMIT");

prepared statement not executing but msqli_stmt_execute returning true

I have an insert query below and am checking if the insert was successful using: mysqli_stmt_execute. The query is not executing as the values are not being entered into my db. However, I am getting into the if condition. I cannot understand this. I have wrapped the stmt_prepare in an if condition previously and that also was returning true tht it was preparing successfully. I did the same with the bind statement and now I have it on the final execute statement. All return true but the query is not executing. The structure of the table is correct. I even preformed an insert in phpmyadmin and pasted the generated query into my AddToken variable.
$con = 'my login credentials'
$stmt = mysqli_stmt_init($con);
$AddToken = "INSERT INTO `auth` VALUES ('',?, ?)";
mysqli_stmt_prepare($stmt, $AddToken);
mysqli_stmt_bind_param($stmt, "si", $Token, $ID);
if (mysqli_stmt_execute($stmt)){
$message2 = "here";
// worked
}
else{
//didn't work
$message2 = "here 2";
}
echo $message2;
EDIT I have no idea what the problem was but I deleted my auth table and recreated it and it worked?
You need not have empty strings in your VALUES()in the insert query, since you are inserting only two values
May be better to specify the column names if you know
$AddToken = "INSERT INTO `auth` (column1, column2) VALUES (?, ?)";

MySQLi: How to insert into multiple tables with prepared statements

I am in a situation where I need to insert into 2 tables in a query. I've searched around web and could not find solution. What I want to do is insert values in user table & insert values in profile simultaneously. I could do one after the other way but I've read that it is not efficient and is considered as poor coding technique.
Current Code:
$statement = $db->prepare("
BEGIN;
INSERT INTO `user`(`username`, `email`, `password_hashed`, `fname`, `lname`, `dob`, `agreement`, `gender`, `access_token`)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);
INSERT INTO `profile_picture`(`owner`) VALUES (LAST_INSERT_ID());
COMMIT;
");
if($statement) {
$statement->bind_param("ssssssiss", $username, $email, $hashedPassword, $fname, $lname, $dob, $agreement, $gender, $access_token);
$statement->execute();
$statement->close();
echo "DONE";
exit();
}
else printf("Error: %s.\n", $db->error);
I had issues with this trying to copy answers like Frank's. The proper way to do it is:
<?php
try {
$db->beginTransaction();
$stmt = $db->prepare("QUERY");
$stmt->execute();
$stmt = $db->prepare("ANOTHER QUERY??");
$stmt->execute();
$db->commit();
}
catch(PDOException $ex) {
//Something went wrong rollback!
$db->rollBack();
echo $ex->getMessage();
}
After the first statement is executed, you can then gain access to the insertID from PHP using the following: $last_id = $db->lastInsertId();
Hope this helps!
Try using mysqli_multi_query, Check this link for example http://blog.ulf-wendel.de/2011/using-mysql-multiple-statements-with-php-mysqli/
Maybe this one can help you: MySQL Insert into multiple tables?
I think you need a statement like this:
BEGIN;
INSERT INTO user(column_a,column_b) VALUES('value_a','value b');
INSERT INTO profile(column_x,column_y) VALUES('value_x','value_y');
COMMIT;
If you need the last id from user table, you can use the LAST_INSERT_ID() function.

Inserting Multiple values into MySQL database using PHP

I'm wondering how to insert multiple values into a database.
Below is my idea, however nothing is being added to the database.
I return the variables above (email, serial, title) successfully. And i also connect to the database successfully.
The values just don't add to the database.
I get the values from an iOS device and send _POST them.
$email = $_POST['email'];
$serial = $_POST['serial'];
$title = $_POST['title'];
After i get the values by using the above code. I use echo to ensure they have values.
Now I try to add them to the database:
//Query Check
$assessorEmail = mysqli_query($connection, "SELECT ace_id,email_address FROM assessorID WHERE email_address = '$email'");
if (mysqli_num_rows($assessorEmail) == 0) {
echo " Its go time add it to the databse.";
//It is unqiue so add it to the database
mysqli_query($connection,"INSERT INTO assessorID (email_address, serial_code, title)
VALUES ('$email','$serial','$title')");
} else {
die(UnregisteredAssessor . ". Already Exists");
}
Any ideas ?
Since you're using mysqli, I'd instead do a prepared statement
if($stmt = mysqli_prepare($connection, "INSERT INTO assessorID (email_adress, serial_code, title) VALUES (?, ?, ?)"))
{
mysqli_stmt_bind_param($stmt, "sss", $email, $serial, $title);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
}
This is of course using procedural style as you did above. This will ensure it's a safe entry you're making as well.

Categories