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 '...';
}
Related
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>";
}
}
?>
I update my code from PHP 5 to PHP 7 and i got problem with foreach loop. I loocked wor answers here, but none is working. Or i dont understand where i have problem
function getStructure($pid = 0, $expand = array(), $alevel = 0)
{
$struct = array();
if ( $alevel > $this->levelCount) $this->levelCount = (int)$alevel;
$str = $this->dbStructure->getStructure($pid);
foreach ($str as &$row)
{
if ($row["type"] == STRUCT_PAGE)
{
$row["editLink"] = "editPage";
$row["target"] = "_self";
}
elseif ($row["type"] == STRUCT_MODULE)
{
$row["editLink"] = "editModule";
$row["target"] = "_self";
}
elseif ($row["type"] == STRUCT_LINK)
{
$row["editLink"] = "editLink";
$row["target"] = "_blank";
}
elseif ($row["type"] == STRUCT_CATALOG)
{
$row["editLink"] = "editCatalog";
$row["target"] = "_self";
}
$row["childrens"] = $this->getStructure((int)$row["id"], $expand, $alevel+1);
if ($row["type"] == STRUCT_CATALOG and isset($row["childrens"][0]["shortcut"]))
{
$row["shortcut"] = $row["childrens"][0]["shortcut"];
$row["target"] = $row["childrens"][0]["type"] == STRUCT_LINK ? "_blank" : "_self";
}
$struct[] = $row;
}
unset($row);
return $struct;
}
All the time $struct is NULL and I need to be multidimensional array
This code by itself is good. Has no problems, only ampersand is not needet. The problem was in different place. Sorry for spam
Here's the thing: I have a foreach loop that adds inputs dynamically. I need it to place part of them in one div, the rest in another. The current code is the following:
$sqla=mysql_fetch_row($sql);
$x=1;
if($x<50)
{
?>
<div class="area area-1">
<?
foreach($sqla as $key=>$values){
if ($key == "0") {
continue;
}
$icheck = ($values > 0) ? "icheck" : "";
$ichecked = ($values > 0) ? "isChecked" : "";
echo "<label class='label-area label-".$values['num".$x."'][$x]." ".$ichecked."'><input name='data[ar][".$x."][]' type='checkbox' value='".$x."' title='".$x."' class='".$icheck." archeck1'><span class='label-num'>".$x."</span><span class='label-check-mark'></span></label>";
if ($key == "50") {
break;
}
$x++;
if ($values > 0) {
$new_rand_arr[] = $values;
}
}
?>
</div>
<?
}else{
?>
<div class="zodiak ar-1">
<?
foreach($sqla as $key=>$values){
if ($key == "50") {
continue;
}
$icheck = ($values > 0) ? "icheck" : "";
$ichecked = ($values > 0) ? "isChecked" : "";
echo "<label class='label-area label-".$values['num".$x."'][$x]." ".$ichecked."'><input name='data[ar][".$x."][]' type='checkbox' value='".$x."' title='".$x."' class='".$icheck." archeck1'><span class='label-num'>".$x."</span><span class='label-check-mark'></span></label>";
if ($key == "62") {
break;
}
$x++;
if ($values > 0) {
$new_rand_arr[] = $values;
}
}
?>
</div>
<?
}
?>
The output puts it all in the first div, but none in the "zodiak ar-1" one. The target thing is everything after the 50-th key to go into that div. Hope that managed to explain the issue...
Thank you
Right now you are doing this:
$x=1;
if($x<50)
{
// your code
} else {
// your code
}
The problem is that you do a foreach INSIDE the if statement, so $x < 50 will ALWAYS be true because just before you do $x = 1.
Now in both foreach loop you do this :
foreach($sqla as $key=>$values){
if ($key == "0") {
continue;
}
// your code
}
foreach($sqla as $key=>$values){
if ($key == "50") {
continue;
}
// your code
}
So you use a var $x that you increment each turn but you have a $key that you use too to check if value is <50 or not?
So try something like this :
$new_rand_arr = array();
$open_first_div = false;
$open_second_div = false;
$html = "";
foreach($sqla as $key=>$values){
if ($key < "50") {
// You open your first div one time
if (!$open_first_div) {
$html .= "<div class=\"area area-1\">";
$open_first_div = true;
}
$icheck = ($values > 0) ? "icheck" : "";
$ichecked = ($values > 0) ? "isChecked" : "";
html .= "<label class='label-area label-".$values['num".$x."'][$x]." ".$ichecked."'><input name='data[ar][".$x."][]' type='checkbox' value='".$x."' title='".$x."' class='".$icheck." archeck1'><span class='label-num'>".$x."</span><span class='label-check-mark'></span></label>";
if ($values > 0) {
$new_rand_arr[] = $values;
}
} else {
// You close your first div and open the second div
if (!$open_second_div) {
$html .= "</div><div class=\"zodiak ar-1\">";
$open_second_div = true;
}
$icheck = ($values > 0) ? "icheck" : "";
$ichecked = ($values > 0) ? "isChecked" : "";
$html .= "<label class='label-area label-".$values['num".$x."'][$x]." ".$ichecked."'><input name='data[ar][".$x."][]' type='checkbox' value='".$x."' title='".$x."' class='".$icheck." archeck1'><span class='label-num'>".$x."</span><span class='label-check-mark'></span></label>";
if ($values > 0) {
$new_rand_arr[] = $values;
}
}
}
// After the foreach your close your div
$html .= "</div>";
// You display it
echo $html;
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
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]);