while loop with if statement not working properly - php

hi i have the following while loop :
while ($row = mysqli_fetch_array($result2)){
$elem_filho = $row['itempt_dim'];
$marcas = "{name: " . "'" . $elem_filho . "'" . ", color: " . "'" . $cor_alea . "'" . ", size: 1";
if (mysqli_num_rows($result2)) {
$dif = "},";
}
else {
$dif = "}]";
}
$vlk = $marcas . $dif;
print_r($vlk);
}
the thing is i had similar code and it worked this way, but the output is alway }, and i want the last item of the query to end with }]
i can't see what i am doing wrong
thanks in advance

With json_encode you code is simplified to:
$vlk = [];
while ($row = mysqli_fetch_array($result2)) {
$vlk[] = [
'name' => $row['itempt_dim'],
'color' => $cor_alea,
'size' => 1,
];
}
print_r(json_encode($vlk));

Related

Generic class for SELECT in mysql leads to endless loop

I began to write a generic class for SELECT queries that looks like this:
class DbQuery
{
private $database;
public function __construct()
{
$db_config = array(
"type" => "mysql",
"host" => "localhost",
"port" => "3306",
"charset" => "utf8",
"db" => "dbname",
"user" => "user",
"password" => "topsecret"
);
$this->database = DatabaseFactory::getFactory()->getConnection($db_config);
}
public function Select($keys = array("*"), $table, $whereClauseArray = null, $orderValues = null, $orderDirection = null, $limitIndex = null, $limitLength = null)
{
$statement = "SELECT " . implode(',', $keys) . " FROM " . $table;
if (!empty($whereClauseArray)) {
$whereClauseString = " WHERE ";
$i = 0;
foreach ($whereClauseArray as $whereClause) {
if ($i > 0) {
$whereClauseString .= " " . $whereClause['link'] . " ";
}
$whereClauseString .= $whereClause['key'] . " " . $whereClause['operand'] . " :" . $whereClause['key'] . "_" . $i;
$i++;
}
$statement .= $whereClauseString;
}
if (!empty($orderValues)) {
$orderClause = " ORDER BY ";
foreach ($orderValues as $order) {
$orderClause .= $order . ", ";
}
$orderClause = substr($orderClause, 0, -2);
$statement .= $orderClause . " " . $orderDirection;
}
if ($limitIndex != null && $limitLength != null) {
$statement .= " LIMIT " . $limitIndex . "," . $limitLength;
}
$query = $this->database->prepare($statement . ";");
$file = $_SERVER["DOCUMENT_ROOT"] . '/../db.log';
$current = file_get_contents($file);
$current .= date("Y-m-d H:i:s", time()) . " => ";
$current .= "Statement: " . $statement . "\n";
file_put_contents($file, $current);
$j = 0;
foreach ($whereClauseArray as $whereClause) {
$keystring = ":" . $whereClause['key'] . "_" . $j;
$bindValue = trim(strip_tags($whereClause['value']));
$query->bindValue($keystring, $bindValue);
$file = $_SERVER["DOCUMENT_ROOT"] . '/../db.log';
$current = file_get_contents($file);
$current .= date("Y-m-d H:i:s", time()) . " => ";
$current .= "BindValue: " . $keystring . " -> " . trim(strip_tags($whereClause['value'])) . "\n";
file_put_contents($file, $current);
$j++;
}
// $query->execute();
if ($keys === "count(*)") {
return $query->fetchColumn(0);
} else {
return $query->fetchAll();
}
}
}
I call the function like that:
$obj_artikel_startseite = new DbQuery();
$obj_artikel_startseite->Select(array("*"), "psartikel", array(array("link" => "AND", "key" => "status", "value" => "freigeschaltet", "operand" => "="), array("link" => "OR", "key" => "status", "value" => "reserviert", "operand" => "=")), array("id"), "DESC", 0, 3)) {
As long as I leave the execution commented, I get a proper output in my db.log file:
2022-10-23 19:35:51 => Statement: SELECT * FROM psartikel WHERE status = :status_0 OR status = :status_1 ORDER BY id DESC
2022-10-23 19:35:51 => BindValue: :status_0 -> freigeschaltet
2022-10-23 19:35:51 => BindValue: :status_1 -> reserviert
But when I try to execute the prepared statement with binded values, it leads to an endless loop. I don´t understand why.
Regards
Edit: Endless loop means the execution limit exceeds and the output in my log is about thousands, indentical entries...

Array_push in for loop giving null response

Hello I am trying to push in an array using array_push but I am getting the value of the first index then after that all I am getting a null response, I am not getting where I have done a mistake.I am getting the values properly but in array_push there is some mistake which is in for loop.
Here is my code :
function actioncouponcsv_download() {
$this->layout = false;
foreach (Yii::app()->log->routes as $route) {
if ($route instanceof CWebLogRoute || $route instanceof CFileLogRoute || $route instanceof YiiDebugToolbarRoute) {
$route->enabled = false;
}
}
$dateRange = json_decode($_POST['dateRange'], true);
$start = $dateRange['start'];
$end = $dateRange['end'];
$validity = $_POST['validity'];
$limit = isset($_REQUEST['limit']) && trim($_REQUEST['limit']) ? $_REQUEST['limit'] : 0;
$studio_id = Yii::app()->user->studio_id;
if (isset($_GET['type']) && intval($_GET['type']) ==2) {
$couponobj = new CouponSubscription();
$getcouponobj = $couponobj->getcoupon_data($studio_id,$start,$end,$validity);
$k = 0;
$title_addon = "\t" . "Discount Cycle" . "\t" . "Extend free trail";
$data_addon = "\t" . $getcouponobj[$k]['discount_multiple_cycle'] . "\t" . $getcouponobj[$k]['extend_free_trail'];
} else {
$title_addon = "";
$data_addon = "";
$couponobj = new Coupon();
$getcouponobj = $couponobj->getcoupon_data($studio_id,$limit,1);
}
//$Coupon = Coupon::model()->find('studio_id=:studio_id', array(':studio_id' => $studio_id));
$dataCsv = '';
if ($getcouponobj) {
$headings = "Sl no" . "\t" . "Coupon" . "\t" . "Coupon Type" . "\t" . "Used by a single user" . "\t" . "Valid" . "\t" . "Used" . "\t" . "User" .$title_addon. "\t" . "Used Date". "\t" . "Content Category". "\t" . "Content"."\n";
$i = 1;
$dataCSV[] = Array();
$j = 0;
for ($k = 0; $k < count($getcouponobj); $k++) {
$userList = '-';
if ($getcouponobj[$k]['used_by'] != '0') {
if ($getcouponobj[$k]['coupon_type'] == 1) {
$userList = '';
$userIdList = explode(",", $getcouponobj[$k]['used_by']);
foreach ($userIdList as $userIdListKey => $userIdListVal) {
if ($userIdListKey == 0) {
$userList .= Yii::app()->webCommon->getuseremail($userIdListVal);
} else {
$userList .= " | " . Yii::app()->webCommon->getuseremail($userIdListVal);
}
}
} else {
$userList = Yii::app()->webCommon->getuseremail($getcouponobj[$k]['used_by']);
}
}
if($getcouponobj[$k]['is_all']!=1){
if($getcouponobj[$k]['content_category']==1){
$cont_cat = "Digital";
$content_str = Coupon::model()->getContentInfo($getcouponobj[$k]['specific_content']);
$cont_str = $content_str;
}else if($getcouponobj[$k]['content_category']==2){
$cont_cat = "Physical";
$content_str = Coupon::model()->getContentInfoPhysical($getcouponobj[$k]['specific_content']);
$cont_str = $content_str;
}else{
$cont_cat = "All";
$cont_str = "All";
}
}else{
$cont_cat = "All";
$cont_str = "All";
}
#echo $getcouponobj[$k]['coupon_code'];
array_push($dataCSV[$j],$i);
array_push($dataCSV[$j],$getcouponobj[$k]['coupon_code']);
array_push($dataCSV[$j],(($getcouponobj[$k]['coupon_type'] == 1) ? 'Multi-use' : 'Once-use'));
array_push($dataCSV[$j],(($getcouponobj[$k]['user_can_use'] == 1) ? 'Multiple times' : 'Once'));
array_push($dataCSV[$j],(($getcouponobj[$k]['used_by'] == 0) ? 'Yes' : 'No'));
array_push($dataCSV[$j],(($getcouponobj[$k]['used_by'] == 0) ? '-' : 'Yes'));
array_push($dataCSV[$j],$userList);
array_push($dataCSV[$j],$getcouponobj[$k]['discount_multiple_cycle']);
array_push($dataCSV[$j],$getcouponobj[$k]['extend_free_trail']);
array_push($dataCSV[$j],(($getcouponobj[$k]['cused_date'] == 0) ? '-' : $getcouponobj[$k]['cused_date']));
array_push($dataCSV[$j],$cont_cat);
array_push($dataCSV[$j],$cont_str);
$j++;
//$dataCsv .= $i . "\t" . $getcouponobj[$k]['coupon_code'] . "\t" . (($getcouponobj[$k]['coupon_type'] == 1) ? 'Multi-use' : 'Once-use') . "\t" . (($getcouponobj[$k]['user_can_use'] == 1) ? 'Multiple times' : 'Once') . "\t" . (($getcouponobj[$k]['used_by'] == 0) ? 'Yes' : 'No') . "\t" . (($getcouponobj[$k]['used_by'] == 0) ? '-' : 'Yes') . "\t" . $userList .$data_addon. "\t" . (($getcouponobj[$k]['cused_date'] == 0) ? '-' : $getcouponobj[$k]['cused_date'])."\t" .$cont_cat ."\t".$cont_str."\n";
$i = $i+1;
}
}
print_r(json_encode($dataCSV));
}
PS: I am getting the values. Any help will be highly appreciated.
Well, first thing i see wrong is the way you declare your array:
$dataCSV[] = Array();
$array[] = Means that you are adding a new value to an existing array. To declare your array you should use
$dataCSV = array();
Also, this code:
array_push($dataCSV[$j],$i);
means that you are adding a new value to your $dataCSV[$j] array, but this is never declared as an array, so first thing would be to do
$dataCSV[$j] = new array();
Your code is really long and complicated, those are only examples of issues i see in there.

php array , how to display array data in email

$qua1 = "5";
$queryNotification= "SELECT * from stock where stockQty <= :qua1 ";
$stmt3 = $conn->prepare($queryNotification);
$stmt3->bindParam(':qua1',$qua1);
$stmt3->execute();
while ($queryNotRow = $stmt3->fetch()){
$a=array("Qty"=>$queryNotRow['stockQty'],"name "=>$queryNotRow['stockName'],"cb "=>$queryNotRow['stockPrice']);
// $array[$queryNotRow['stockQty']] = $queryNotRow['stockName'];
foreach( $a as $row ):
$b = "stockqty = " . $queryNotRow['stockQty'] . " and StockName = " . $queryNotRow['stockName'] . "<br>";
endforeach;
echo $b;
}
If I add send email code inside the foreach loop , the system will send many email according on how many data. How can I only send all the data by ONE EMAIL??
$a=array("Qty"=>$queryNotRow['stockQty'],"name "=>$queryNotRow['stockName']);
foreach($a as $key=>$data){
echo 'stock'.$key.'='.$data.'<br/>';
}
foreach( $a as $row ):
echo "stockqty = " . $row['Qty'] . " and StockName = " . $row['name'] . "<br>";
endforeach;
try this,
$a[] = array(
"Qty" => 1,
"name " => 2
);
foreach ($a as $row) {
echo $row['Qty']."===".$row['name'];
}

var_export prettifier / visualizer

I'm using var_export to dump output to logs when errors occur. However since the result is in pure text, I don't get a chance to push it through some sort of library like krumo so I can interactively explores the output.
What methods do people have to deal with making var_export text more readable?
Here is my function, it works well for multidimensional arrays:
function VE($varname, $varval, $short_syntax=true, $tag = ' ', $comma='', $end_line="\r\n") {
$res = '';
if($short_syntax){
$begin_array = '[';
$end_array = ']';
} else {
$begin_array = 'array(';
$end_array = ')';
}
$arr = explode('/',$varname);
$dim =count($arr)-1;
$lastKey = end($arr);
if (! is_array($varval)){
if( is_string($varval)) $varval = "'$varval'";
$res .= str_repeat($tag,$dim) . $lastKey . ' => ' . $varval . $comma . $end_line;
}else{
$res .= str_repeat($tag,$dim) . $lastKey . ' => ' . $begin_array . $end_line;
$count_varval = 0;
$dim_varval = count($varval);
foreach ($varval as $key => $val){
$count_varval++;
if($count_varval<$dim_varval) $commma=','; else $commma='';
if( is_string($key)) $key = "'$key'";
$res .= VE ($varname . "/" . $key , $val, $short_syntax, $tag, $commma);
}
$res .= str_repeat($tag,$dim) . $end_array . $comma . $end_line;
}
return $res;
}
$bigarray = array(); // your array
$bb = VE ('$bigarray', $bigarray);
echo "<pre>$bb</pre>";
I hope it helps ;)

Multidimensional Array filled from textfile

i would like to import a txt-file with datas for a project. The file have different sections.
$file = fopen( $filename, "r" );
$object = array();
while( !feof( $file ) )
{
$line = fgets($file);
$items = explode( ";", $line );
//Import the global values
if( count($items) == 1 )
{
$arraySection = str_replace("#", "",trim($items[0]) );
}
else if ( count($items) == 3 )
{
$object[$arraySection][$items[0]] = $items[1];
}
else if ( count($items) == 4 )
{
//$object[$arraySection][] = array("gewerknummer" => $items[1], "gewerkbezeichnung" => $items[2]);
}
//Import the articel
else if ( count($items) > 4 )
{
if( $items[0] == "Artikel-Nr" )
{
$articelrow = $items;
}
else
{
$articeldetails = array();
for($i = 0; $i < count($items)-1; $i++)
{
$articeldetails[] = array($articelrow[$i]=>$items[$i]);
}
$object["artikel"] = array(
$articeldetails
);
}
}
}
//Start of import the array to the database
$arrValue = array();
for($i = 0; $i < count($object['artikel']); $i++)
{
$tArray = array();
$tArray[] = $object['Objekt']['Objektnr'];
$tArray[] = $object['SuAdresse']['SUNr'];
$tArray[] = $object['artikel'][$i][0]['Artikel-Nr'];
$tArray[] = "'" . $object['artikel'][$i][1]['Artikel']. "'";
$tArray[] = "'" . $object['artikel'][$i][2]['Beschreibung'] . "'";
$tArray[] = "'" . $object['artikel'][$i][3]['Einheit'] . "'";
$tArray[] = "'" . str_replace(",", ".", $object['artikel'][$i][4]['Preis-Pro-Einheit']) . "'";
$tArray[] = $object['artikel'][$i][5]['AnzahlParameter'];
$tArray[] = "'" . $object['artikel'][$i][6]['P1_Einheit'] . "'";
$tArray[] = "'" . $object['artikel'][$i][7]['P2_Einheit'] . "'";
$tArray[] = "'" . $object['artikel'][$i][8]['P3_Einheit'] . "'";
$tArray[] = "'" . $object['artikel'][$i][9]['MBS Artikel'] . "'";
$tArray[] = $object['artikel'][$i][10]['Status'];
$tArray[] = $object['artikel'][$i][11]['SuArtikel'];
$tArray[] = $object['artikel'][$i][12]['SuGewerke'];
$tArray[] = "'" . $object['artikel'][$i][13]['PreisStatus'] . "'";
if ( empty( $object['artikel'][$i][14]['ZulageMindermengenArtikelNr'] ) )
$tArray[] = 0;
else
$tArray[] = 0 . $object['artikel'][$i][14]['ZulageMindermengenArtikelNr'];
$arrValue[] = "(" . implode(",", $tArray) . ")";
}
$query = "INSERT INTO objekt_artikel
(
id_objekt,
id_subunternehmer,
artikelnummer,
artikel,
beschreibung,
einheit,
preis_pro_einheit,
anzahl_parameter,
p1_einheit,
p2_einheit,
p3_einheit,
mbs_artikel,
status,
su_artikel,
su_gewerk,
preis_status,
zulage_mindermengen_artikel_nummer
)
VALUES " . implode(",", $arrValue);
But the articels are not added right to the multi-array, because the loop for the query creates only one insert, but when i make a var_dump of of the $object, there looks that the values all be inserted to the array.
I think i have a logic error with filling the array and reading it out.
echo count($object['artikel']) . "\n";die();
This give me the result, that only one Element in the array, but normaly it have to be over 800.
The Element in the array is the last one from the hole Articel list.
Change:
$object["artikel"] = array(
$articeldetails
);
to:
$object["artikel"][] = $articeldetails;
You're not adding to $object['artikel'] each time, you're overwriting it.
You are replacing the same variable each time you go in the while loop...
$object['artikel'] = array($articeldetails);
With this affectation, the array $object has the same cell ('artikel') replaced everytime...

Categories