Variable variables counted php - php

I know the title isn't that good, BUT I really don't know how to describe it in one setence and I need help.
Currently I have this type of disastrous code that count every $type of product there is in the DB (I have 20-30 types, not 2 only):
$cong = 0;
$refr = 0;
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$arr[] = $row;
if ($arr[$t]['product_type'] == 'Congélateur') {
$cong += 1;
}
if ($arr[$t]['product_type'] == 'Réfrigérateur') {
$refr += 1;
}
$t++;
}
}
And I do stuff with it after. But I was disgusted to see that code, so I tried to minimize it, but I can't figure it out, I tried that:
<php?
$t = 0;
$type = array(
"cong" => "Congélateur",
"refr" => "Réfrigérateur",
);
extract($type, EXTR_PREFIX_SAME, "");
if (mysqli_num_rows($result) > 0) {
foreach ($type as $type_n => $type_m) {
$$type_n = 1;
while ($row = mysqli_fetch_assoc($result)) {
$arr[] = $row;
foreach ($type as $type_n2 => $type_m2) {
if ($arr[$t]['product_type'] == $type_m2) {
$$type_n++;
}
}
$t++;
}
echo $type_n . "=" . $$type_n . "<br>";
}
}
?>
Output:
cong=9
refr=1
What we should expect regarding the DB (In the database, there's 2 cong and 6 refr):
cong=2
refr=6
Any sugestion? Thank you!

You're really making this more complicated than it needs to be. Variable variables are almost never the solution and can always be replaced with an array.
The code you're working with makes no sense, why is it assigning $row to another array and then using a counter to access it? The answer you accepted includes 4 loops, one of them nested.
if (mysqli_num_rows($result) === 0) {
// always exit early rather than indent yourself to death
return false;
}
while ($row = mysqli_fetch_assoc($result)) {
$type = $row["product_type"];
$counts[$type] = ($counts[$type] ?? 0) + 1;
}
print_r($counts);
Demo: https://3v4l.org/8cuis#focus=7.3.28

Counters (which count the type names in your example) should be initialised to 0 not to 1.
You also need to increment $$type_n2 in DB read loop. I'd avoid variable variables if possible.
<php?
$t = 0;
$type = array(
"cong" => "Congélateur",
"refr" => "Réfrigérateur",
);
extract($type, EXTR_PREFIX_SAME, "");
if (mysqli_num_rows($result) > 0) {
foreach ($type as $type_n => $type_m) {
$$type_n = 0;
}
while ($row = mysqli_fetch_assoc($result)) {
$arr[] = $row;
foreach ($type as $type_n2 => $type_m2) {
if ($arr[$t]['product_type'] == $type_m2) {
$$type_n2++; // not $$type_n
}
}
$t++;
}
foreach ($type as $type_n => $type_m) {
echo $type_n . "=" . $$type_n . "<br>";
}
}
?>

Related

MySQLi why am I only getting 1 result?

There are three "BC" in the result_category but I am only getting 1 result. This is for a personality quiz. Please Help. I also tried $query = "SELECT result FROM quiz_map where result_category = 'BC'"; but still, only 1 result is showing.
$result = mysqli_query($link, $query);
$cat_a = $cat_b = $cat_c = $cat_d = $cat_e = 0;
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
$cat = $row['category'];
if ($cat == "A") {
$cat_a += 1;
} elseif ($cat == "B") {
$cat_b += 1;
} elseif ($cat == "C") {
$cat_c += 1;
} elseif ($cat == "D") {
$cat_d += 1;
} elseif ($cat == "E") {
$cat_e += 1;
}
}
$array = array('A' => $cat_a, 'B' => $cat_b, 'C' => $cat_c, 'D' => $cat_d, 'E' => $cat_e);
$str = '';
foreach ($array as $i => $value) {
if ($value >= 6) {
$str = $i;
break;
} elseif ($value >= 2) {
$str .= $i;
}
}
$var = sort($array);
$query = "SELECT result FROM quiz_map where result_category = '$str' LIMIT 1";
$result = mysqli_query($link, $query);
$row = mysqli_fetch_array($result);
echo $row[0];
?>
There's many things wrong with your code!
As pointed by #IsThisJavascript and #Cashbee:
You are executing a query with a LIMIT 1 statement, it will only return one record.
As pointed by myself:
Doing echo $row[0] will have the same result, if you are only echoing the first value of the array you can't expect to have multiples can you?
As pointed by #IsThisJavascript:
You need to loop the results array, like so:
while($row = mysqli_fetch_array($result)){
echo $row['result_category'];
}
Consider switching the query from a '=' to a '%like%' statement, to maximize results if you want to get the values that partionaly cointain the string.

Display data from variables with condition

I've a question for you if you can help me, I've some variables that I retrieve with them data from database, but I want to resolve this problem
if all the variables are empty then show something if not then show the just the variables that have data.
The Code is:
foreach ($row as $result) {
if ($row[29] == '') {
$string29 = '';
}else if ($row[29] == 0){
$string29 = '';
} else{
$string29 = '<div class="add_img"><h1>Pression</h1><img src="images/'.$row[29].'.png"></div>';
}
}
foreach ($row as $result) {
if ($row[30] == '') {
$string30 = '';
}else if($row[30] == 0){
$string30 = '';
} else{
$string30 = '<div class="add_img"><h1>Fixation</h1><img src="images/'.$row[30].'.png"></div>';
}
}
`
Then I have
echo &string29 and so on........
Your code is rather redundant. By PHP typecasting rules, 0 and '' are actually loosely equal:
php > var_dump(0 == '');
bool(true)
What you should be doing is have an array of keys/names you could loop over, e.g:
$fields = array(29 => 'Pression', 30 => 'Fixation');
foreach ($fields as $key => $field) {
if ($row[$key]) { .... }
echo '...';
}

getting the even index of a string

hey guys im trying to get the even indexes of a string from the db then save them in a variable then echo. but my codes seems doesnt work. please help. here it is
require_once('DBconnect.php');
$school_id = '1';
$section_id = '39';
$select_pk = "SELECT * FROM section
WHERE school_id = '$school_id'
AND section_id = '$section_id'";
$query = mysql_query($select_pk) or die (mysql_error());
while ($row = mysql_fetch_assoc($query)) {
$public_key = $row['public_key'];
}
if ($public_key) {
$leng_public_key = strlen($public_key);
$priv_key_extract = "";
$array_pki = array();
for ($i=0; $i <=$leng_public_key-1 ; $i++) {
array_push($array_pki,$public_key[$i]);
}
foreach ($array_pki as $key => $value) {
if($key % 2 == 0) {
$priv_key_extract += $public_key[$key];
} else {
$priv_key_extract ="haiiizzz";
}
}
}
echo $priv_key_extract;
as you can see im trying to use modulo 2 to see if the index is even.
I have updated your code as below, it will work now :
<?php
$public_key = 'A0L8V1I5N9';
if ($public_key) {
$leng_public_key = strlen($public_key);
$priv_key_extract = "";
$array_pki = array();
for ($i=0; $i <=$leng_public_key-1 ; $i++) {
array_push($array_pki,$public_key[$i]);
}
foreach ($array_pki as $key => $value) {
//Changed condition below $key % 2 ==0 => replaced with $key % 2 == 1
if($key % 2 == 1) {
// Changed concatenation operator , += replaced with .=
$priv_key_extract .= $public_key[$key];
} /*else {
//Commented this as it is getting overwritten
$priv_key_extract ="haiiizzz";
}*/
}
}
echo $priv_key_extract;
?>
Try this function
function extractKey($key) {
if (empty($key) || !is_string($key)) return '';
$pkey = '';
for ($i=0;$i<strlen($key);$i++) {
if ($i % 2 == 0) {
$pkey .= $key[$i];
}
}
return $pkey;
}
echo extractKey('12345678'); # => 1357

removing item from result query in codeigniter

I can't remove an item from query result array in php + codeigniter.
This is my code
if($query->num_rows > 0)
{
$rows = $query->result();
foreach ($rows as $key => $row)
{
$i = 0;
$fornecedor = $row->fornecedor;
$marca = $row->marca;
$modelo = $row->modelo;
$versao = $row->versao;
$preco = $row->preco;
foreach ($rows as $row2)
{
$fornecedor2 = $row2->fornecedor;
$marca2 = $row2->marca;
$modelo2 = $row2->modelo;
$versao2 = $row2->versao;
$preco2 = $row2->preco;
if(($fornecedor == $fornecedor2) && ($marca == $marca2) && ($modelo == $modelo2) && ($versao == $versao2) && ($preco == $preco2))
{
$i++;
}
}
if($i > 3)
{
unset($row[$key]);
}
}
return $query;
}
I already checked some examples here in stackoverflow but i cant make this work.
I can't see the problem ty
so $row is a $rows[$key], maybe i don't understand something, but it's seems to me you have to write unset($rows[$key]);

static marker from a mysql array

I have a little problem I can't figure out how to solve.
I have an SQL result with 3 rows and I want to put the id from each row into a static marker ie.
MARKER_1 = 4
MARKER_2 = 5
MARKER_3 = 6
How can I do that so I get my static markers but with dynamic values?
I can't do it with a normal
while($row = mysql_fetch_array($result)) {
}
$i = 1;
while($row = mysql_fetch_array($result)) {
if($i == 1) {
$marker_1 = $row;
} elseif($i == 2) {
$marker_2 = $row;
} elseif($i == 3) {
$marker_3 = $row;
}
$i++;
}
i would recommend using an array like this
$results = array();
while($row = mysql_fetch_array($result)) {
$results[] = $row;
}
and then access it via:
$results[0] // or $results[1] and so on. you can even loop that :)
hope that helps
Hope this helps
while($row = mysql_fetch_array($result)) {
echo "MARKER_".$row['id'];
echo"=". $row['value'];
}

Categories