How to use multiple array in foreach - php

Array
(
[0] => Array
(
[emp_name] =>
[emp_title] => Senior Developer
[emp_master_id] => 0
[emp_designation] => TL
[emp_skills] => PHP, MySQL
[emp_experience] => 4-5
[emp_location] => Chennai
)
[1] => Array
(
[emp_name] =>
[emp_title] => Web Developer
[emp_master_id] => 0
[emp_designation] => Senior Developer
[emp_skills] => 10Base-T Switching, PHP
[emp_experience] => 4-5
[emp_location] => Chennai
)
)
I want Insert the array In Db by using Foreach.. Any Suggestions

let say your array name is $data
foreach($data as $key => $value){
$sql="Insert into table_name (empname,..... )values('".$value['empname']."',....);";
$result=$conn->query($sql);
}
This should do the work, Assuming that you have connection variable something like
$conn = new mysqli($servername, $username, $password, $dbname);
Give the column name as in your table in the sql query.
EDIT
The secure way of doing it
foreach($data as $key => $value){
// prepare and bind
$stmt = $conn->prepare("INSERT INTO table_name(emp_name, title, ...) VALUES (?, ?, ..)");//No of question marks are equal to columns you have mentioed
$stmt->bind_param("sss", $empName, $title, ...);
// i - integer
// d - double
// s - string
// b - BLOB
// set parameters and execute
$empName= $value['empname'];
$title= $value['title'];
//continue to do it for all...
$stmt->execute();
$stmt->close();
}
$conn->close();
NOTE: You can use function also if you know how to do it, less code inside the foreach
Happy coding :)

foreach($arr as $v){
$sql = ') VALUES (';
foreach($v as $k => $value){
$sql = ",".$k.$sql.'"'.$value.'",';
}
$sql = 'Insert into table_name ('.trim($sql,',').';';
$result=$conn->query($sql);
}
this maybe working.

Related

Insert into a database a single string value of a randomized array

I have this code:
$possible_pics = array(
'red-pfp' => 'teem-pfp-red.svg',
'pink-pfp' => 'teem-pfp-pink.svg',
'blue-pfp' => 'teem-pfp-blue.svg',
'green-pfp' => 'teem-pfp-green.svg',
'purple-pfp' => 'teem-pfp-purple.svg',
'yellow-pfp' => 'teem-pfp-yellow.svg',
'orange-pfp' => 'teem-pfp-orange.svg',
);
shuffle($possible_pics);
echo reset($possible_pics);
The result of it, I want to insert it into a database this way:
$sentence = $connection->prepare("
INSERT INTO users (id, user, pass, email, profile_pic) VALUES (:id, :user, :password, :email, :profile_pic)
");
$sentence->execute(array(
':id' => $user_id,
':user' => $user,
':password' => $password,
':email' => $email,
':profile_pic' => $possible_pics
));
At this point I have already connected to the database, I'm just doing the SQL code.
As you can see, I am inserting the values into the database through an array, and in the part of :profile_pic, I am saying that I want to insert the result of the first code I added to my question, where I am shuffling the array and it only brings us 1 value. The problem here is that when I run this, it shows this:
Notice: Array to string conversion on line 73
Why is this happening and how can I make so it inserts the value of the randomized array? Where I do that, it works perfectly, and it returns effectively only 1 value. I can't do an implode() because it marks, unexpected implode().
In resume, how can I insert into a database the returned value of the randomized array I showed at the beginning of my question?
Just pick the output of reset function to a variable and use it in your insert statement.
shuffle($possible_pics);
$shuffledPic = reset($possible_pics);
...
$sentence->execute(array(
':id' => $user_id,
':user' => $user,
':password' => $password,
':email' => $email,
':profile_pic' => $shuffledPic
));

PDO insert array is only showing one entry

I am try to insert an array into a table with PDO and it is only inserting the first (or last, depending how you look at it) item in the array. Here is my code:
$pdo = new PDO("mysql:charset=utf8mb4;host=$servername;dbname=$dbname", $username, $password);
$sql = "INSERT INTO orderitems
(pid,
name,
style,
weight,
price,
quantity)
VALUES (:pid,
:name,
:style,
:weight,
:price,
:quantity) ";
$stmt= $pdo->prepare($sql);
foreach ($order as $order) {
$stmt->execute(array (
'pid' => $order['id'],
'name' => $order['name'],
'style' => $order['style'],
'weight' => $order['weight'],
'price' => $order['price'],
'quantity' => $order['quantity']
));
}
The problem may be here:
foreach ($order as $order) {
Probably, the first $order variable, as it's naming suggests, is not an array.

MySQL - number of bound variables does not match number of tokens

Can't figure out why this code isn't working:
$update_SQL = $db->prepare($SQL_update);
$update_SQL->execute([$SQL_values]);
And these are dumps of the two strings being inserted into those statements:
$SQL_update = UPDATE laptops SET asset_tag = :asset_tag WHERE id = :id
$SQL_values = 'asset_tag' => 5544, 'id' => 23
You missed : in your code:-
$update_SQL = $db->prepare($SQL_update);
$update_SQL->execute([':asset_tag' => 5544, ':id' => 23]);
So actually what you have to do is:-
$SQL_values =[':asset_tag' => 5544, ':id' => 23]; // create array like this
$update_SQL = $db->prepare($SQL_update);
$update_SQL->execute($SQL_values); // pass that array
Or
$SQL_values =['asset_tag' => 5544, 'id' => 23]; // create array like this
$update_SQL = $db->prepare($SQL_update);
$update_SQL->execute($SQL_values); // pass that array
Note:- execute won't accept a string, it must be an array.

Running Multiple MySQL Queries in PHP

In PHP I'm attempting to build a form that needs to check for an ID in one table and if it exists it should create a record in another table. So far, that works but the issue I'm having is when I attempt to handle the case if the ID I checked for didn't exist. If it doesn't exist I'd like to create another one. But every time I try it, I get 500 errors from the server when I fetch the results.
Essentially I made the following function
function trySQL($con, $query, $params) {
$stmt = $con->prepare($query);
$result = $stmt->execute($params);
$id = $stmt->insert_id;
return array($stmt,$result,$id);
}
I call this function multiple times through out my php code but when I call it more then once and attempt to fetch the results it breaks.
$custINSquery = "
INSERT INTO custs (
FirstName,
LastName,
EmailAddress,
PhoneNumber
) VALUES (
:FirstName,
:LastName,
:EmailAddress,
:PhoneNumber
)
";
$createJob = "
INSERT INTO jobs (
custs_id,
StAddress,
State,
ZipCode,
MoistureLocation,
status_id
) VALUES (
:custs_id,
:StAddress,
:State,
:ZipCode,
:IssueDesc,
:status_id
)
";
$custSELquery = "SELECT id, FirstName, LastName, EmailAddress FROM custs WHERE FirstName = :FirstName AND LastName = :LastName AND EmailAddress = :EmailAddress";
$custSELquery_params = array(
':FirstName' => $_POST['FirstName'],
':LastName' => $_POST['LastName'],
':EmailAddress' => $_POST['EmailAddress']
);
$checkcust = trySQL($db, $custSELquery, $custSELquery_params);
$row = $checkcust[0]->fetch();
if(!$row){
$custINSquery_params = array(
':FirstName' => $_POST['FirstName'],
':LastName' => $_POST['LastName'],
':EmailAddress' => $_POST['EmailAddress'],
':PhoneNumber' => $_POST['PhoneNumber']
);
$custins = trySQL($db, $custINSquery, $custINSquery_params);
$custsel = trySQL($db, $custSELquery, $custSELquery_params);
$custs_id = $custsel[0]->fetch();
if ($custs_id != null) {
$createJobParam = array(
':custs_id' => $custs_id,
':StAddress' => $_POST['StAddress'],
':State' => $_POST['State'],
':ZipCode' => $_POST['ZipCode'],
':IssueDesc' => $_POST['MoistureLocation'],
':status_id' => $_POST['status_id']
);
$jobins = trySQL($db, $createJob, $createJobParam);
$jobres = $jobins[0]->fetch();
die("um...");
if ($jobres) {
# code...
die("looks like I made it");
}
}
} else {
$createJobParam = array(
':custs_id' => $row['id'],
':StAddress' => $_POST['StAddress'],
':State' => $_POST['State'],
':ZipCode' => $_POST['ZipCode'],
':IssueDesc' => $_POST['MoistureLocation'],
':status_id' => $_POST['status_id']
);
$data['success'] = true;
$data['message'] = 'Success!';
}
Additional Notes: When I look through the php doc's they are saying that I could use the inserted_id thing in order to get the ID that I inserted previously but when I try that it just gives me nulls with this set up.
Any help would be appreciated.
Thanks!

MySQL Single Insert Multiple Rows fom post data array

I have search but dont see any answer or example that fits mine code. I am pretty new to MySQL/PHP, so I might not understand the answers I have looked at.
I have a web page that posts data over that I want to use just one insert. This is what I have so far for the insert:
$statement1 = $link->prepare("INSERT INTO collection_items(collection_list_id, collection_item_number, username_id, collection_item_title, collection_item_text, created_date)
VALUES(:collection_list_id, :collection_item_number, :username_id, :collection_item_title, :collection_item_text, now())");
$statement1->execute(array(
"collection_list_id" => $last_id,
"collection_item_number" => "1",
"username_id" => $user_number,
"collection_item_title" => $collection_item_title_1,
"collection_item_text" => $collection_item_text_1
),
(
"collection_list_id" => $last_id,
"collection_item_number" => "2",
"username_id" => $user_number,
"collection_item_title" => $collection_item_title_2,
"collection_item_text" => $collection_item_text_2
));
If I drop the last set of data it works just fine for one row. I have about 20 twenty rows of data from the page post.
TIA
This is what I have, but can't get it to work. I'v shown more code to help.
$form = $_POST;
$collection_item_title_1 = $form[ 'number1' ];
$collection_item_text_1 = $form[ 'comment1' ];
$collection_item_title_2 = $form[ 'number2' ];
$collection_item_text_2 = $form[ 'comment2' ];
$last_id = $link->lastInsertId();
$q= $link->query("SELECT id FROM sitelok WHERE Username='$slusername'");
$user_number = $q->fetchColumn();
$collection_item_titles = array($collection_item_title_1, $collection_item_text_1, $collection_item_title_2, $collection_item_text_2);
$statement1 = $link->prepare("INSERT INTO collection_items(collection_list_id, collection_item_number, username_id, collection_item_title, collection_item_text, created_date)
VALUES(:collection_list_id, :collection_item_number, :username_id, :collection_item_title, :collection_item_text, now())");
for ($i = 0; $i < size($collection_item_titles); $i++)
$statement1->execute(array(
"collection_list_id" => $last_id,
"collection_item_number" => "$i",
"username_id" => $user_number,
"collection_item_title" => $collection_item_title[$i],
"collection_item_text" => $collection_item_text[$i]
));
You could create an array and loop through the data and instead of having your data in separate variables ($collection_item_title_1, $collection_item_title_2) you could do something such as $collection_item_titles[] then loop through as such:
statement1 = $link->prepare("INSERT INTO collection_items(collection_list_id, collection_item_number, username_id, collection_item_title, collection_item_text, created_date)
VALUES(:collection_list_id, :collection_item_number, :username_id, :collection_item_title, :collection_item_text, now())");
for ($i = 0; $i < size($collection_item_titles); $i++)
$statement1->execute(array(
"collection_list_id" => $last_id,
"collection_item_number" => "$i",
"username_id" => $user_number,
"collection_item_title" => $collection_item_title[$i],
"collection_item_text" => $collection_item_text[$i]
);
You can't pass more then 1 argument to execute
You can either insert values in a foreach loop or create a query with hundreds of placeholders.
I think first way is better, for example:
$values = array(); // your inserted values array here
$statement1 = $link->prepare("INSERT INTO collection_items(collection_list_id, collection_item_number, username_id, collection_item_title, collection_item_text, created_date) VALUES(:collection_list_id, :collection_item_number, :username_id, :collection_item_title, :collection_item_text, now())");
foreach ($values as $v) {
$statement1->execute($v);
}

Categories