Insert Query into Online MySQL database not working - php

I am trying to insert data into an online MySql database,I used this query a few months ago now it doesn't seem to work,
My Form:
$name = "Hilary";
$number = "768";
$orderss = "Rice x1";
$location = "Chilenje";
$con= mysqli_connect($host,$user,$pass,$db);
$query= "insert into orders values('".$name."','".$number."','".$orderss."','".$location."');";
$result= mysqli_query($con,$query);
if(!$result)
{
$response = array();
$code= "reg_false";
$message="Error Placing Order...";
array_push($response,array("code"=>$code,"message"=>$message));
echo json_encode(array("server_response"=>$response));
}
else
{
$response = array();
$code= "reg_true";
$message="Order Successful,Please wait for our call...";
array_push($response,array("code"=>$code,"message"=>$message));
echo json_encode(array("server_response"=>$response));
}
mysqli_close($con);
?>
When i run this form i get the "Error placing orders" part of server response and values are not inserted.Please help me

Make your $query very simple like this if you're inserting into all columns of your table
$stmt = $conn->prepare("INSERT INTO orders VALUES (?, ?, ?, ?)");
$stmt->bind_param("siss", $name, $number, $orderss, $location);
or if you're inserting into specific columns you can use this by replacing column_name* with your actual column names
$stmt = $conn->prepare("INSERT INTO orders (column_name1, column_name2, column_name3, column_name4) VALUES (?, ?, ?, ?)");
$stmt->bind_param("siss", $name, $number, $orderss, $location);
or I also modified your current code so you can test at your end one more thing "siss" are arguments which are of 4 different types i - integer, d - double, s - string, b - BLOB
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$name = "Hilary";
$number = "768";
$orderss = "Rice x1";
$location = "Chilenje";
// Create connection
$con = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
// prepare and bind
$stmt = $conn->prepare("INSERT INTO orders VALUES (?, ?, ?, ?)");
$stmt->bind_param("siss", $name, $number, $orderss, $location);
if($stmt->execute()) {
$stmt->execute();
$response = array();
$code= "reg_true";
$message="Order Successful,Please wait for our call...";
array_push($response,array("code"=>$code,"message"=>$message));
echo json_encode(array("server_response"=>$response));
} else {
$response = array();
$code= "reg_false";
$message="Error Placing Order...";
array_push($response,array("code"=>$code,"message"=>$message));
echo json_encode(array("server_response"=>$response));
}
$stmt->close();
$con->close();
?>

Related

PHP: Taking the last row's id number from one mysql table and using it to update a field in the first row of another table

I'm trying to put the 'id' field value of the last row from users_data table to into the first row of the field_num field of the field_numbers table but this is not updating properly. I can verify that $last_id gets set to the most recent id number in the field_numbers table.
The issue with getting the UPDATE line to work near the bottom...
Your help is greatly appreciated!
if ($_SERVER["REQUEST_METHOD"] == "POST") {//Check it is coming from a form
//mysql credentials
$mysql_host = "buythosecarscom.fatcowmysql.com";
$mysql_username = "[secret]";
$mysql_password = "[secret]";
$mysql_database = "buythatcar";
//header("Location: survey_two.html");
$u_q1 = filter_var($_POST["question_1"], FILTER_SANITIZE_STRING); //set PHP variables like this so we can use them anywhere in code below
$u_q2 = filter_var($_POST["question_2"], FILTER_SANITIZE_STRING);
$u_q3 = filter_var($_POST["question_3"], FILTER_SANITIZE_STRING);
$u_q4 = filter_var($_POST["question_4"], FILTER_SANITIZE_STRING);
$u_q4b = filter_var($_POST["question_4b"], FILTER_SANITIZE_STRING);
$u_q5 = filter_var($_POST["question_5"], FILTER_SANITIZE_STRING);
$u_q6 = filter_var($_POST["question_6"], FILTER_SANITIZE_STRING);
$u_q7 = filter_var($_POST["question_7"], FILTER_SANITIZE_STRING);
$u_q8 = filter_var($_POST["question_8"], FILTER_SANITIZE_STRING);
$u_q9 = filter_var($_POST["question_9"], FILTER_SANITIZE_STRING);
$u_q10 = filter_var($_POST["question_10"], FILTER_SANITIZE_STRING);
//Open a new connection to the MySQL server
$mysqli = new mysqli($mysql_host, $mysql_username, $mysql_password, $mysql_database);
//Output any connection error
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
$statement = $mysqli->prepare("INSERT INTO users_data (question_1, question_2, question_3, question_4, question_4b, question_5, question_6, question_7, question_8, question_9, question_10) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); //prepare sql insert query
//bind parameters for markers, where (s = string, i = integer, d = double, b = blob)
$statement->bind_param('sssssssssss', $u_q1, $u_q2, $u_q3, $u_q4, $u_q4b, $u_q5, $u_q6, $u_q7, $u_q8, $u_q9, $u_q10); //bind values and execute insert query
if($statement->execute()){
//This does not work to update the field_num record at id =1 to $last_id's value
$last_id = $mysqli -> insert_id;
$sql = "UPDATE field_numbers SET field_num= '$last_id' WHERE id=1";
//This correctly returns that value of the last_id... so I know it's set right
echo "New record has id: " . $last_id;
print "Hello " . $mysqli-> insert_id . "!, your message has been saved!";
print "Hello $last_id";
}else{
print $mysqli->error; //show mysql error if any
}
}
?>
Looks like you need to execute the $sql query... see the modified code below for how to execute a mysqli sql update query.
<?php
//mysql credentials
$mysql_host = "buythosecarscom.fatcowmysql.com";
$mysql_username = "[secret]";
$mysql_password = "[secret]";
$mysql_database = "buythatcar";
//header("Location: survey_two.html");
$u_q1 = filter_var($_POST["question_1"], FILTER_SANITIZE_STRING); //set PHP variables like this so we can use them anywhere in code below
$u_q2 = filter_var($_POST["question_2"], FILTER_SANITIZE_STRING);
$u_q3 = filter_var($_POST["question_3"], FILTER_SANITIZE_STRING);
$u_q4 = filter_var($_POST["question_4"], FILTER_SANITIZE_STRING);
$u_q4b = filter_var($_POST["question_4b"], FILTER_SANITIZE_STRING);
$u_q5 = filter_var($_POST["question_5"], FILTER_SANITIZE_STRING);
$u_q6 = filter_var($_POST["question_6"], FILTER_SANITIZE_STRING);
$u_q7 = filter_var($_POST["question_7"], FILTER_SANITIZE_STRING);
$u_q8 = filter_var($_POST["question_8"], FILTER_SANITIZE_STRING);
$u_q9 = filter_var($_POST["question_9"], FILTER_SANITIZE_STRING);
$u_q10 = filter_var($_POST["question_10"], FILTER_SANITIZE_STRING);
//Open a new connection to the MySQL server
$mysqli = new mysqli($mysql_host, $mysql_username, $mysql_password, $mysql_database);
//Output any connection error
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
$statement = $mysqli->prepare("INSERT INTO users_data (question_1, question_2, question_3, question_4, question_4b, question_5, question_6, question_7, question_8, question_9, question_10) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); //prepare sql insert query
//bind parameters for markers, where (s = string, i = integer, d = double, b = blob)
$statement->bind_param('sssssssssss', $u_q1, $u_q2, $u_q3, $u_q4, $u_q4b, $u_q5, $u_q6, $u_q7, $u_q8, $u_q9, $u_q10); //bind values and execute insert query
if($statement->execute()){
$last_id = $mysqli -> insert_id;
echo "New record has id: " . $last_id;
print "Hello " . $mysqli-> insert_id . "!, your message has been saved!";
print "Hello $last_id";
$sql = "UPDATE field_numbers SET field_num= '$last_id' WHERE id=1";
if($mysqli->query($sql) === TRUE) {
echo "cool";
}else{
echo "awful: " . $mysqli->error;
}
}else{
print $mysqli->error; //show mysql error if any
}
?>

No data supplied for parameters in prepared statement - error php MySQLi [duplicate]

This question already has an answer here:
"No data supplied for parameters in prepared statement"
(1 answer)
Closed 1 year ago.
i'm very new to php. So, I tried to make a simple form to order sandwiches, but when I click the submit button i get this error "No data supplied for parameters in prepared statement".
Btw, I copied most of the code from a YouTube video, and I don't know what some parts of the code actually do.
that's my code:
<?php
if (isset($_POST['submit'])) {
if (isset($_POST['nombre']) && isset($_POST['apellido']) &&
isset($_POST['bocadillo']) && isset($_POST['extra']) &&
isset($_POST['comentario']) && isset($_POST['comentario'])) {
$nombre = $_POST['nombre'];
$apellido = $_POST['apellido'];
$bocadillo = $_POST['bocadillo'];
$extra = $_POST['extra'];
$comentario = $_POST['comentario'];
$host = "localhost";
$dbUsername = "------";
$dbpassword = "------";
$dbName = "------";
$conn = new mysqli($host, $dbUsername, $dbpassword, $dbName);
if ($conn->connect_error) {
die('Could not connect to the database.');
}
else {
$Select = "SELECT extra FROM pedidos WHERE extra = ? LIMIT 1";
$Insert = "INSERT INTO pedidos(nombre, apellido, bocadillo, extra, comentario) values(?, ?, ?, ?, ?)";
$stmt = $conn->prepare($Select);
$stmt->execute();
$stmt->bind_result($resultemail);
$stmt->store_result();
$stmt->fetch();
$rnum = $stmt->num_rows;
if ($rnum == 0) {
$stmt->close();
$stmt = $conn->prepare($Insert);
if ($stmt->execute()) {
echo "New record inserted sucessfully.";
}
else {
echo $stmt->error;
}
}
else {
echo "Someone already registers using this email.";
}
$stmt->close();
$conn->close();
}
}
else {
echo "All field are required.";
die();
}
}
else {
echo "Submit button is not set";
}
?>
You're missing the bind_param statements for both queries
$Select = "SELECT extra FROM pedidos WHERE extra = ? LIMIT 1";
$stmt = $conn->prepare($Select);
$stmt->bind_param("s", $extra);
$stmt->execute();
and then in the insert
$Insert = "INSERT INTO pedidos(nombre, apellido, bocadillo, extra, comentario) values(?, ?, ?, ?, ?)";
$stmt = $conn->prepare($Select);
$stmt->bind_param("sssss", $nombre, $apellido, $bocadillo, $extra, $comentario);
$stmt->execute();
https://www.w3schools.com/php/php_mysql_prepared_statements.asp

How do I check whether two values exists in a database?

I'm creating a booking calendar and am having issues making the timeslots that have been booked unavailable. I have populated them separately unfortunately, so the date and timeslot have no connection.
How do I check if both the timeslot and date (in the same ID) have been booked?
$name = $_POST['name'];
$email = $_POST['email'];
$timeslot = $_POST['timeslot'];
$date = $_POST['date'];
$conn = new mysqli("localhost","root","root","bookingCalendar");
if($conn->connect_error){
die("Failed to connect : ".$conn->connect_error);
} else {
$stmt = $conn->prepare("insert into bookings(name, email, timeslot, date) values(?, ?, ?, ?)");
$stmt->bind_param("ssss", $name, $email, $timeslot, $date); //Saves values as strings, thus further functions can't be created
$stmt->execute();
echo '<script>alert("Booking successful!")</script>';
echo "<script> location.href='bookCal.php'; </script>";
$stmt->close();
$conn->close();
}

PHP query wont insert to database

The below query wont insert to database, I had tried this query on my database so I am quite sure that the query is working. I also added the dbcon.php below.
<?php
require '../api/dbcon.php';
$stmt=$conn->prepare("INSERT INTO joborder (AirCondition,
CarpentryMasonry,
ElectricalWorks,
Plumbing,
Welding,
Campus,
priorityId,
RequestorName,
UserJobDescription,
SerialCode
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" );
$stmt->bind_param('ssssssssss',
$airConditioning,
$masonryCarpentry,
$electrical,
$plumbing,
$welding,
$campus,
$priority,
$requester,
$userJobDescription,
$serialCode);
$airConditioning = "check";
$masonryCarpentry = "check";
$electrical = "check";
$plumbing = "check";
$welding = "check";
$campus = 'NA';
$priority = '1';
$requester = "m";
$userJobDescription ="test";
//create serial code
$serialCode= "na12321";
?>
dbcon.php
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbtable = "table";
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbtable);
if(!$conn ){
die('Could not connect: ' . mysqli_error());
}
?>
you're using a bad error reporting mode, and thus need to meticulously check for errors everywhere, but you're not.
on not-dbcon.php on line 4 you're not checking that $conn->prepare succeeded, do that, it returns bool(false) if there was an error. on line 16 you're not checking that $stmt->bind_param succeeded, do that, it returns bool(false) if there was an error. or better yet, don't do that, just convert return-value-error-reporting into exception-error-reporting, by running $conn->report_mode = MYSQLI_REPORT_ALL; immediately after creating the object.
... and most importantly, seems you forgot to run $stmt->execute(), which actually executes the query, which obviously explains why you're not inserting anything.
<?php
$servername = "localhost";
$username = "root";
$password = "123456";
$database = "inventory";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
$stat = $conn->prepare("INSERT INTO salary (name, salary, job) values (?, ?, ?)");
$name = 'test';
$salary = '21123';
$job = 'demo';
$stat->bind_param($name,$salary, $job );
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// prepare and bind
$stmt = $conn->prepare("INSERT INTO salary (name, salary, job) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
// set parameters and execute
$firstname = "Johnqqq";
$lastname = "123123";
$email = "sdadsad";
$stmt->execute();
echo "New records created successfully";
$stmt->close();
$conn->close();
?>

Insert multiple rows in to table using php

Am trying to insert multiple rows in to table using php:
<?php
$host = "localhost";
$username = "mysql_username";
$password = "mysql_password";
$dbname = "employee";
$con = mysqli_connect($host, $username, $password, $dbname) or die('Error in Connecting: ' . mysqli_error($con));
$st = mysqli_prepare($con, 'INSERT INTO emp(name, gender, designation) VALUES (?, ?, ?)');
// bind variables to insert query params
mysqli_stmt_bind_param($st, 'sss', $name, $gender, $designation);
for ($x = 0; $x <= 3; $x++) {
$name = 'tom';
$gender = 'male';
$designation = 'developer';
mysqli_execute($st);
}
//close connection
mysqli_close($con);
?>
But the rows that i want to insert are not saved in database. Are there any mistakes in my code ?
Actually I want the for loop from json array, I just test using for loop for knowing it is worked or not.
I think the code is right, but try this:
<?php
$host = "localhost";
$username = "mysql_username";
$password = "mysql_password";
$dbname = "employee";
$con = mysqli_connect($host, $username, $password, $dbname) or die('Error in Connecting: ' . mysqli_error($con));
$st = mysqli_prepare($con, 'INSERT INTO emp(name, gender, designation) VALUES (?, ?, ?)');
for ($x = 0; $x <= 3; $x++) {
$name = 'tom';
$gender = 'male';
$designation = 'developer';
// bind variables to insert query params
mysqli_stmt_bind_param($st, 'sss', $name, $gender, $designation);
mysqli_execute($st);
}
//close connection
mysqli_close($con);
?>
The mysqli_stmt_bind_param($query, 'is',…) means the first value is an integer (i) and the next value is a string (s). Feel free to adjust to best fit your actual data types.

Categories