How to loop the query in this case? - php

I have been trying to loop this query but all I get is the first value.
When I do the same command in workbench I get all the values.
What am I doing wrong here? Any answers are much appreciated!
global $db;
$stmt12 = $db->query('SELECT `Value` FROM overriddenpropertyvalues WHERE ParentGUID LIKE "' . $itemguid . '";');
$propertyvaluerow = $stmt12->fetch();
while ($propertyvaluerow != null) {

You are fetching only one value with ->fetch(). That's why you receive only one value.
Example from here:
$query = $db->prepare('SELECT `Value` FROM `overriddenpropertyvalues` WHERE ParentGUID LIKE :like');
$query->execute([':like' => $itemguid]);
$stmt->bind_result($value);
while ($query->fetch()) {
echo $value."<br/>"
}

There might possibly be a loophole in your Program depending on what the $stmt12->fetch() does. If it fetches an Array of Data, your while loop might not behave as expected. Below is a commented alternative to what you might want to try out:
<?php
global $db;
$stmt12 = $db->query('SELECT `Value` FROM overriddenpropertyvalues WHERE ParentGUID LIKE "' . $itemguid . '";');
// ASSUMES YOU ARE USING PDO SO WE FETCH ALL THE DATA
$propertyvaluerow = $stmt12->fetchAll();
// THERE MIGHT BE A LOOPHOLE IN YOUR PROGRAM DEPENDING ON WHAT $stmt12->fetch() IS AND DOES
// ASSUMING IT FETCHES AN ARRAY OF NESTED OBJECTS OR SCALAR VALUES, THE WHILE LOOP WOULD NOT BEHAVE AS EXPECTED.
// THAT MEANS IF IT IS AN ARRAY YOU COULD USE A DIFFERENT CONSTRUCT LIKE THE ONE BELOW YOUR WHILE CONSTRUCT:
/* while ($propertyvaluerow != null) { */
// CREATE A $count VARIABLE TO HOLD THE INCREMENTAL COUNT THROUGH THE ITERATION:
$count = count($propertyvaluerow);
while($count > 0){
// DO YOUR WORK HERE
//DECREMENT THE VALUE OF COUNT OTHERWISE YOU MAY HAVE AN INFINITE LOOP TO DEAL WITH.
$count--;
}
?>
There is yet another alternative:
<?php
// OR EVEN A MUCH MORE EASIER WAY IS TO USE THE FOREACH LOOP, WHICH ACHIEVES THE SAME THING AS THE WHILE LOOP:
foreach($propertyvaluerow as $iKey=>$objData){
// SIMPLY USE THE $objData IN WITHING THE LOOP
// THE $objData IS THE VALUE OF THE CURRENT OBJECT IN THE $propertyvaluerow IN THE ITERATION
}

Best way:
global $db;
$stmt = $db->prepare('SELECT `Value` FROM OverriddenPropertyValues WHERE ParentGUID=?');
$stmt->execute([$itemguid]);
$rows = $stmt->fetchAll();
foreach($rows as $row) {
// $row->Value or $row['Value']
}

Related

How to stop second foreach from looping more than once

I have an query which select all ids from a table. Once I have all id's, they are stored in an array which I foreach over.
Then there is an second array which pull data from url (around 5k rows) and should update DB based on the id's.
The problem - second foreach is looping once for each ID, which is not what I want. What I want is to loop once for all id's.
Here is the code I have so far
$query = " SELECT id, code FROM `countries` WHERE type = 1";
$result = $DB->query($query);
$url = "https://api.gov/v2/data?api_key=xxxxx";
$api_responce = file_get_contents($url);
$api_responce = json_decode($api_responce);
$data_array = $api_responce->data;
$rows = Array();
while($row = $DB->fetch_object($result)) $rows[] = $row;
foreach ($rows as $row) {
foreach ($data_array as $key => $dataArr) {
$query = "UPDATE table SET data_field = $dataArr->value WHERE country_id = $row->id LIMIT 1";
}
}
The query returns 200 id's and because of than the second foreach (foreach ($data_array as $key => $dataArr) { ... }) execute everything 200 times.
It must execute once for all 200 id's not 200 * 5000 times.
Since the question is aboot using a loop, we will talk about the loop, instead of trying to find another way. Actually, I see no reason to find another way.
->Loops and recursions are great, powerful tools. As usually, with great tools, you need to also find ways of controlling them.
See cars for example, they have breaks.
The solution is not to be slow and sit to horses era, but to have good brakes.
->In the same spirit, all you need to master the power called recursions and loops is to stop them properly. You can use if cases and "break" command in PHP.
For example, here we have a case of arrays containing arrays, each first child of the array having the last of the other (1,2,3), (3,4,5) and we want to controll the loop in a way of showing data in a proper way (1,2,3,4,5).
We will use an if case and a counter :
<?php
$array = array( array(-1,0,1), array(1,2,3,4,5), array(5,6,7,8,9,10), array(10,11,12,13,14,15) );
static $key_counter;
foreach( $array as $key ){
$key_counter = 0;
foreach( $key as $key2 ){
if ( $key_counter != 0 ) {
echo $key2 . ', ';
}
$key_counter = $key_counter + 1;
}
}
Since I dont have access to your DB is actually hard for me to run and debbug the code, so the best I can say is that you need to use an if case which checks if the ID of the object is the ID we want to proccess, then proceed to proccessing.
P.S. Static variables are usefull for loops and specially for recurrsions, since they dont get deleted from the memory once the functions execution ends.
The static keyword is also used to declare variables in a function
which keep their value after the function has ended.

I can't get the value of a query outside the loop

I'm using PHP and I do a mysql query and I save the result of this query in an array. Then, I use a loop and into the loop i do another mysql query using the values of the array in the where clause. It's right but if I try to get the result of the query outside the loop I can't.
Here an example code
$result=$mysqli->query("SELECT code FROM referee");
$i=0;
$arcode=array();
while($row=$result->fetch_array()){
$arcode[$i]=$row["code"];
$i++;
}
for($j=0;$j<sizeof($arcode);$j++){
$result2=$mysqli->query("SELECT code, time FROM match where referee_code IN ($arcode[$j])");
}
/*Here I can't get the result values*/
$matcode=array();
$hour=array();
$k=0;
while($row2=$result2->fetch_array()){
$matcode[$k]=$row2["code"];
$hour[$k]=$row2["time"];
}
If I put all in the same loop I get the result repeated (This code is one example of all my code but the idea is the same in the rest).
You are overwriting the result set values into $result2.
The correct method would be something like:
$matcode = array();
$hour = array();
$result2 = $mysqli->query("SELECT code,
time
FROM `match`
WHERE referee_code IN (SELECT code
FROM referee)");
while ($row2 = $result2->fetch_array())
{
$matcode[] = $row2["code"];
$hour[] = $row2["time"];
}
You may change the index values according to the way you want the array to look like.
Also match is a reserved word. So you would have to enclose it in backticks.
If you want to print complete data then try this :
$matcode = array();
$hour = array();
$result2 = $mysqli->query("SELECT code,
time
FROM `match`
WHERE referee_code IN (SELECT code
FROM referee)");
$completeData=array();
while ($row2 = $result2->fetch_array())
{
$completeData[] = $row2;
}
print_r($completeData);
Don forget to accept answer if it helps :)

How do I insert values into an multidimensional-array, then show them?

I'm fairly new to php, and I don't know how to work with arrays very well. Here's the deal, I want to add into a multidimensional array three or more values I obtain from my database, then I want to sort them based on the timestamp (one of the values). After that, I want to show all of the sorted values. I can't seem to do this, here's the code
$queryWaitingPatients = 'SELECT ArrivalTime, TargetTime, Order, Classification FROM exams WHERE (CurrentState = "Pending")';
$results = mysql_query($queryWaitingPatients) or die(mysql_error());
if (mysql_num_rows($results) == 0) {
echo '<p>There\'s currently no patient on the waiting list.</p>';
return;
}
while ($rows = mysql_fetch_array($results)) {
extract($rows);
//now is the part that I don't know, putting the values into an array
}
// I'm also not sure how to sort this according to my $TargetTime
asort($sortedTimes);
//the other part I don't know, showing the values,
Thanks for the help!
Well, let's look at your code. First, you have a query that's returning a result set. I don't recommend using mysql_fetch_array because it's not only deprecated (use mysqli functions instead) but it tends to lend itself to bad code. It's hard to figure out what you're referencing when all your keys are numbers. So I recommend mysqli_fetch_assoc (be sure you're fully switched to the mysqli functions first, like mysql_connect and mysqli_query)
Second, I really dislike using extract. We need to work with the array directly. Here's how we do this
$myarray = array();
while ($rows = mysqlI_fetch_assoc($results)) {
$myarray[] = $rows;
}
echo $myarray[0]['ArrivalTime'];
So let's go over this. First, we're building an array of arrays. So we initialize our overall array. Then we want to push the rows onto this array. That's what $myarray[] does. Finally, the array we're pushing is associative, meaning all the keys of the row match up with the field names of your query.
Now, the sorting really needs to be done in your query. So let's tweak your query
$queryWaitingPatients = 'SELECT ArrivalTime, TargetTime, `Order`, Classification
FROM exams
WHERE CurrentState = "Pending"
ORDER BY TargetTime';
This way, when your PHP runs, your database now churns them out in the correct order for your array. No sorting code needed.
$arr = array();
while ($rows = mysql_fetch_array($results)) {
array_push ($arr, $row);
}
print_r($arr);
<?php
$queryWaitingPatients = ' SELECT ArrivalTime, TargetTime, Order, Classification, CurrentState
FROM exams
WHERE CurrentState = "Pending"
ORDER BY TargetTime ';
$results = mysql_query($queryWaitingPatients) or die(mysql_error());
if ($results -> num_rows < 1)
{
echo '<p>There\'s currently no patient on the waiting list.</p>';
}
else
{
while ($rows = mysqli_fetch_array($results))
{
$arrivaltime = $row['ArrivalTime'];
$targettime = $row['targettime'];
$order = $row['Order'];
$classification = $row['Classification'];
echo "Arrival: ".$arrivaltime."--Target time: ".$targettime."--Order: ".$order."--Classification: ".$classification;
}
}
echo "Done!";
//or you could put it in a json array and pass it to client side.
?>

PHP and MYSQL "while" prints only one value

Hey all i have a mind bug with this wile loop , i am a bit of a noob
$sql_advanced_bio = mysql_query("SELECT * FROM bio_details WHERE mem_id='$id'");
while($row = mysql_fetch_assoc($sql_advanced_bio)){
$bio_time_family = $row["bio_time_family"];
}
So this is the php now in my HTML i have this
*php echo $bio_time_family *
Why dose it echo only one value ?
SIMPLE ANSWER
so i tried somethingh easier like this $bio_fun_family .= $row["bio_fun_family"].",";
and then this
$bio_fun_family = substr($bio_fun_family,0,-1);
I added the .next to the =
It appends the values
You need to store the values in an array, otherwise you're just overwriting one variable each time, so you'll just end up with the last value.
You also need to use a loop to echo out each value in the array.
$sql_advanced_bio = mysql_query("SELECT * FROM bio_details WHERE mem_id='$id'");
$bio_time_family = array();
while($row = mysql_fetch_assoc($sql_advanced_bio)) {
$bio_time_family[] = $row["bio_time_family"];
}
And then for the output;
foreach($bio_time_family as $b) {
echo($b . '<br />');
}
With each iteration of the while loop, you're assigning to $bio_time_family the newly extracted value. If you'd like to make an array of the, instead, use $bio_time_family[] = $row["bio_time_family"];
Because every time you run through the loop you're re-assigning $bio_time_family to the next row's value. Try calling echo directly in your loop or add the row to an array, then loop through that and output the rows

Saving 2 variable's values for later use

I tried to make the title of this most the most descriptive as possible, as I don't know how to do this... I know the best way will be value storage in some form of array.
My question is this, I have this query where I need to pic the tag name and the correspondent id for a later comparison and use ($tag_nome is collected by $_GET):
$resultado2 = mysql_query("SELECT tag.tag_nome, rel_frasetag.id_tag
FROM tag, rel_frasetag
WHERE rel_frasetag.id_tag = tag.id_tag AND
rel_frasetag.id_frase='$id_frase'") or die(mysql_error());
while($res2 = mysql_fetch_array($resultado2))
{
$tag_nome2 = utf8_encode($res2['tag_nome']);
$id_tag = $res2['id_tag'];
}
I already tried some things like array_push() but couldn't get it to work.
At the end of this snippet I'm comparing $tag_nome2 against $tag_nome to see if they match. If so, it will echo one link with the corresponding $tag_nome2 and $id_tag, and if not will echo pretty much the same thing, with a different class on the link.
My best guess as far as what you want to do is the following:
if( $tag_nome2 == $id_tag )
{
// do something
}
else
{
// no match
}
Perhaps though, you're saying your variable names are being overwritten? You're inside of a while loop, so the values they'll ultimately receive will be that of $res2[] at the end of the last iteration of your loop.
And if you're saying you want to save your rows for later, you can do:
$holder = array();
$res = mysql_query("");
while( $row = mysql_fetch_assoc($res) )
{
$holder[] = $row;
}
print_r($holder);

Categories