Built one MySQL INSERT using two different arrays using for each - php

I hope someone is able to help me with the problem I'm facing for hours already. I'm trying to built a MySQL INSERT from two arrays. One array ($bms) holds 6 values and the second one holds 3 values (I want to use the array with 3 values inside the INSERT query where I'm using the placeholder group right now). Each value of the (group array) needs to be used 2 times. I hope you understand with my example below:
The 2 arrays – always include 6 respectively 3 values:
Array ( [0] => 8 [1] => 3 [2] => 4 [3] => 121 [4] => 13 [5] => 154 ) // $bms
Array ( [0] => 266 [1] => 267 [2] => 268 ) // group
The query with foreach loops:
$query = "INSERT INTO userlinks (linkpool_id, group, userid) VALUES ";
foreach($bms as $bm) {
$query .= "('".$bm."', group, '".$userid."'),";
}
echo $query;
The output so far:
INSERT INTO userlinks (linkpool_id, group, userid) VALUES ('8', group, '19'),('3', group, '19'),('4', group, '19'),('121', group, '19'),('13', group, '19'),('154', group, '19')
WHAT I'M TRYING TO ACHIEVE:
INSERT INTO userlinks (linkpool_id, group, userid) VALUES ('8', '266', '19'),('3', '266', '19'),('4', '267', '19'),('121', '267', '19'),('13', '268', '19'),('154', '268', '19')
I really appreciate your help and invested time – awesome community!

You can use a for loop instead :
$query = "INSERT INTO userlinks (linkpool_id, group, userid) VALUES ";
for($i = 0; $i < count($bms); $i++) {
$j = (int) $i/2; //[0,1] will return 0, [2,3] return 1 etc...
$query .= "('".$bms[$i]."', '".$groups[$j]."', '".$userid."'),";
}
rtrim($query, ",");
echo $query;
Edit: Thanks #RajdeepPaul for more precision.

Related

php mysql check if vendor has 3 low consecutive ratings

on my ratings table for my software i have 4 fields.
id autoincrement
rvid vendor id
ratedate date of rating
rating the actual numeric rating
I have done alot with it over the last few months but this time im stumped and i cant get a clear picture in my head of the best way to do this. What i am trying to do is find out if the vendor has had 3 low 'consecutive' ratings. If their last three ratings have been < 3 then i want to flag them.
I have been playing with this for a few hours now so i thought i would ask (not for the answer) but for some path direction just to push me forward, im stuck in thought going in circles here.
I have tried GROUP BY and several ORDER BY but those attempts did not go well and so i am wondering if this is not a mysql answer but a php answer. In other words maybe i just need to take what i have so far and just move to the php side of things via usort and the like and do it that way.
Here is what i have so far i did select id as well at first thinking that was the best way to get the last consective but then i had a small breakthrough that if they have had 3 in a row the id does not matter, so i took it out of the query.
$sql = "SELECT `rvid`, `rating` FROM `vendor_ratings_archive` WHERE `rating` <= '3' ORDER BY `rvid` DESC";
which give me this
Array
(
[0] => Array
(
[rvid] => 7
[rating] => 2
)
[1] => Array
(
[rvid] => 5
[rating] => 1
)
[2] => Array
(
[rvid] => 5
[rating] => 0
)
[3] => Array
(
[rvid] => 5
[rating] => 3
)
)
this is just just samples i tossed in the fields, and there are only 4 rows here where as in live it will be tons of rows. But basically this tells me that these are the vendors that have low ratings in the table. And that is where i get stumpted. I can only do one sort in the query so that is why i am thinking that i need to take this and move to the php side to finish it off.
I think i need to sort the elements by rvid with php first i think, and then see if three elements in a row are the same vender (rvid).
Hope that makes sense. My brain hurts lol...
update - here is all of the table data using *
Array
(
[0] => Array
(
[id] => 7
[rvid] => 7
[ratedate] => 2016-05-01
[rating] => 2
)
[1] => Array
(
[id] => 8
[rvid] => 5
[ratedate] => 2016-05-01
[rating] => 1
)
[2] => Array
(
[id] => 6
[rvid] => 5
[ratedate] => 2016-05-01
[rating] => 0
)
[3] => Array
(
[id] => 5
[rvid] => 5
[ratedate] => 2016-05-01
[rating] => 3
)
)
Here's one way you can begin approaching this - completely in SQL:
Get the last rating for the vendor. ORDER BY date DESC, limit 1.
Get the second to last rating for the vendor. ORDER BY date DESC, limit 1, OFFSET 1.
Then write a query that does a LEFT join of the first two tables. You will have a dataset that has three columns:
vendor id
last rating
second to last rating
Then you can write an expression that says "if column1 is <3 and column2 < 3, then this new column is true"
You should be able to extend this to three columns relatively easily.
Here is what a came up with to solve this riddle. I think explaining it on here helped as well as Alex also helped as he keyed my brain on using the date. I first started looking at using if statment inside of the query and actually that got my brain out of the box and then it hit me what to do.
It is not perfect and certainly could use some trimming to reduce the code, but i understand it and it seems to work, so that is par for me on this course.
the query...
$sql = "SELECT `rvid`, `ratedate`,`rating` FROM `vendor_ratings_archive` WHERE `rating` <= '3' ORDER BY `ratedate`, `rvid` DESC";
which gives me this
Array
(
[0] => Array
(
[rvid] => 7
[ratedate] => 2016-05-01
[rating] => 2
)
[1] => Array
(
[rvid] => 5
[ratedate] => 2016-05-01
[rating] => 1
)
[2] => Array
(
[rvid] => 5
[ratedate] => 2016-05-01
[rating] => 0
)
[3] => Array
(
[rvid] => 5
[ratedate] => 2016-05-01
[rating] => 3
)
)
notice how vendor (rvid) 5 is grouped together which is an added plus.
next a simple foreach to load a new array
foreach($results as $yield)
{
$rvidarray[] = $yield['rvid'];
}//close foreach
which gives me this
Array
(
[0] => 7
[1] => 5
[2] => 5
[3] => 5
)
then we count the array values to group dups
$rvidcounter = array_count_values($rvidarray);
which results in this
Array(
[7] => 1
[5] => 3
)
so now vender 7 as 1 low score and vendor 5 has 3 low scores and since they were already sorted by date i know that its consecutive. Well it sounds good anyway lol ")
then we create our final array with another foreach
foreach($rvidcounter as $key => $value)
{
//anything 3 or over is your watchlist
if($value > 2)
{
$watchlist[] = $key; //rvid number stored
}
}//close foreach
which gives me this
Array
(
[0] => 5
)
this was all done in a service function. So the final deal is everyone in this array has over 3 consecutive low ratings and then i just use a returned array back in my normal php process file and grab the name of each vender by id and pass that to the html and print out the list.
done...
please feel free to improve on this if you like. I may or may not use it because the above code makes sense to me. Something more complicated may not make sense to me 6 mos from now lol But it would be interesting to see what someone comes up with to shorten the process a bit.
Thanks so much and Happy Coding !!!!!
Dave :)
You could do it in SQL like that:
SET #rvid = -1;
SELECT DISTINCT rvid FROM
(
SELECT
rvid,
#neg := rating<3, /* 0 or 1 for addition in next line */
#count := IF(#rvid <> rvid , #neg, #count+#neg) AS `count`, /* set or add */
#rvid := rvid /* remember last row */
FROM
testdb.venrate
ORDER BY
rvid, datetime desc
) subq
WHERE count>=3
;
You set a variable to a non existing id. In each chronologically sorted row you check if rating is too low, that results in 1 (too low) or 0 (ok). If rvid is not equal to the last rvid, it means a new vender section is beginning. On begin of section set the value 0 or 1, else add this value. Finally store the current row's rvid for comparison in next row process.
The code above is looking for 3 consecutive low ratings (low means a value less than 3) over all the time.
A small modification checks if all the latest 3 ratings has been equal to or less than 3:
SET #rvid = -1;
SELECT DISTINCT
rvid
FROM
(
SELECT
rvid,
#high_found := rating>3 OR (#rvid = rvid AND #high_found) unflag,
#count := IF(#rvid <> rvid , 1, #count+1) AS `count`,
#rvid := rvid /* remember last row */
FROM
testdb.venrate
ORDER BY
rvid, datetime desc
) subq
WHERE count=3 AND NOT unflag
;

match all values in an array php

The user can search for something using select and checkbox forms. The data is sent in GET variables.
I'm collected all the possible values in variables and putting it into an array:
$term_taxomony_ids_array = array($term_taxonomy_id_m, $term_taxonomy_id_l, $term_taxonomy_id_t_1, $term_taxonomy_id_t_2, $term_taxonomy_id_t_3, $term_taxonomy_id_t_4, $term_taxonomy_id_t_5, $term_taxonomy_id_t_6, $term_taxonomy_id_t_7, $term_taxonomy_id_t_8);
print_r($term_taxomony_ids_array); would then give
eg:
Array (
[0] => 12
[1] => 14
[2] =>
[3] =>
[4] => 9
[5] =>
[6] => 2
[7] =>
[8] =>
[9] =>
)
How would I make this array simpler but leaving out the empty results altogether (as suggested in a comment)?
I need to find the 'places' in the database who match all the criteria that was selected.
My database table is set up so I have two columns.
1. Object_id 2. term_taxonomy_id.
The term_taxonomy_id are the values in the array.
eg my table looks like this
Object id term_taxonomy_id
2 12
2 3
3 12
3 14
3 9
3 2
4 5
5 9
So only object_id '3' matches all the terms in the array - 12, 14, 9, 2
How would I run a query to find this result?
I'm using a mysql database, phpmyadmin and my site is built on wordpress.
Thanks
Basically:
SELECT objectID, COUNT(term_taxonomy_id) AS cnt
FROM yourtable
WHERE term_taxonomy_id IN (2, 9, 14, 12)
GROUP BY objectID
HAVING cnt = 4
find all the objectIDs that have one or more matching taxonomy IDs, but then return only the object IDs that have FOUR matching taxonomy IDs.
Use IN, Combined with COUNT() and having/GROUP.
$array = array_filter(array_unique($array));
$count = count($array);
$sql = "SELECT id, COUNT(*) FROM table WHERE field IN (" . implode(',', $array) . ") GROUP BY id HAVING COUNT(*) = " . $count;
The SQL might be a bit off (you might have to re-order having and group).

php dynamically create multi dimensional array

I am writing a php script to extract some data from a MYSQL db, then I want to take that data and store it into a two dimensional array. Thinking of it normally, if I use code like this
$test = array();
$test[0]=array();
$test[0]['hello']='hello';
$test[1]=array();
$test[1]['hello']='hello';
$test[2]=array();
$test[2]['hello']='hello';
print_r($test);
the output will be:
Array ( [0] => Array ( [hello] => hello ) [1] => Array ( [hello] => hello ) [2] =>
Array ( [hello] => hello ) )
which is how I want my output to be
so this is what I do in my script
So basically in my database I have table with standings for a women's league and the columns are
team_name, played, won, drawn, lost, for, against, points
All the connections have been taken care of successfully, below is my query
$get_ladies_query = "SELECT
`team_name`, `played`, `won`, `drawn`, `lost`, `for`, `against`, `points`
FROM `standings_ladies` order by pos";
An important point to not before I show the next code is that, there are 2 other standings tables, men_senior and men_intermediate with the same structure but obviously only the data changes, below are the two queries just incase
$get_mens_inter_query = "SELECT
`team_name`, `played`, `won`, `drawn`, `lost`, `for`, `against`, `points`
FROM `standings_men_inter` order by pos";
$get_mens_senior_query = "SELECT
`team_name`, `played`, `won`, `drawn`, `lost`, `for`, `against`, `points`
FROM `standings_men_senior` order by pos";
Now I create 3 arrays which I want to hold standings seperately for the ladies, mens senior, mens intermediate
$standings_ladies = array();
$standings_men_inter = array();
$standings_men_senior = array();
The data I want displayed in the array is like so
array(0=>array(team_name,wins,drawn,lost,for,against,points)
1=>array(team_name,wins,drawn,lost,for,against,points)) and so on
Now since I wanted to create the multidimensional arrays of standings for all 3 categories, I could have run the queries in 3 separate while loops altough I thought, I could accomplish the same result in 1 and i felt it would help improve performance. If its better to use 3 while loops, please let me know, what I tried is below.
//I run the 3 queries and store them in the given variables
$result_mens_senior = mysqli_query($link,$get_mens_senior_query);
$result_mens_inter = mysqli_query($link,$get_mens_inter_query);
$result_ladies= mysqli_query($link, $get_ladies_query);
//I want to create 1 while loop so based of the results returned from the 3
//queries so based on the results returned from the 3 queries,
//I get the max number of times I want the query to run
$ladies_boundary = mysqli_num_rows($result_ladies);
$mens_senior_boundary = mysqli_num_rows($result_mens_senior);
$mens_inter_boundary = mysqli_num_rows($result_mens_inter);
$max_size = max(array($ladies_boundary,$mens_senior_boundary,$mens_inter_boundary));
//set an index to start from 0
$index = 0;
//I will only show the example for 1 of the arrays but you get an idea
that this issue will occur for all
while ($index < $max_size)
{
//first, everytime the loop is entered, we need the next row to be fetched
$standings_men_inter_table = mysqli_fetch_assoc($result_mens_inter);
$standings_ladies_table = mysqli_fetch_assoc($result_ladies);
//there is a high chance that the other two tables return a different row size
//so its best to check that we do not go beyond
if($index < $mens_senior_boundary)
{
//we fetch the rows every time we enter the block
$standings_men_senior_table = mysqli_fetch_assoc($result_mens_senior);
//then, this is how I attempt at creating the 2 dimensional array
array_push($standings_men_senior, array(
$standings_men_senior_table['team_name'],
$standings_men_senior_table['played'],
$standings_men_senior_table['won'],
$standings_men_senior_table['drawn'],
$standings_men_senior_table['lost'],
$standings_men_senior_table['for'],
$standings_men_senior_table['against'],
$standings_men_senior_table['points']));
}
//incrementing index each time the loop runs
$index++;
}
Then finally, I just want to print what I think is the array but get this, attached image, hope you can see it clearly
Just to investigate even further, every time, the 'if' block is entered, I just commented everything out and just put this to see what was being returned
if($index < $mens_senior_boundary)
{
print_r(mysqli_fetch_assoc($result_mens_senior));
}
The output I got was almost 90% what I need
Array
([team_name] => Morley Gaels [played] => 8 [won] => 6 [drawn] => 2
[lost] => 0 [for] => 110 [against] => 83 [points] => 14 )
Array ( [team_name] => Southern Districts [played] => 8 [won] => 3 [drawn] => 2
[lost] => 3 [for] => 104 [against] => 98 [points] => 8 )
Array ( [team_name] => St Finbarrs [played] => 8 [won] => 3 [drawn] => 2
[lost] => 3 [for] => 107 [against] => 99 [points] => 8 )
Array ( [team_name] => Western Shamrocks [played] => 8 [won] => 3 [drawn] => 0
[lost] => 5 [for] => 96 [against] => 88 [points] => 6 )
Array ( [team_name] => Greenwood [played] => 8 [won] => 1 [drawn] => 1
[lost] => 9 [for] => 82 [against] => 109 [points] => 3 )
What I need is for example:
Array(0=>Array
([team_name] => Morley Gaels [played] => 8 [won] => 6 [drawn] => 2
[lost] => 0 [for] => 110 [against] => 83 [points] => 14 )
1=>Array
([team_name] => Southern Districts [played] => 8 [won] => 3 [drawn] => 2
[lost] => 3 [for] => 104 [against] => 98 [points] => 8 )..... so on);
My questions are
What is wrong with my code and what is the correct way to dynamically create
multidimensional arrays in php ?
Is there something I have not understood about how mysql_fetch_assoc works and how it returns ?
Anything to improve, anything I am doing wrong ?
I appreciate your time, than you for reading it, I tried to be as detailed as I can about what I have tried.
Thank You.
Try this
After you do this:
$result_mens_senior = mysqli_query($link,$get_mens_senior_query);
$result_mens_inter = mysqli_query($link,$get_mens_inter_query);
$result_ladies= mysqli_query($link, $get_ladies_query);
just do this
while ($standings_men_senior[] = mysqli_fetch_assoc($result_mens_senior)){}
while ($standings_men_inter[] = mysqli_fetch_assoc($result_mens_inter)){}
while ($standings_ladies[] = mysqli_fetch_assoc($result_ladies)){}
Basically all of the posted code should be able to be replaced with:
<?php
$ladies_query = "SELECT `team_name`, `played`, `won`, `drawn`, `lost`, `for`, `against`, `points`
FROM `standings_ladies` order by pos";
$inter_query = "SELECT `team_name`, `played`, `won`, `drawn`, `lost`, `for`, `against`, `points`
FROM `standings_men_inter` order by pos";
$senior_query = "SELECT `team_name`, `played`, `won`, `drawn`, `lost`, `for`, `against`, `points`
FROM `standings_men_senior` order by pos";
$ladies_stmt = mysqli_query($link, $ladies_query) || die ("Couldn't get Ladies"); // reminds me of high school
$inter_stmt = mysqli_query($link, $inter_query) || die ("Couldn't get Inter");
$senior_stmt = mysqli_query($link, $serior_query) || die ("Couldn't get Seniors");
$standings_men_senior = array();
$standings_men_inter = array();
$standings_ladies = array();
while ($row = mysqli_fetch_assoc($senior_stmt)){
$standings_men_senior[] = $row;
}
while ($row = mysqli_fetch_assoc($inter_stmt)){
$standings_men_inter[] = $row;
}
while ($row = mysqli_fetch_assoc($ladies_stmt)){
$standings_ladies[] = $row;
}
Don't try to put everything in a single loop, it significantly reduces your code clarity and will give you little to no gain in performance, there is a term for this and it's called micro-optimization, and you should never do it unless it is really necessary (a bottleneck on a large site).
Now, what I suggest to you is to remake your loop and make it as clear as possible as to how data is manipulated.
The most important thing in your case is to debug, print_r the content of your arrays on every step of the process to check what it contains, from the database to the end of your code, you will find where the problem is.

multiple sorting in php or/and mysql doesn't take effect

EDIT
solved ! it was my fault, the mysql query and the php method, both are working perfectly. my very bad example cunfused myself. aktually they should be sorting products by favorite ( true / false ) and then by date.
i'm trying to sort a multidimensional array by two "cols" but it just won't work for me :O
I've serched and copyed all possible ways ( mysql - order by, php - array_multisort() )
but it still won't work for me....
here is the method i've tryed first:
// MySQL Query
SELECT * FROM `test` ORDER BY `name` ASC, `age` DESC;
// or
SELECT * FROM `test` ORDER BY `name`, `age`;
// or
SELECT * FROM `test` ORDER BY name, age;
// or
SELECT * FROM `test` ORDER BY name, age DECT;
// `name` is VARCHAR and `age` is INT
so , i've tryed all possible syntax, but the query wont give me the wanted result.
the original table :
ID NAME AGE
---------------------
1 adam 23
2 bernd 30
3 cris 22
4 dora 21
5 anton 18
6 brad 36
7 sam 41
8 ali 13
what i want to get from MySQP Query :
ID NAME AGE
--------------------- // first sort by name...
8 ali 13 // then sort by age
5 anton 18 // ...
1 adam 23 // for each "similar" name or names with "a", "b", ...
2 bernd 30 // and so on...
6 brad 36
3 cris 22
4 dora 21
7 sam 41
but it actually gives my either sorted by NAME ( ORDER BY name, age ) or AGE ( ORDER BY age, name;
as i get frustrated, i've decidet to just get that query and sort it in PHP...
well, i've also tryed some codes but they all don't work either.
here is the one i aktually did now:
// this array is just exported from mysql to debug without mysql query...
$test = array(
array('id' => '1','name' => 'adam','age' => '23'),
array('id' => '2','name' => 'bernd','age' => '30'),
array('id' => '3','name' => 'cris','age' => '22'),
array('id' => '4','name' => 'dora','age' => '21'),
array('id' => '5','name' => 'anton','age' => '18'),
array('id' => '6','name' => 'brad','age' => '36'),
array('id' => '7','name' => 'sam','age' => '50'),
array('id' => '8','name' => 'ali','age' => '13')
);
// ...print out the original array
foreach( $test as $key => $value ) {
echo $value['name'] . " - " . $value['age'] . "<br>";
}
// here is the part where i am sorting...
$sort = array();
foreach ($test as $key => $value ) {
$sort['name'][$key] = $value['name'];
$sort['age'][$key] = $value['age'];
}
array_multisort($sort['age'], SORT_ASC, $sort['name'], SORT_DESC, $test);
// ...till here.
// reorder array and print the new sorted array
$sorted = array();
for( $i = 0; $i < count( $sort['name'] ); $i++ ) {
array_push( $sorted, array( $sort['name'][$i], $sort['age'][$i] ) );
echo $sort['name'][$i] . " - " . $sort['age'][$i] . "<br>";
}
but as you'll see if you test this, the sorting will just affect the AGE...
i dont know what i am doing wrong, prease tell me guys T_T
It appears to me that you only want to sort on the first char of the name:
You should try:
SELECT * FROM `test` ORDER BY SUBSTR(name,0,1), age;
What you encountered is absolutely expected behaviour. Why? If you sort first by name, you get results sorted for the full strings in the name column, where
'adam' < 'ali' < 'anton'
If there were more than one rows with name='adam', but different ages, like this:
ID NAME AGE
---------------------
1 adam 23
5 anton 18
8 ali 13
9 adam 52
You would get this result for SELECT * FROM test ORDER BY name, age;
ID NAME AGE
---------------------
1 adam 23
9 adam 52
8 ali 13
5 anton 18
As it is first sorted by name column, where the two adam values are the same, and then sorts based on the age, where 23 is smaller than 52...
But now, sorting on first character of name, and age SELECT * FROM test ORDER BY SUBSTR(name,0,1), age;:
ID NAME AGE
---------------------
8 ali 13
5 anton 18
1 adam 23
9 adam 52
If I unserstand you correctly, what you want to do is to sort just on the first letter of the name, then on the age. - What you have gotten from mysql is just what I would expect from your query and data set. If you choose several columns for sort, the secound kicks in only if you have equal values in the first one, eg if you had two Adams, one 18 and one 20 years old, the two would be sorted by age. and if you had Adam and Beth, both 18, Beth would come after Adam in the "sort by age,name"

MySQL: Update several entries with array values in 1 call?

If I have a table in a MySQL DB, with fields id and position amung others.
Then in PHP I have an array like this:
Array
(
[0] => 1
[1] => 3
[2] => 8
[3] => 4
[4] => 5
[5] => 6
[6] => 7
)
Where the array key should map to the position and the array value should map to the id.
For example, If I made a call for every array value the first would be
UPDATE table SET position = 0 WHERE id = 1
Is there a way I could do all this in 1 call?
$string = "";
foreach($array as $k => $v)
$string .= "UPDATE table SET position = ".$v." WHERE id = ".$k.";";
mysql_query($string);
updating multiple records with different values for each record is possible, but it's not recommdned - it makes for an incredibly ugly query:
UPDATE table
SET position = CASE position
WHEN 0 THEN 1
WHEN 1 THEN 3
WHEN 2 THEN 8
etc...
Here we go a foreach solution :
$Array = array(0 => 1, 1 => 3);
if(count($Array) > 0){
foreach($Array as $Key => $Value)
// UPDATE table SET position = 1 WHERE id = 3 LIMIT 1
mysql_query('UPDATE table SET position = '.$Key.' WHERE id = '.$Value.' LIMIT 1;');
}
Problem : you can't do multiple update with MySQL ... yes, like Marc B said but it's very ugly.

Categories