MySQLi Array in PHP sometimes coming up empty - php

Okay, so I'm pretty much at the end of my rope trying to discover the issue here, because sometimes this code works perfectly, and then sometimes not, so here it is:
$allItems = array();
$allItemsQuery = mysqli_query($conn,"SELECT * FROM cart_items WHERE crt_id='".$row['crt_id']."' AND quantity>0");
while($itemsArray = mysqli_fetch_assoc($allItemsQuery)){
array_push($allItems,$itemsArray['item_id']);
}
$allItemsNames = array();
foreach($allItems as $key => $value){
$itemNames = mysqli_fetch_assoc(mysqli_query($conn,"SELECT * FROM items WHERE id='$value'"));
array_push($allItemsNames, $itemNames['item_name']);
}
$allItemsFinal = array_combine($allItems,$allItemsNames);
$itemsList = 'Items:<br>';
foreach($allItemsFinal as $key => $value){
$itemsList .=''.$value.'<br><br>';
}
The idea is it's supposed to get all of the item ID's the user has in their cart from the DB and put it into an array, which I've established exists, grab all of the item names based on their ID, and put that into an array, and then combine the two arrays as a key and value. Then I output the data from the arrays into a string.
This code works perfectly sometimes, and then suddenly not. Can somebody give me any idea why? I'd be indebted forever.

I think you should throw this code away and use something like this:
$items = array();
$itemsQuery = "SELECT i.item_name, i.item_id
FROM items i WHERE i.item_id
IN (SELECT ci.item_id
FROM cart_items
WHERE crt_id='".$row['crt_id']."'
AND quantity>0
)");
$allItemsQuery = mysqli_query($conn, $itemsQuery);
while ($row = mysqli_fetch_assoc($allItemsQuery))
$items[$row['item_id']] = $items[$row['item_name']];

Related

How to find any common number exists between 2 dynamic values - PHP

From my database my code fetch (dynamic) two values (varChar) from 2 tables and I want to find is there at least one common number between the 2 values. If at least one number is common, my code will fetch rows and display the rows values (while loop).
I am new to php and new to 'stackoverflow'. My code works fine and fetch results as I desired. The problem 1.) will it work rightly all the time? 2.) I feel my code seems to be ugly and it can be refined.
Here my code:
$sql = "SELECT * FROM table1 WHERE userId = '".$_SESSION['userId']."'"; $result = $conn->query($sql); $row = $result->fetch_assoc(); $nearBy = $row['nearBy']; $area_1 = explode(',', $nearBy); //Here, for example I am getting the result - 1,4,5,9,12
and
$sql = "SELECT * FROM table2 ORDER By id";
$result = $conn->query($sql);
while($row = $result->fetch_assoc())
{
$area_2 = explode(',', $row['areas']); // 9,12,24,67
```
foreach ($area_1 as $value1) {
$value1;
foreach ($area_2 as $value2){
$value2;
if($value1 == $value2){
if(!empty($result)){
```
```
$sql10 = "SELECT * FROM table2 ORDER By id";
$result10 = $conn->query($sql10);
while($row10 = $result10->fetch_assoc())
```
`
// Finished, the idea is - I converted the first result (area_1) into an array by explode and I did the same to 'area_2'. Then I looped through both the arrays to find out at least any common number. If the result is not empty then at least one common number is available and the specific row details will be displayed. Like wise all the rows will be displayed one by one.
I again wish to remain the coders that I am very new to php coding. Thanks in advance for your upcoming helps.
My code works fine and fetch results as I desired.
The problem 1.) Will it work rightly all the time?
2.) I feel my code seems to be ugly and it can be refined.

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.

Implode ids within a while loop and add commas between

I'm trying to display some sub-content so I need to get the child id's of their parent.
This is how I wanted to do it:
$ids = "SELECT * FROM `web_categories` WHERE parent_id = 14 AND published = 1";
$idscon = $conn->query($ids);
while ($ids = $idscon->fetch_array()){
$idss .= $ids['id'];
}
$project1 = "SELECT * FROM `web_content` WHERE catid in ('$idss') AND state = 1";
$projectcon1 = $conn->query($project1);
$projectcr1 = array();
while ($projectcr1[] = $projectcon1->fetch_array());
I tried imploding $idss like this:
$implode = implode(',', $idss);
But this gives me Invalid arguments passed. What am I doing wrong?
You are doing wrong in the first while loop.
Here it is, $idss .= $ids['id'];, You are doing wrong this. You are storing value in a variable as string, but when you try to implode this... It throws an error!!! Cause implode() use to make array into string. So follow the below steps.
Change $idss .= $ids['id']; to $idss[] = $ids['id']; and instead of implode() use the join().
Create an array names $idss, and push or insert the ids into that array. Then implode/join that IDs.
$idss = array();
while ($ids = $idscon->fetch_array()){
$idss[] = $ids['id'];
}
$implode = implode(',', $idss);
Now you can use this $implode variable in the next query.
You just need to store all IDs in an array, something like $yourIDs[] = $ids['id']; inside your first while loop.
With $idss .= $ids['id']; you can't use implode() because result of this action should be something like "1234" without any single comma.
You just need to use like that:
<?php
$yourIDs = array();
while ($ids = $idscon->fetch_array()){
$yourIDs[] = $ids['id']; // this will save all IDs into $yourIDs array.
}
$idss = implode(',',$yourIDs); // result of this should be 1,2,3,4 etc.
?>
I think you could most likely do that in one query
SELECT * FROM `web_content` WHERE `catid` in (
SELECT `id` FROM `web_categories` WHERE `parent_id` = 14 AND `published` = 1
) AND `state` = 1
The original code was, in effect, doing exactly this but in two stages - sub-queries can be slow sometimes but it does depend on the size of the db and the number of expected results. It is true that joins can be and generally are more efficient than dependant subqueries so perhaps that is another option to explore. As mysql executes the query plan from the outside to the inside rather than the intuitive inside to outside subqueries can cause the server to crawl - it really depends on the complexity of the subquery and the amount of data that has to be processed.

PHP array not updating

There is probably something dumb I am doing wrong here.
public function get_scores($id)
{
$results = array();
$sql = "SELECT * FROM scores WHERE comp_id = $id";
$rows = $this->db->query($sql)->result();
foreach($rows as $row) {
if($row->confirmed_id) {
$results[$row->uid] += $row->score;
}
}
sort($results);
return $results;
}
So basically what I am trying to do is add all of the users scores in the database and return them in order of rank. confirmed->id is just a check to make sure the score has been confirmed (and thus is addable to their total score). I am basically trying to just make an associative array where the key is the users ID, and the score of each question they have in the database is added on. The query works fine, and $row-uid and $row->score both return the correct thing for every row, but $results[] never has anything added to it. If I even change it just to something silly like $results[3] = 0 at top, and then $results[3]++ or += 1 in the for loop, it doesn't add anything to $results[3].
EDIT: Problem solved. Indeed was something dumb -- confirmed_id was set to null by my partner when he reran our database after I had previously set it all to 1. Thanks guys :)
You are adding to $results[something] before it exists. You need to create it in the first case and then only increment it once it exists.
You need to remove the "+=" operation from the code. Check with this.
public function get_scores($id)
{
$results = array();
$sql = "SELECT * FROM scores WHERE comp_id = $id";
$rows = $this->db->query($sql)->result();
foreach($rows as $row)
if($row->confirmed_id)
$results[$row->uid] = $row->score;
sort($results);
return $results;
}
Your previous operation is similar to
$results[$row->uid] = $results[$row->uid] + $row->score;
So it will not add values to your row.

Working with arrays in Kohana, Blank page?

tl;dr - Pushing an array (by $array[] or $array[$id] is not working in Kohana 3, it gives a blank white page.
I'm using Kohana (3), it's my first experience with MVC and it's been great so far; however, I'm working with a database and encountered a weird problem that I was hoping someone could shed some light on:
My workflow is like this, to give you an idea of my problems surrounding:
$sql = "SELECT table1.row1, max(table2.row1) as `maxAwesome` FROM table1, table2 WHERE table1.id=table2.table1id GROUP BY table1.id";
$table1Results = DB::query(Database::SELECT, $sql)->execute();
$masterArray = array();
foreach ($table1Results as $result1)
{
$sql = "SELECT * FROM table2 WHERE table2id='" . $result1['id'] . "' AND column > 21";
$table2Results = DB::query(Database::SELECT, $sql)->execute();
$subArray = array();
foreach ($table2Results as $result2)
{
$subArray[$result1['id']] = $result2;
// Even had just $subArray[] = array("whatever");
}
$masterArray[] = array("table1Data" => array(), "table2Data"=> $subArray);
}
I do a query where I run a couple max/min functions then do a query within the foreach doing another select to build a master array of data formatted the way I want it and all the SQL etc works fine and dandy; however, the problem arises when I'm pushing the array.
It seems whenever I push the array by doing either $array[] = array("data"); or by specifying the key $array[$id] = array("data"); Kohana gives me a straight blank page, no error, no output etc.
Sometimes I get a Kohana error indicating the key does not exist (duh, I'm creating it) but for the most part the output is straight white.
Why is this happening? Am I going about it wrong?
Thanks in advance.
Clarity edit:
My SQL blunders aside, the issue lies in the building of the secondary array, for example:
$queryStores = "SELECT stores.store_id, stores.title, max(product.discount) as `max_discount`, min(product.discount) as `min_discount`
FROM stores, products
WHERE products.store=stores.store_id
GROUP BY products.store";
$stores = DB::Query(Database::SELECT, $queryStores)->execute();
$formattedStores = array();
if (count($stores))
{
foreach ($stores as $store)
{
$formattedStores[$store['store_id']] = array(
"title" => $store['title'],
);
// Same result if just doing $formattedStores[] = array();
// Problem goes away should I do:
// $formattedStores = array("This works");
//
}
}
echo "<pre>";
print_r($formattedStores);
echo "</pre>";
That does not print an array, it simply gives a blank page; however, if i change it to just re-set the $formattedStores array to something I get an output. What is it about pushing the array that's causing a problem, perhaps a Kohana bug?
Thanks
Your code should be like:-
$sql = "SELECT table1.id, table1.row1, max(table2.row1) as `maxAwesome`
FROM table1, table2
WHERE table1.id = table2.table1id
GROUP BY table1.id";
$table1Results = DB::query(Database::SELECT, $sql)->execute();
$masterArray = array();
if (count($table1Results))
{
foreach ($table1Results as $result1)
{
$sqlInner = "SELECT * FROM table2
WHERE table2id = '" . $result1['id'] . "'
AND column > 21";
$table2Results = DB::query(Database::SELECT, $sqlInner)->execute();
$subArray = array();
if (count($table2Results))
{
foreach ($table2Results as $result2)
{
$subArray[$result1['id']] = $result2;
// Even had just $subArray[] = array("whatever");
}
}
$masterArray[] = array("table1Data" => array(), "table2Data"=> $subArray);
}
}
Some valuable coding standards & miss-ups:-
You have got the "id" field (w.r.t. the "table1" DB table) missing from the first SQL.
The second SQL should be better written using another variable naming, so as to keep it separate from the first one. Hence the second variable is named as "$sqlInner".
It's always better to check for any existence of array elements in an array variable, so I have used the simple checks using the "if" statement.
Hope it helps.
I've determined this to be memory related.

Categories