Data not stored using prepared statements - php

I am just learning to use prepared statements and stuck here. there is no problem with normal method. there is nothing error shown but the data is not stored in database although it displays "data entered".
$db = new mysqli("localhost", "root","","learndb");
if ($db->connect_error) {
die("Connection failed this is the error: " . $db->connect_error);
}
$stmt = $db->prepare("INSERT INTO studentrecords (Name, email, Phone, school,dob,father,feereceived,due,image) VALUES (?,?,?,?,?,?,?,?,?)");
$stmt->bind_param("ssisssiib",$first,$email,$phone,$school,$dob,$father,$feereceived,$due,$image);
$stmt->execute();
if($stmt)
{
echo"data entered";
}
Update
Data is stored but not the type required. should i specify all types in user input? Also the pattern in html form not working.

I'd suggest that you wrap the entire bind_param & execute with an if condition as the statement will fail to be prepared if there is even a minor issue. In this case I would guess it could be that the types for each variable/field is wrong at some point - probably the image / b part.
You can echo the type of each using gettype which might help track it down:
echo gettype($first), gettype($email), gettype($phone),
gettype($school), gettype($dob), gettype($father),
gettype($feereceived), gettype($due), gettype($image);
$db = new mysqli("localhost", "root","","learndb");
if ($db->connect_error) {
die("Connection failed this is the error: " . $db->connect_error);
}
$stmt = $db->prepare("INSERT INTO studentrecords (`Name`, `email`, `Phone`, `school`,`dob`,`father`,`feereceived`,`due`,`image`) VALUES (?,?,?,?,?,?,?,?,?)");
if($stmt) {
$stmt->bind_param("ssisssiib",$first,$email,$phone,$school,$dob,$father,$feereceived,$due,$image);
$stmt->execute();
} else {
echo 'Failed to prepare the sql statement';
}

Related

Prepared statement: column cannot be null

I've been trying to figure out why I get this error in my prepared statement but I can't solve the problem. I get the error:
Notice: Undefined index: tipimage in C:\xampp\htdocs\Matt\addtip.php on line 68
ERROR: Could not execute query: INSERT INTO tips (tiptitle, tiptext, tiplink, tipimage) VALUES (?, ?, ?, ?). Column 'tipimage' cannot be null
All the values in my database are set to type text, except Id.
....
else {
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$mysqli = new mysqli("localhost", "paul", "pass", "yourcomp");
// Check connection
if($mysqli === false){
die("ERROR: Could not connect. " . $mysqli->connect_error);
}
// Prepare an insert statement
$sql = "INSERT INTO tips (tiptitle, tiptext, tiplink, tipimage) VALUES (?, ?, ?, ?)";
if($stmt = $mysqli->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bind_param("ssss", $tiptitle, $tiptext, $tiplink, $tipimage);
// Set parameters
$tiptitle = $_REQUEST['tiptitle'];
$tiptext = $_REQUEST['tiptext'];
$tiplink = $_REQUEST['tiplink'];
$tipimage = $_REQUEST['tipimage'];
// Attempt to execute the prepared statement
if($stmt->execute()){
$successmsg = "<div class='alert alert-success'>Tip Added Successfully!</div>";
} else{
echo "ERROR: Could not execute query: $sql. " . $mysqli->error;
}
} else{
echo "ERROR: Could not prepare query: $sql. " . $mysqli->error;
}
You're looking for a POST variable that wasn't sent with the request. This is what the undefined index notice is trying to tell you. You don't check to see if it exists before passing it to the database, so it ends up getting passed as null. Just give a default value of an empty string (here using the null coalesce operator) and it will work fine.
$tipimage = $_REQUEST['tipimage'] ?? "";

Inserting into two table simultaneously sharing same id

Please i have a little problem here. the below code i wrote was meant to insert into two tables simultaneously but it those not work. but if i remove the second INSERT the first INSERT will work dont know whats wrong. ITs meant insert in the first table and also collect the last Insert Id of the First table to the Second table. What did i do wrong
<?php
$english_name = $_POST['EnglishName'];
$tel_number = $_POST['TelNumber'];
$email_address = $_POST['EmailAddress'];
$gender = $_POST['Gender'];
$age = $_POST['Age'];
$region = $_POST['Region'];
mysql_connect("localhost", "root", "") or die ('Error: ' . mysql_error());
mysql_select_db("fruitmarket");
$query="INSERT INTO data (english_name, tel_number, email_address, gender, age, region) VALUES (";
$query.="'".$english_name."', ";
$query.="'".$tel_number."', ";
$query.="'".$email_address."', ";
$query.="'".$gender."', ";
$query.="'".$age."', ";
$query.="'".$region."')";
$query .= "INSERT INTO data_category (id, english_name)
VALUES (LAST_INSERT_ID(), '$english_name');";
mysql_query($query) or die ('Error updating database');
echo "Record is inserted.";
?>
its almost 2018, so please stop using depreciated and removed mysql_* functions use PDO/mysqli with prepared statements.
I have re-written your code with prepared statements, please follow these links :
Why shouldn't I use mysql_* functions in PHP?
How can I prevent SQL injection in PHP?
Prepared statements
<?php
$servername = "localhost";
$username = "username";
$password = "";
$dbname = "fruitmarket";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$stmt = "INSERT INTO data (english_name,tel_number,email_address,gender,age,region) VALUES(?,?,?,?,?,?)";
$sql = $conn->prepare($stmt);
$sql->bind_param("ssssis", $english_name, $tel_number, $email_address, $gender, $age, $region);
if ($sql->execute()) {
$id = $sql->insert_id;
$insert = $conn->prepare("INSERT INTO data_category (id, english_name) VALUES(?,?)");
$insert->bind_param("is", $id, $english_name);
if ($insert->execute()) {
echo "data inserted successfully";
} else {
printf("Errormessage: %s\n", $mysqli->error);
}
} else {
printf("Errormessage: %s\n", $mysqli->error);
}
A prepared statement is a feature used to execute the same (or similar) SQL statements repeatedly with high efficiency.
Prepared statements basically work like this:
Prepare: An SQL statement template is created and sent to the
database. Certain values are left unspecified, called parameters
(labeled "?"). Example: INSERT INTO myTabvle VALUES(?, ?, ?)
The database parses, compiles, and performs query optimization on
the SQL statement template, and stores the result without executing
it
Execute: At a later time, the application binds the values to the
parameters, and the database executes the statement. The application
may execute the statement as many times as it wants with different
values Compared to executing SQL statements directly, prepared
statements have three main advantages:
Prepared statements reduces parsing time as the preparation on the
query is done only once (although the statement is executed multiple
times)
Bound parameters minimize bandwidth to the server as you need send
only the parameters each time, and not the whole query
Prepared statements are very useful against SQL injections, because
parameter values, which are transmitted later using a different
protocol, need not be correctly escaped. If the original statement
template is not derived from external input, SQL injection cannot
occur.
I tested the above code and noticed you just need just to add and change some code see my below example
<?php
$english_name = $_POST['EnglishName'];
$tel_number = $_POST['TelNumber'];
$email_address = $_POST['EmailAddress'];
$gender = $_POST['Gender'];
$age = $_POST['Age'];
$region = $_POST['Region'];
mysql_connect("localhost", "root", "") or die ('Error: ' . mysql_error());
mysql_select_db("fruitmarket");
$query="INSERT INTO data (english_name, tel_number, email_address, gender, age, region) VALUES (";
$query.="'".$english_name."', ";
$query.="'".$tel_number."', ";
$query.="'".$email_address."', ";
$query.="'".$gender."', ";
$query.="'".$age."', ";
$query.="'".$region."')";
mysql_query($query) or die ('Error updating database');
echo "Record is inserted.";
$query= "INSERT INTO data_category (id, english_name)
VALUES (LAST_INSERT_ID(), '$english_name');";
mysql_query($query) or die ('Error updating database');
echo "Record is inserted.";
?>
test it to check if it will work

How can I pass my user entered information to my database using php?

The users enter their name and number in the textfields. The this information is passed then sent to the data.php file where I am trying to get it to write to my database. The data base name is called hello.
<!-- connect to database -->
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "hello";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
echo "wooo connected";
}
//<!-- post added information to database -->
if ($_POST['name']) {
if ($_POST['number']) {
$sql = "INSERT INTO hello (id, name, number)
VALUES ('', '$_POST['name']', '$_POST['number'')";
if(mysqli_query($conn, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
} ?>
From looking at my code I believe the issue is with this line.
$sql = "INSERT INTO hello (id, name, number)
VALUES ('', '$_POST['name']', '$_POST['number']')";
There is a blank left at the star for the auto incremented id that I have set in phpmyadmin.
I can hard code an entry such as:
$sql = "INSERT INTO hello (id, name, number)
VALUES ('', 'john', '12345)";
These hard coded entries are put into the database but i can't get the user entered data to go in.
Create variables for the $_POST values and add the vars for ease of code understanding:
$name = $_POST['name'];
$number = $_POST['number'];
$sql = "INSERT INTO hello (id, name, number) VALUES ('', $name, $number)";
One reason your code may not be working because you have the single quotes around the $_POST values, then you can also do what Jasbeer Rawal recommended.
UPDATE
Based on the kind comments... I would personally take a different approach to adding the data to your database, instead use prepared statements. I use MySQLi, but you can also use PDO.
Start by creating your connection:
<?php
define("HOST", "localhost");
define("USER", "");
define("PASSWORD", "");
define("DATABASE", "");
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
if ($mysqli->connect_error) {
echo "There was a slight problem, please contact your webmaster before continuing.";
exit();
}
Then when the user submits the form handle it:
if(isset($_POST['submit']
{
$name = $_POST['name'];
$number = $_POST['number'];
if ($stmt = $mysqli->prepare("INSERT hello (name, number) VALUES (?, ?)"))
{
$stmt->bind_param("ss", $name, $number);
$stmt->execute();
$stmt->close();
}
else
{
echo "ERROR: Could not prepare SQL statement.";
}
}
This will add $name and $number and your ID role has to be a primary role and set to auto_increment. IDs will be automatically generated.
You're about to go down a slippery slope using mysqli. I'd recommend trying to learn to use PDO for making queries. Right now, someone could easily put SQL into the name POST data and actually do damage to your database.
Anyways, your problem at hand, you have a missing bracket and one issue:
VALUES ('', '$_POST['name']', '$_POST['number'')";
It won't work as intended with nested single quotes.
VALUES ('', '$_POST[name]', '$_POST[number]')";
Remove single quotes from $_POST['name'] and $_POST['number'] as below
$sql = "INSERT INTO hello (id, name, number)
VALUES ('', $_POST['name'], $_POST['number'])";
Your insert code be like this
$sql = "INSERT INTO hello (id, name, number)
VALUES ('','{$_POST['name']}', '{$_POST['number']}')";
Then your value will be in database
If field id is primary key and auto increment then your insert statement should be like
Try this:
$sql = "INSERT INTO hello ( name, number)
VALUES ('{$_POST['name']}', '{$_POST['number']}')";

im getting error when performing insert multiple records

<?php
session_start();
if(isset($_SESSION['id']))
$servername = "localhost";
$dbname = "school";
// Create connection
$conn = mysqli_connect($servername, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$teacher_id=$_SESSION['id'];
$student_id=$_POST['student_id'];
$subject=$_POST['subject'];
$description=$_POST['description'];
$sql="INSERT INTO t_sent (teacher_id, student_id, subject, description)
VALUES
('$_SESSION[id]', '$_POST[student_id]', '$_POST[subject]', '$_POST[description]')";
$sql .="INSERT INTO p_inbox (teacher_id, student_id, subject, description)
VALUES
('$_SESSION[id]', '$_POST[student_id]', '$_POST[subject]', '$_POST[description]')";
if (mysqli_multi_query($conn, $sql)) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
and im getting this error message when im adding records
Error:
INSERT INTO t_sent (teacher_id, student_id, subject, description) VALUES ('Badri', 'ca11099', 'cm ', 'cm')INSERT INTO p_inbox (teacher_id, student_id, subject, description) VALUES ('Badri', 'ca11099', 'cm ', 'cm')
No database selected
I don't know what I'm missing
I think you missed out the syntax for mysqli_connet
mysqli_connect(host, user,password, db);
Please let me know if it didnt work for you.
First of all it looks like you are incorrectly using an if statement - namely
if(isset($_SESSION['id'])).
That if statement will only apply to the very next line ($servername = "localhost";). You need to wrap the code you want that statement to apply to with { } (judging by your code, it's every line after that).
Your parameters for mysqli_connect() are wrong - it should be
mysqli_connect($servername, $username, $password, $dbname);
You are missing the username and password which should go before the database name.
You're also not sanitizing or escaping your input which is very bad and can lead to SQL injection attacks. You should never directly take user input and run queries against that.
Use correct mysqli_connect() with all the parameters:
<?php
$con = mysqli_connect($servername, $username,$password, $database_name);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
Also, You can select database using mysqli_select_db() function

MySQLi insert, successful database connection but not successfully inserted [duplicate]

This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 2 years ago.
I'm attempting to insert some data into a table using mysqli functions.
My connection works fine using the following:
function connectDB(){
// configuration
$dbuser = "root";
$dbpass = "";
// Create connection
$con=mysqli_connect("localhost",$dbuser,$dbpass,"my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
return false;
}else{
echo '<br />successfully connected<br />';
return $con;
}
}
But when I attempt to run my insert function I get nothing in the database.
function newUserInsertDB($name,$email,$password){
$con = connectDB();
// Prepare password
$password = hashEncrypt($password);
echo $password . "<br />";
// Perform queries
mysqli_query($con,"SELECT * FROM users");
mysqli_query($con,"INSERT INTO users (name,email,password,isActivated) VALUES ($name,$email,$password,0)");
// insert
mysqli_close($con);
}
I have been looking through the list of mysqli functions for the correct way to give errors but they all seem to be regarding the connection to the DB, not regarding success of an insert (and I can clearly see in my DB that it is not inserting.)
What would be the best way to debug? Which error handling shall I use for my insert?
I've tried using mysqli_sqlstate which gives a response of 42000 but I cannot see any syntax errors in my statement.
As mentioned in my comment, you would be better off using a prepared statement. For example...
$stmt = $con->prepare(
'INSERT INTO users (name, email, password, isActivated) VALUES (?, ?, ?, 0)');
$stmt->bind_param('sss', $name, $email, $password);
$stmt->execute();
Using this, you don't have to worry about escaping values or providing quotes for string types.
All in all, prepared statements are much easier and much safer than attempting to interpolate values into an SQL string.
I'd also advise you to pass the $con variable into your function instead of creating it within. For example...
function newUserInsertDB(mysqli $con, $name, $email, $password) {
// Prepare password
$password = hashEncrypt($password);
// functions that "echo" can cause unwanted side effects
//echo $password . "<br />";
// Perform queries
$stmt = $con->prepare(
'INSERT INTO users (name, email, password, isActivated) VALUES (?, ?, ?, 0)');
$stmt->bind_param('sss', $name, $email, $password);
return $stmt->execute(); // returns TRUE or FALSE based on the success of the query
}
The quotes are missing from the mysql statement from around the values. Also, you should escape the values before inserting them into the query. Do this way:
mysqli_query($con,"INSERT INTO users (name,email,password,isActivated) VALUES ('".
mysqli_real_escape_string($con,$name)."','".
mysqli_real_escape_string($con,$email)."','".
mysqli_real_escape_string($con,$password)."',0)");
Regards

Categories