I am receiving the following arrays from a form:
array (size=1)
'checkbox' =>
array (size=2)
0 => string '14' (length=2)
1 => string '13' (length=2)
2 => string '15' (length=2)
array (size=1)
'id' => string '1' (length=1)
I need to build a query looking like this:
$sql = "INSERT INTO table(column1,column2) VALUES (14,1),(13,1),(15,1)";
And the first array will be different every time based on the checked checkboxes.
Well, you can try looping with a foreach on that array. So let's say you have named your checkboxes as name="checkbox[]".
Then on the page where you are processing the $_POST vars you can do
$sql = "INSERT INTO table(column1,column2) VALUES (?,?)";
$stmt = $mysqli->prepare($sql);
foreach ($_POST['checkbox'] as $box) {
//process each checkbox here
$stmt->bind_param('ss', $box, $otherValue);
$stmt->execute();
}
This is just a pseudo-code to get you started.
You can find more info on prepared statements here: http://php.net/manual/en/mysqli-stmt.bind-param.php
// Create an empty array to store each checkbox value
$values = array();
if(is_array($_POST['checkbox'])){
foreach($_POST['checkbox'] as $checkbox){
foreach($checkbox as $key => $value){
// add each checkbox value to an array
$values[] = ($value,$_POST['id']);
}
}
}
// if the array has values..
if(count($values)){
// implode the values into a string..
$sqlValues = implode(',',$values);
// ..and use that string in the query
$sql = "INSERT INTO table(column1,column2) VALUES $sqlValues";
}
Related
I am inserting string with multiple delimiters and split it using explode function to mysql database table but i failed in building proper logic.
I tried with single delimiter i-e , and successfully insert that record.
Now i want to split string with | and ,.
I used for row separation and | for value seperation.
i-e
$var = "Facebook|http://facebook.com/123|12312|12 to 13,Twitter|http://twitter.com/231|12321|12 to 13";
$cat="2,3";
$i=0;
$arrayOfCategories = explode(",", $cat);
foreach ($arrayOfCategories as $categories) {
$datas[$i]['UserID'] = 2;
$datas[$i]['CatID'] = $categories;
$i++;
}
var_dump($datas);
Format showed using var_dump is the format which i want to insert using insert_batch of codeigniter.
This is the expected output
array (size=2)
0 => array (size=2)
'SocialName' => string 'Facebook'
'URL' => string 'facebook.com/123'
1 => array (size=2)
'SocialName' => string 'Twitter'
'URL' => string 'twitter.com/231'
$array = array();
$string = "Facebook|http://facebook.com/123|12312|12 to 13,Twitter|http://twitter.com/231|12321|12 to 13";
$rows = explode(',', $string);
foreach ($rows as $row) {
$values = explode('|', $row);
$array[] = array('SocialName' => $values[0], 'URL' => $values[1]);
}
var_dump($array);
Create an array $array to store the final result in.
Now, split the input string $string on , using explode, this gives you the "rows".
Go through all the rows (foreach), and split each row on the | (explode), this gives you the "values".
The first value $values[0] is the "SocialName", and the second value $values[1] is the "URL", so add those to a new array, and add that new array to the final result array $array.
I have this PHP code to insert into mysql.
require_once("../form/corefile/functions.php");
$fn = new Functions();
$offers = $_REQUEST;
$offer=$_REQUEST['offer'];
$website =$_REQUEST['website'];
$keyword =$_REQUEST['keyword'];
$count_offer = count($_REQUEST['offer']);
var_dump($offer);exit;
for($i=0;$i<$count_offer ;$i++){
$_offer = ($offer[$i]);
$_website = ($website[$i]);
$_keyword = ($offer[$i]);
$query = $fn->InsertQuery("INSERT INTO offers (offer, website, keyword) VALUES ('$_offer','$_website','$_keyword')");
//var_dump($query);exit;
if($query)
{
$msg="Data Successfully Saved";
}
}
The array with var_dump($offer) looks like this;
array (size=2)
0 =>
array (size=1)
'name' => string 'offer1' (length=6)
1 =>
array (size=1)
'name' => string 'offer2' (length=6)
I am getting the error:
Notice: Array to string conversion in repeat.php on line 19
where line 19 is the $query = $fn->insertQuery
Looks like I am making some mistake in pulling the correct data from the array.
The array $offer is an array of associative arrays.$offer[0] would return an array of singular key value pair which ofcourse is not a String hence the error.
I'm trying to write an INSERT SQL request to populate a table of my db with a multidimensional array.
The array use the session variables (it's a shopping cart) $_SESSION['panier'], and currently has the following content :
array (size=3)
'ARTCOD' =>
array (size=2)
0 => string 'NA1818BLCFEZ' (length=12)
1 => string 'SER5151BLCFEZ' (length=13)
'COLLIB' =>
array (size=2)
0 => string 'blanc' (length=5)
1 => string 'blanc' (length=5)
'quantite' =>
array (size=2)
0 => int 6
1 => int '8'
My table has more field :
the 'ID' field, which need to auto increment.
the 'reference' field, which contains the reference of the order, I will generate it randomly.
The 'ARTCOD' field, it's the code associated to an article, here it's in $_SESSION['panier']['ARTCOD'].
The 'CLICOD' field, it's the code associated to the client which is ordering, here it's in $_SESSION['CLICOD'].
the 'quantite' field, the quantity of the ordered article, contained in $_SESSION['panier']['quantite'].
The 'type' field, contain the order type, here it's just a defined word that will not change.
And the 'date' field, contain the timestamp of the order.
So I need help to write a function that will generate my MySQL request without using multiple INSERT.
I've already create this:
$query = "";
for ($i = 0; $i < count($_SESSION['panier']['ARTCOD']); ++$i) {
$query .= 'INSERT INTO commandevalide (id, reference, ARTCOD, CLICOD, quantite, type, date) VALUES ("", "'.$_SESSION['panier']['ARTCOD']['$i'].'", "'.$reference.'", "'.$_SESSION['CLICOD'].'", '.$_SESSION['panier']['quantite']['$i'].', "Location", now());';
}
But I prefer something which will give just one INSERT request.
I saw that I need to use the implode function and a foreach loop but I did not manage to create something working.
To combine all those inserts into a single one, you can try this :
$query = "INSERT INTO commandevalide (id, reference, ARTCOD, CLICOD, quantite, type, date) VALUES ";
for ($i = 0; $i < count($_SESSION['panier']['ARTCOD']); ++$i) {
$query .= '("", "'.$_SESSION['panier']['ARTCOD'][$i].'", "'.$reference.'", "'.$_SESSION['CLICOD'].'", '.$_SESSION['panier']['quantite'][$i].', "Location", now()), ';
}
$query = rtrim($query, ', ');
Note : Don't put $i between single quotes.
I'm new to array and I have a decrypt function and sql query. Process is I query in the database and return the $get in an array like so:
array (size=1)
0 =>
array (size=3)
'Username' => string 'joenefloresca' (length=13)
'MiddleName' => string 'Estero' (length=6)
'Email' => string 'joenefloresca#gmail.com' (length=23)
What I want is to use my decrpyt function (data is encrypted, above is just an example). When I decrypt
it I want it to overwrite $get array with the decrypted values. I can do it this way,
foreach( $get as $key => $result )
{
$get[$key]['Username'] = $decr->decrypt($result['Username']);
$get[$key]['MiddleName'] = $decr->decrypt($result['MiddleName']);
$get[$key]['Email'] = $decr->decrypt($result['Email']);
}
But I can do that if my Fields like Username,MiddleName,Email is fixed in the sql query, what if
it is dynamic? Fields in the query is defined by the user, ex. What if Username is the only field? or Username and Email only? How can I overwrite the array with the decrypted one with the selected Field only?
Thanks.
Just nest another loop inside if you do not want to explicitly set the index you want:
foreach($get as $key => $result) {
foreach($result as $k => $val) { // will loop for each piece/copy of `$result`
$get[$key][$k] = $decr->decrypt($val);
}
}
I am using simplehtmldom to parse a webpage and extract a data and then put it in a mysql database. I successfully extracted the data and put it in array but now the problem i am facing is how to convert this array to variable so that I may use it in my database query to insert the record in the specific fields. I want to convert array to individual variables
here is the code
<?php
include("simple_html_dom.php");
$html = file_get_html('abc.html');
$sched = array();
foreach ( $html->find('tr[class=highlight-darkgrey]') as $event ) {
$item['title'] = trim($event->find('td', 1)->plaintext);
$sched[] = $item;
}
var_dump($sched);
?>
and the output is
array (size=6)
0 =>
array (size=1)
'title' => string 'Network admin, field engineer, engineering analyst, sales executive, PA to HR director Required by Telecommunication Company' (length=124)
1 =>
array (size=1)
'title' => string 'Karachi, Hydrabad, Lahore, Rawalpindi, Peshawar, Multan, Faisalabad' (length=67)
2 =>
array (size=1)
'title' => string '5 - 6 Years' (length=11)
3 =>
array (size=1)
'title' => string 'Knowledge of Field' (length=18)
4 =>
array (size=1)
'title' => string '' (length=0)
5 =>
array (size=1)
'title' => string '- Salary and incentives are not full and final. Can be discussed on final interview.
Can please somebody help me in achieving it. Thanks in advance
Well, if this needs to go in specific fields then you can do something like this:
INSERT INTO table_name (column1, column2, column3,...)
VALUES ($sched[0]['title'], $sched[1]['title'], $sched[2]['title'],...);
Php has a function for getting individual variables, extract() http://php.net/manual/en/function.extract.php
However I don't know why you would do that instead of just using a loop to go though your array.
You mean somethign like
foreach($sched as $item) {
$title = $item['title'];
insert_into_db($title);
}
?
Why do you want to move data from one perfectly good location i.e. the array into a scalar variable.
Double your memory usage for no actual reason.
I assume you are going to want to store the title's in a table
So you can :
foreach ( $sched as $one_sched ) {
// do your database update using $one_sched['title'] as the data identifier.
}
Why not use the array values directly? Also to me it makes no sense to build a subarray where every field is called title.
$sched = array();
foreach ( $html->find('tr[class=highlight-darkgrey]') as $event ) {
$sched[] = trim($event->find('td', 1)->plaintext);
}
Then access the values like:
$value0 = $sched[0];
$value1 = $sched[1];
// PDO example
$sth = $dbh->prepare(
'INSERT INTO table VALUES (?, ?, ...)'
);
$sth->execute(array($sched[0], $sched[1], ...));
// or if array count is right
$sth->execute($sched);