Insert multiple rows in to table using php - 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.

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
}
?>

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 a foreign key using prepared statement

i want to insert with foreign key resident_id using prepared statement in table_complaints.
here is my picture of :
also i get the $ides = $_POST["resident_id"]; in view page
$servername = "localhost";
$username = "root";
$password = "";
$database = "myDb";
$conn = mysqli_connect($servername, $username, $password, $database);
if(!$conn){
die("Connection Failed: " . mysqli_connect_error());
}
if(isset($_POST["submits"])){
$comp_text = $_POST["comp"];
$complaints = $_POST["complaints"];
$ides =$_POST["resident_id"];
$statementi = mysqli_stmt_init($conn);
mysqli_stmt_prepare($statementi, "INSERT INTO table_complaint (nature_of_complaints, status)
VALUES (?, ?) WHERE resident_id = ?");
mysqli_stmt_bind_param($statementi, "ssi", $comp_text, $complaints);
mysqli_stmt_execute($statementi);
mysqli_stmt_close($statementi);
}
mysqli_close($conn);
Your insert query is incorrect.
You can use this:
INSERT INTO table_complaint (resident_id,nature_of_complaints, status) VALUES (?,?,?)
and then bind the parameters:
mysqli_stmt_bind_param($statementi, "iss", $ides,$comp_text, $complaints);

Insert Query into Online MySQL database not working

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

Prepared statement giving error

What am I missing?
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
$name = 'Samuel "L" Jackson';
$conn = new mysqli($servername, $username, $password, $dbname);
$stmt = $conn->prepare("INSERT INTO test2 (id, name) VALUES (?,
?)");
$stmt->bind_param("is",'600' , $name);
$stmt->execute();
$stmt->close();
$conn->close();
?>
I'm getting the following error:
Cannot pass parameter 2 by reference in C.... on line ...
bind_param accepts two or more arguments. The first must be a string identifying the data types for the SQL parameters. The rest of the arguments must be variables that can be passed by reference. '600' is a constant, so you cannot pass it by reference.
Just use a temporary variable to work around that limitation, like this:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
$id = 600;
$name = 'Samuel "L" Jackson';
$conn = new mysqli($servername, $username, $password, $dbname);
$stmt = $conn->prepare("INSERT INTO test2 (id, name) VALUES (?, ?)");
$stmt->bind_param("is", $id, $name);
$stmt->execute();
$stmt->close();
$conn->close();
?>

Categories