I have an array called $columns :
array(3) {
[0]=>
string(8) "Food"
[1]=>
string(6) "Calories"
[2]=>
string(3) "Carbs"
}
array(3) {
[0]=>
string(8) "Food"
[1]=>
string(6) "Calories"
}
Another called values
array(5) {
[0]=>
string(4) "'Fish'"
[1]=>
string(7) "'100'"
[2]=>
string(13) "'0'"
}
array(6) {
[0]=>
string(4) "'Tatoe'"
[1]=>
string(7) "'100'"
}
I have columns in my database that represent all possible columns that an array has.The arrays could have 5,6 more or less columns depending on the item.
I have this code that is suppose to generate the sql statement in this sense :
INSERT INTO MEALS (the columns in that array) VALUES (the values in the value array)
Here is the code :
for($i = 0; $i < count($column); $i++)
{
echo("INSERT INTO 'MEALS` ($column[$i]) VALUES ($values[$i])\n");
}
The problem is for each "MEAL":
n(per column) number of sql queries will be generated.
as such :
INSERT INTO `MEALS` (Food) VALUES ('Fish')
INSERT INTO `MEALS` (Calory) VALUES ('100')
INSERT INTO `MEALS` (Carbs) VALUES ('0')
Instead of it all being on the same query.
INSERT INTO MEALS (Food,Calory,Carbs) VALUES ('Fish','100','0')
So if i insert in the database, 3 rows will be created.
I know i am missing the logic, any help is appreciated
Why aren't you genererating the two parts of your query (1 variable for columns in insert and 1 variable for values) inside your array loop?
Once your loop is done, simply concatenate your strings :
$query = "INSERT INTO 'MEALS' (" . $var_column_list . ") VALUES (" . $var_values_list . ")";
$query = "insert into table(".join($colomn,','). ") values (\"".join($values,'","')."\")";
Try using variant of above according to your need
Try This....
$colums = implode(',', $array_of_colums);
$values = implode(',', $array_of_values);
$query = "INSERT INTO `tableName` (".$colums.") VALUES(".$values.") ";
Related
First of all, I couldn't think of any better title, sorry if you find it inapropiate.
I have this function which task is to bring data from 2 databases, modify some of that data, and upload everything to an external API.
The first database accounting has
subscriber_id | amount | zone_id
stored in the table named cdr
The second db billing has stored inside the table billing_zones these values:
zone_id | zone_name
Everything I've done works fine, but the resulting array is not what I expected/wanted.
This is my code:
try {
$conn = new PDO('mysql:host=host;dbname=accounting','user','password');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}catch(PDOException $e){
echo "ERROR: " . $e->getMessage();
}
$destinationId = 0;
$stmt = $conn->prepare('SELECT a.`zone`, b.`source_external_subscriber_id`, SUM(b.`source_customer_cost`) AS total
FROM `billing`.billing_zones a INNER JOIN cdr b
ON a.`id` = b.`source_customer_billing_zone_id`
WHERE destination_account_id = :destinationId
GROUP BY b.`source_external_subscriber_id`, a.`zone`');
$stmt->execute(array('destinationId' => $destinationId));
foreach ($stmt as $row) {
$data[] = $row;
}
for ($i=0; $i < sizeof($data); $i++) {
$sanitizedData[$i] = array(
0 => $data[$i][0],
1 => $data[$i][1],
2 => $data[$i][2]
);
}
/*ATTEMPT TO MAKE THE ARRAY I WANTED - DIDN'T WORK*/
for ($i=0; $i < sizeof($data); $i++) {
while ($sanitizedData[$i] == $sanitizedData[$i-1][1]) {
$newArray[] = array_merge($sanitizedData[$i], $sanitizedData[$i-1]);
}
}
var_dump($sanitizedData);
The result of the code above my ATTEMPT comment is a big array, I will show you a piece of it so you can understand better what I want to do:
[1047]=>
array(3) {
[0]=>
string(27) "Llamadas Moviles nacionales"
[1]=>
string(9) "V30048086"
[2]=>
string(10) "460.440000"
}
[1048]=>
array(3) {
[0]=>
string(28) "Llamadas Premium 902 Nivel 1"
[1]=>
string(9) "V30048086"
[2]=>
string(9) "87.301236"
}
[1049]=>
array(3) {
[0]=>
string(25) "Llamadas Fijos nacionales"
[1]=>
string(9) "W24154073"
[2]=>
string(9) "64.340367"
}
[1050]=>
array(3) {
[0]=>
string(27) "Llamadas Moviles nacionales"
[1]=>
string(9) "W24154073"
[2]=>
string(10) "116.480000"
}
[1051]=>
array(3) {
[0]=>
string(28) "Llamadas Premium 901 Nivel 1"
[1]=>
string(9) "W24154073"
[2]=>
string(9) "62.559759"
}
To clarify:
array[n][0] is the aforementioned zone_name
array[n][1] is the subscriber_id - The id defining the customer
array[n][2] is the SUM() of the amount for that id in that zone.
So the result is that for every id, there are several arrays for each zone.
What I want to do is to group those in a unique array like:
[1051]=>
array(3) {
[0]=>
string(9) "W24154073"
[1]=>
string(28) "Llamadas Premium 901 Nivel 1"
[2]=>
string(9) "62.559759"
[3]=>
string(28) "Llamadas Moviles nacionales"
[4]=>
string(9) "116.480000"
[5]=>
string(28) "Llamadas Fijos nacionales"
[6]=>
string(9) "64.340367"
.
.
.
If there were more
}
As #Misorude pointed out in the comments, maybe using the subscriber_id as key for the main array would be a better solution:
["W24154073"]=>
array(3) {
[0]=>
string(28) "Llamadas Premium 901 Nivel 1"
[1]=>
string(9) "62.559759"
[2]=>
string(28) "Llamadas Moviles nacionales"
[3]=>
string(9) "116.480000"
[4]=>
string(28) "Llamadas Fijos nacionales"
[5]=>
string(9) "64.340367"
.
.
.
If there were more
}
This way, I could later access the array and fetch the info customer by customer, not having in mind how many zones they are in.
I don't know if this is all necessary or if I don't even need any of this to begin with, but I could not think about any way to do it. Maybe I have overthinked this a lot.
If you know how to turn the array I get into the array I want it would be great, but if there is another solution to pass the data easier than this, then please, bring me the light I need.
Thank you for the help, have a great weekend!
After a bit of discussion and clarifying the requirement, this boiled down to inserting two data fields from each record into an array, grouped under an ID value from a third field.
This can be a achieved in quite a simple fashion, like this:
$data = [];
foreach ($stmt as $row) {
// $row[1] is the subscriber_id
$data[$row[1]][] = $row[0]; // $row[0] is zone_name
$data[$row[1]][] = $row[2]; // $row[2] is the sum amount
}
var_dump($data);
The “trick” here is to let PHP take care of the grouping, basically, by providing the grouping id as array key on the first level, $data[$row[1]], and then simply appending new items under that on the second level, using [] = … syntax.
I am trying to provide a count of certain sizes of lockers. My SQL statement is:
$sql = "SELECT Concat(`Height`, 'x', `Width`, 'x', `Depth`) as Locker, count(*) from lockers GROUP BY `Height`, `Width`, `Depth` ";
a var_dump in a loop of the rows gives me the following (many more rows are possible):
array(2) { ["Locker"]=> string(8) "15x30x45" ["count(*)"]=> int(6) }
array(2) { ["Locker"]=> string(8) "45x30x45" ["count(*)"]=> int(4) }
I want to obtain a JSON string that looks like this:
{
"SizeList": {
"15x30x45": 6
"45x30x45": 4
}
}
I have tried a lot of different methods (including converting it into an object, but I can't get the value of the size as an index. For example, I get different variations of:
[0]=> string(31) "{"Locker":"15x30x45","count(*)":6}"
[1]=> string(31) "{"Locker":"45x30x45","count(*)":4}"
Any help appreciated...
You could just manually create the object like this:
$sizeList = new stdClass();
foreach ($results as $row) {
$sizeList->{$row['Locker']} = $row['count(*)'];
}
echo json_encode(array('SizeList' => $sizeList));
I'm trying to insert an array of IDs into a database table, but at the moment it only inserts 1 row when it's meant to do multiple rows. My array of IDs contains just (filmid) Does anyone know what the problem is?
$pm = "2";
$id = "2";
if($stmt1->execute())
{
$films=array();
foreach($_SESSION['products'] as $key=>$product)
{
array_push($films, $product['filmid']);
$f_id = implode(",", $films);
$stmt2 = $this->conn->prepare("INSERT INTO `filmPurchase` (`fpid`, `payid`, `filmid`, `shopid`, `custid`, `price`) VALUES (NULL, :id, :f_id, :pm, :pm, '8')");
$stmt2->bindParam('pm',$pm);
$stmt2->bindParam('id',$id);
$stmt2->bindParam('f_id',$f_id);
$stmt2->execute();
}
}
I've tried to loop over the array with:
foreach($_SESSION['products'] as $key=>$product)
{
var_dump($key);
var_dump($product);
}
This is what outputted:
int(29) array(4) { ["qty"]=> int(1) ["filmtitle"]=> string(45) "The Lord of
the Rings: The Return of the King" ["filmid"]=> string(2) "29" ["price"]=>
float(6.99) }
If your placeholder is :id and :pm (as in prepare()) then you must use :id in bindParam()
See php documentation
I am trying to create a query from a form that passes ID and Details fields, the post array looks like this:
array(2) {
["ID"]=> array(9)
{
[0]=> string(3) "10a"
[1]=> string(3) "10b"
[2]=> string(3) "10c"
[3]=> string(3) "10d"
[4]=> string(3) "10e"
[5]=> string(3) "10f"
}
["Details"]=> array(9)
{
[0]=> string(19) "This is textfield 1"
[1]=> string(17) "This is textfield 2"
[2]=> string(0) ""
[3]=> string(0) ""
[4]=> string(0) ""
[5]=> string(0) ""
}
}
The ID is hardcoded into the page and always passed, the details can be filled out by the user as needed.
if ($_POST['OthProb']['Details'] != '') {
// Catch issue text and assign to variable
foreach ( $_POST['OthProb']['Details'] as $key => $value) {
$id = $_POST['OthProb']['ID']->$key;
$dets = $value;
// Focus on fields with values and join the array values together in a query string
if ($dets != ''){
$string = "INSERT into $table (AccountID, OtherID, ID, Details) VALUES ($_POST[AccountID], $_POST[OtherID], '".$id.", '".$dets."')";
$sql = $DBH->prepare($string);
// $sql->execute();
// var_dump ($id);
}
}
}
creates the following
"INSERT into tbl_problems (AccountID, OtherID, ID, Details) VALUES (80, 80, '10f, 'This is Title issue')"
The 'Details' are outputting correctly, but its cycling all the way through the ID's to the last one, is that because I'm nesting a foreach? What would be the best way to structure the loop?
Try to replace this line:
$id = $_POST['OthProb']['ID']->$key;
by
$id = $_POST['OthProb']['ID'][$key];
I have a multidimensional array called $data that is basically data extracted from a table into the array.
This is how I get my array using JS_extractor:
set_include_path(get_include_path() . PATH_SEPARATOR . './library/');
require_once 'JS/Extractor.php';
$extractor = new JS_Extractor(file_get_contents('temp.html'));
$body = $extractor->query("body")->item(0);
$table = $body->query("//table[#class='rstatisztika_tabla']")->item(0);
$data = array();
foreach ($table->query('tr') as $i => $tr) {
if ($i == 0) {
continue;
}
$a = $tr->query('.//a');
$a = $a->item($a->length - 1);
$url = $a->getAttribute('href');
$parsed = parse_url($url);
parse_str($parsed['query'], $query);
$data[] = array(
$a->textContent,
$url,
$query['user'],
);
}
//var_dump($data);
when I actually do
var_dump($data);
I get this:
array(3)
{
[0]=> array(3)
{
[0]=> string(4) "Thad"
[1]=> string(7) "http://localhost/index.php?m=karakterlap&user=91"
[2]=> string(2) "91"
}
[1]=> array(3)
{
[0]=> string(4) "Bill"
[1]=> string(8) "http://localhost/index.php?m=karakterlap&user=110"
[2]=> string(3) "110"
}
[2]=> array(3)
{
[0]=> string(7) "Thadson"
[1]=> string(7) "http://localhost/index.php?m=karakterlap&user=147"
[2]=> string(3) "147"
}
}
I also have a Mysql database table called warlord
CREATE TABLE IF NOT EXISTS `warlord` (
`id` int(5) NOT NULL default '0',
`name` varchar(35) character set utf8 NOT NULL default '',
`active` tinyint(1) NOT NULL default '1',
UNIQUE KEY `id` (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
INSERT INTO `warlord` (`id`, `name`, `active`) VALUES
(2, 'Admin', 0), (100, 'Thadson', 1), (147, 'John', 1);
From the array, I want to add the new users (Thad & Bill) to the warlord table and set them active (1)
I want the user (Thadson), who is also in the array, to stay active (1)
However I want the user (John) who is not in the array, set to inactive (0)
and leave admin who is also not in the array (and is already inactive) inactive (0)
I know this is a very beginners question, but how do I do this?
Thanks
You might want to use array_map function to set a callback function for the multi-array and process it accordingly:
array_map
I saw this and I have tried it:
$data = array();
for($i=0; $i<count($data_array); $i++){
$data_items[$i] = explode(',', $data_array[$i]); // create a multi-dimensional array
$data[] = '( ' .$data_items[$i][2]. ', '.$data_items[$i][0]. ', '. 1 .')';
}
$sql = "INSERT INTO warlord(id, name, active) VALUES ('".$data_items[$i][2]."','".$data_items[$i][0]."','1') ";
...to get the data into my table
I ignore the 2nd elements from the array (The ones that look like this: [1]=> string(7) "user=91") and I try to insert elements [2] and [0] into the table and make the new users active with placing 1 into the active field.
This obviously doesn't do all I need (actually it doesn't do any of it) and I have no idea what I'm doing. This is why I'm asking for help.
If I was to approach this question I would firstly try to organise my arrays (the $data array and also the array from the database) into a similar format (possibly using the id as the array key) so that I could use array_intersect to work out the people in both $data and $database (ie. people who should set active) and array_diff to work out the people in $data and not in $database (ie. the people who need to be added to the database) and then array_diff again (with $database first this time) to work out the people in $database and not in $data (ie. the people who should be set inactive).
Hope this helps put you on the write track. Sorry but I don't have the time to actually write the code for you.