Loop from array not executed - php

I am working on an android app that should create some records on a MySQL database.
This is the PHP file that receives the POST values from the app.
As you may see, there are three arrays that collect specific POST.
The first and second loops are working fine and executing the related guardar_post_media() function.
But the third loop is not executed and there are real values on the variables inside the third array.
May be there is something wrong that I canĀ“t detect, may be you can.
<?php
require_once '../mis_php_functions/funciones_basicas.php';
if($_SERVER['REQUEST_METHOD']=='POST'){
$val39 = $_POST['val39'];
$val40 = $_POST['val40'];
$val46 = $_POST['val46'];
$val48 = $_POST['val48'];
$val50 = $_POST['val50'];
$val52 = $_POST['val52'];
$val54 = $_POST['val54'];
$val56 = $_POST['val56'];
$val58 = $_POST['val58'];
$val60 = $_POST['val60'];
$val62 = $_POST['val62'];
$val64 = $_POST['val64'];
$val65 = $_POST['val65'];
$val67 = $_POST['val67'];
$val69 = $_POST['val69'];
$val71 = $_POST['val71'];
$val73 = $_POST['val73'];
$val75 = $_POST['val75'];
$val77 = $_POST['val77'];
$val79 = $_POST['val79'];
$val81 = $_POST['val81'];
$val82 = $_POST['val82'];
$val83 = $_POST['val83'];
$val84 = $_POST['val84'];
$val85 = $_POST['val85'];
$val86 = $_POST['val86'];
$val87 = $_POST['val87'];
$val88 = $_POST['val88'];
$val89 = $_POST['val89'];
$val100 = $_POST['val100'];
$val101 = $_POST['val101'];
$val102 = $_POST['val102'];
$val103 = $_POST['val103'];
$val104 = $_POST['val104'];
$status = 1;
$post = guardar_post($val40,$val39,$val100,$val102,$status,$val103);
if ($post != false) {
$fotos = array($val48,$val50,$val52,$val54,$val56,$val58,$val60,$val62,$val64);
$arrayLength = count($fotos);
echo "Numero de fotos ".$arrayLength;
$i = 0;
while ($i < $arrayLength)
{
if ($fotos[$i] == 0){
}
else{
guardar_post_media(1,$fotos[$i],$val102,$val100,$post);
}
echo "<br />".$fotos[$i] ."<br />";
$i++;
}
$videos = array($val67,$val69,$val71,$val73,$val75,$val77,$val79,$val81,$val83);
$arrayLength2 = count($videos);
echo "Numero de videos ".$arrayLength2;
$i = 0;
while ($i < $arrayLength2)
{
if ($videos[$i] == 0){
}
else{
guardar_post_media(2,$videos[$i],$val102,$val100,$post);
}
echo "<br />".$videos[$i] ."<br />";
$i++;
}
$youtube = array($val85,$val86,$val87,$val88,$val89);
$arrayLength3 = count($youtube);
echo "Numero de youtube ".$arrayLength3;
$i = 0;
while ($i < $arrayLength3)
{
if ($youtube[$i] == 0){
}
else{
guardar_post_media(3,$youtube[$i],$val102,$val100,$post);
}
echo "<br />".$youtube[$i] ."<br />";
$i++;
}
sendMessageNuevoPost($val39,$val102,$val103,$val104); // envio de push
}
else{
echo 'error';
}
}
?>

You have:
if ($youtube[$i] == 0){
}
else {
}
But POST vars are all strings. Change to:
if ($youtube[$i] == "0"){
}
else {
}
In otherwords, an equality on a string to numerical 0 will be true in your cases. And thus your else never executes.
*** Edit. PROOF
$test1 = "filename.dat";
$test2 = "2939";
$test3 = "some useful data";
$test4 = "0";
if ($test1 == 0) {
// Dont do anything
}
else {
echo "Do Work 1.";
}
if ($test2 == 0) {
// Dont do anything
}
else {
echo "Do Work 2.";
}
if ($test3 == 0) {
// Dont do anything
}
else {
echo "Do Work 3.";
}
if ($test4 == 0) {
// Dont do anything
}
else {
echo "Do Work 4.";
}
Only echoes out Do Work 2.. All other echo()s are not run because the equality of a string to a number 0 will return true except in those cases where the string also is numerical, and then the interpreter will compare the numerical values.
As how this relates to the OP's question: It can be inferred that the OP's POST vars must contain some non-numerical data because the OP insists that the 3rd array is populated:
But the third loop is not executed and there are real values on the variables inside the third array.
I will add likely the loop is executed, but not giving the expected the results due the reasons so mentioned.
Tested on PHP 5 and 7.

Related

Adwords Exported CSV Report Parsing in PHP not working

I have created a table which I am trying to populate with data from a CSV file exported from AdWords. Following is my table -
The table is only displayed when ajax call is successful because the table HTML is returned by the page I make ajax request to. As you can see I'm getting the table columns and the table is being populated properly but I'm not getting the values for some reason.
GENERATING TABLE WITH VALUES FROM FUNCTION
$campaigns_data = getCampaignsCSVData($account_name);
$campaigns_columns = $campaigns_data['columns'];
$campaigns_values = $campaigns_data['values'];
if(!empty($campaigns_columns) && !empty($campaigns_values)){
echo '<h4>Campaign Totals</h4>'.PHP_EOL;
getCampaignsTable($campaigns_columns,$campaigns_values,$campaigns_included_cols,'Clicks','DESC');
}
FUNCTION TO GENERATE CAMPAIGNS TABLE
function getCampaignsTable($columns,$values,$included_cols,$sort_by='',$sort_dir='ASC'){
$values_by_column_key = array();
foreach($values as $key=>$row){
$processed_cols = array();
foreach($row as $key=>$col){
if(is_numeric(str_replace(',','',$col))){
$col = str_replace(',','',$col);
}
if($col[0] == '$'){
$processed_cols[$columns[$key]] = str_replace('$','',$col);
}else{
$processed_cols[$columns[$key]] = $col;
}
}
$values_by_column_key[] = $processed_cols;
}
if(!empty($sort_by)){
usort($values_by_column_key, function($a,$b)use($sort_by,$sort_dir){
if($sort_dir == 'ASC'){
return $a[$sort_by] > $b[$sort_by];
}elseif($sort_dir == 'DESC'){
return $a[$sort_by] < $b[$sort_by];
}
});
}
echo '<table class="data-table">'.PHP_EOL;
echo '<thead>'.PHP_EOL;
echo '<tr>'.PHP_EOL;
if(!empty($included_cols)){
foreach($included_cols as $col){
echo '<th>'.$col['label'].'</th>'.PHP_EOL;
}
}
echo '</tr>'.PHP_EOL;
echo '</thead>'.PHP_EOL;
echo '<tbody>'.PHP_EOL;
$row_count = 0;
foreach($values_by_column_key as $key1=>$row){
$row_count++;
if($row_count <= RESULT_LIMIT){
echo '<tr>'.PHP_EOL;
foreach($included_cols as $key2=>$inc_cols){
if($inc_cols['format'] == 'currency'){
echo '<td>'.$inc_cols['currency_symbol'].$row[$key2].'</td>'.PHP_EOL;
}else{
echo '<td>'.$row[$key2].'</td>'.PHP_EOL;
}
}
echo '</tr>'.PHP_EOL;
}
}
echo '</tbody>'.PHP_EOL;
echo '</table>'.PHP_EOL;
}
FUNCTION TO READ AND PARSE CSV FILE
function getCampaignsCSVData($account){
$data = array();
$dir = ADWORDS_REPORTS_DIR.$account.'/';
$filename = ADWORDS_CAMPAIGN_FILE;
$filepath = $dir.$filename;
$row_count = 0;
if(file_exists($filepath)){
$csvfile = #fopen($filepath,'r');
if($csvfile){
while(!feof($csvfile)){
$row = fgets($csvfile);
$row = preg_replace("/[^a-zA-Z ]/", "", $row);
$row_count++;
$row_data = '';
if(stristr($row,CAMPAIGNS_REPORT_IN_COLUMNS_WORD)){
$row_data = str_replace('Impr.','Impressions',$row);
$row_data = str_replace('Interactions','Clicks',$row_data);
$data['columns'] = str_getcsv($row_data);
$columns_row_index = $row_count;
} elseif($row_count > $columns_row_index && !empty($columns_row_index)){
$row_data = $row;
if(!stristr($row,'Total') && !empty($row)){
$data['values'][] = str_getcsv($row_data);
}
}
}
}
fclose($csvfile);
}else{
$data = false;
}
return $data;
}
This code has been working for a long time but it suddenly stopped working recently without changing anything. I can't seem to get my head around it because I can't find any error. Please help. Thanks!

sum all value keep same id

My problem is I have some value using explode, so if I want display value in database using explode, I must use foreach. The problem is I don't want all showing up, because I want sum all the value to keep same id.
$customer_sql_query = "SELECT * FROM winner_delivery ";
$customer_sql_result = mysqli_query($connection,$customer_sql_query);
while ($customer = mysqli_fetch_array($customer_sql_result)){
$ecommercelist = "";
$snacklist = "";
if ($customer['ecommercelist'] != "") {
$ecommercelist = $customer['ecommercelist'];
}
else if ($customer['status'] == "delivered") {
$snacklist = $customer['deliverysnacklist'];
}
else {
$snacklist = $customer['usersnacklist'];
}
if ($ecommercelist){
$ecommercelist_array = explode('~',$ecommercelist);
$i = 0;
foreach ($ecommercelist_array as $ecommercelist_row) {
if ($i % 2 == "1"){
$alternatecolor = "#EEEEEE";
}
else {
$alternatecolor = "#FFFFFF";
}
$selection_array = explode('|',$ecommercelist_row);
$selection_entry = $selection_array[0];
$temp_qty = $selection_array[1];
$temp_producttitle = $product_ob[$selection_entry]['producttitle'];
$temp_imageurl = $product_ob[$selection_entry]['imageurl'];
$temp_weighttitle = $product_ob[$selection_entry]['weighttitle'];
$temp_productid = $product_ob[$selection_entry]['productid'];
$count=$count_qty[$selection_entry] += $temp_qty;
$i++;
?>
<li>
<div class="picture"><?=$temp_productid ?></div>
<div class="weighttitle" nowrap>x<?=$count ?></div>
</li>
<?
}
}
}
Actually I have many time adjust to make better, but is the result!
btw this my database for ecommerlist

Simple Search Engine Only Works With One SQL Row

I'm making a rather simple search engine with PHP and I've ran into a problem... The engine will only work for one SQL row. In the table the PHP is connected to, there are two rows. One named "The Painful Truth" and the other "Darkness Rising". If you type "darkness" or "rising" into the search bar it will come back with "Darkness Rising" as expected. However, if you input "the", "painful", or "truth" into the bar it will come back with zero results.(P.S. "The Painful Truth" is the first entry in the table) I attempted to debug it by listing out the song names in the table, the search, and the array after exploding the song names. They all line up like they should work, but alas, they don't.
The code below takes the input and removes characters and spaces
$lower = strtolower($_POST["text"]);
$characterRemover = preg_replace('/[^ \w]+/', '', $lower);
$search = str_replace(' ' , '' , $characterRemover);
echo "<strong>". $search . "</strong><br>";
The code below takes data from the database, explodes the string and tries to find a match.
while($row = $result->fetch_assoc()) {
$Slower = strtolower($row["song_name"]);
echo "Song Name: " . $Slower . "<br>";
$song_name = explode(" " , $Slower);
// list array
$arrlength = count($song_name);
for($x = 0; $x < $arrlength; $x++) {
echo $song_name[$x];
echo "<br>";
}
if (in_array($search, $song_name) !== false) {
$song_result = $row["song_name"];
} else {
$song_result = "0 results buddy";
}
}
here's how it looks when I search for "the":
What's happening here is that the loop is running for every single row and the variable $song_result is being overwritten. Try to use a flag $found to get the song.
$found = false;
while(!$found && ($row = $result->fetch_assoc())) {
$Slower = strtolower($row["song_name"]);
echo "Song Name: " . $Slower . "<br>";
$song_name = explode(" " , $Slower);
// list array
$arrlength = count($song_name);
for($x = 0; $x < $arrlength; $x++) {
echo $song_name[$x];
echo "<br>";
}
if (in_array($search, $song_name) !== false) {
$song_result = $row["song_name"];
$found = true;
} else {
$song_result = "0 results buddy";
}
}
If you want to capture every song, then use an array or concatenate a string:
$songs = [];
while($row = $result->fetch_assoc()) {
$Slower = strtolower($row["song_name"]);
echo "Song Name: " . $Slower . "<br>";
$song_name = explode(" " , $Slower);
// list array
$arrlength = count($song_name);
for($x = 0; $x < $arrlength; $x++) {
echo $song_name[$x];
echo "<br>";
}
if (in_array($search, $song_name) !== false) {
$songs[] = $row["song_name"];
}
}
if (count($songs)) {
$song_result = implode('<br>', $songs);
} else {
$song_result = "0 results buddy";
}
Note: You should follow JimL's suggestion and request the info filtering the DB query via the WHERE clause. And then just show the result of the query. ;)
<?php
//Kindly make sure you have create a connection and select a db. this is a sample code to search from mysql db using data supplied
$msg=$_POST['search'];
if(isset($msg)){
$search=explode(' ',$msg);
$len=count($search);
$query="select * from news where ";
for($m=0;$m<$len;$m++){
$query.=" post like '%{$search[$m]}%' || ";
}
$query.=" post like '%{$msg}%' order by upload_date desc";
if($get=mysqli_query($connect,$query)){
$contentSearch=array();
$i=0;
while($row=mysqli_fetch_assoc($get)){
contentSearch[$i]=$row;
$i++;
}
echo"List of Search Items<br>";
print_r($contentSearch);
}
}

PHP, listing things twice

I'm using this script to list a few Twitch.tv streams and their status (offline or online).
If there are no online streams found, I want it to display a text saying that all are offline.
Code that checks if the added streams are online:
//get's member names from stream url's and checks for online members
$channels = array();
for ($i = 0; $i < count($members); $i++) {
if (isset($json_array[$i])){
$title = $json_array[$i]['channel']['channel_url'];
$array = explode('/', $title);
$member = end($array);
$viewer = $json_array[$i] ['stream_count'];
onlinecheck($member, $viewer);
$checkedOnline[] = signin($member);
}
}
unset($value);
unset($i);
//checks if player streams are online
function onlinecheck($online, $viewers)
{
//If the variable online is not equal to null, there is a good change this person is currently streaming
if ($online != null)
{
echo ' <strong>'.$online.'</strong>';
echo '&nbsp <img src="/images/online.png"><strong> Status:</strong> Online! </br>';
echo '<img src="/images/viewers.png"><strong>Viewers:</strong> &nbsp' .$viewers.'</br>';
}
}
Full code:
<html>
<head>
<title>Streamlist</title>
</head>
<body>
<?php
$members = array("ncl_tv");
$userGrab = "http://api.justin.tv/api/stream/list.json?channel=";
$checkedOnline = array ();
foreach($members as $i =>$value){
$userGrab .= ",";
$userGrab .= $value;
}
unset($value);
$json_file = file_get_contents($userGrab, 0, null, null);
$json_array = json_decode($json_file, true);
$channels = array();
for ($i = 0; $i < count($members); $i++) {
if (isset($json_array[$i])){
$title = $json_array[$i]['channel']['channel_url'];
$array = explode('/', $title);
$member = end($array);
$viewer = $json_array[$i] ['stream_count'];
onlinecheck($member, $viewer);
$checkedOnline[] = signin($member);
}
}
unset($value);
unset($i);
function onlinecheck($online, $viewers) {
if ($online != null) {
echo ' <strong>'.$online.'</strong>';
echo '&nbsp <img src="/images/online.png"><strong> Status:</strong> Online! </br>';
echo '<img src="/images/viewers.png"><strong>Viewers:</strong> &nbsp' .$viewers.'</br>';
}
}
$alloffline = "All female user streams are currently offline.";
function signin($person){
if($person != null){
return $person;
}
?>
</body>
</html>
............................................................................................................................................................................
Is it because your $userGrab URL contains usernames twice? This is the URL whose contents you're retrieving:
http://api.justin.tv/api/stream/list.json?channel=painuser,ZombieGrub,Nathanias,Youbetterknowme,ncl_tv,painuser,ZombieGrub,Nathanias,Youbetterknowme,ncl_tv
Having looked at the response, it doesn't look like it's causing the problem. The strange URL is a result of you appending to the $userGrab string in the first foreach loop, after you've already added them with the implode() function call before. I think twitch.tv is rightly ignoring duplicate channels.
If all the values in $checkedOnline are null, everyone is offline. Put this at the end of your first code sample:
$personOnline = false;
foreach($checkedOnline as $person) {
if($person !== null) {
$personOnline = true;
break;
}
}
if(!$personOnline) {
echo 'No one is online';
}
else {
//there is at least someone online
}

Storing array in a variable

I'm trying to replace the code below
$Palette = array(
"0"=>array("R"=>188,"G"=>224,"B"=>46,"Alpha"=>100),
"1"=>array("R"=>188,"G"=>224,"B"=>46,"Alpha"=>100),
"2"=>array("R"=>188,"G"=>224,"B"=>46,"Alpha"=>100),
"3"=>array("R"=>188,"G"=>224,"B"=>46,"Alpha"=>100),
"4"=>array("R"=>176,"G"=>46,"B"=>224,"Alpha"=>100),
);
with something similar but different values for the R, G and B. I have written the code below so far as a replacement:
$x = '0';
$incrementarray = array("0"=>"A","1"=>"B","2"=>"C","3"=>"D","4"=>"E");
do
{
if ($correct == $incrementarray[$x])
{
$colour[$x] = '"'.$x.'"=>array("R"=>188,"G"=>224,"B"=>46,"Alpha"=>100),';
}
else
{
$colour[$x] = '"'.$x.'"=>array("R"=>255,"G"=>51,"B"=>51,"Alpha"=>100),';
}
$x++;
}
while ($x <= '4');
$allcolours = $colour[0].$colour[1].$colour[2].$colour[3].$colour[4];
however, when I implement it into my script using the line below , it doesn't work.
$Palette = array($allcolours);
$x = '0';
$incrementarray = array("0"=>"A","1"=>"B","2"=>"C","3"=>"D","4"=>"E");
do
{
if ($correct == $incrementarray[$x])
{
$Pallete[$x] = array("R"=>188,"G"=>224,"B"=>46,"Alpha"=>100);
}
else
{
$Pallete[$x] = array("R"=>255,"G"=>51,"B"=>51,"Alpha"=>100);
}
$x++;
}
while ($x <= '4');
there is a little excessive usage of $x.
as a matter of fact, you don't need that variable at all
$Palette = array();
$incrementarray = array("0"=>"A","1"=>"B","2"=>"C","3"=>"D","4"=>"E");
foreach ($incrementarray as $value)
{
if ($correct == $value)
{
$Palette[] = array("R"=>188,"G"=>224,"B"=>46,"Alpha"=>100);
}
else
{
$Palette[] = array("R"=>255,"G"=>51,"B"=>51,"Alpha"=>100);
}
}
you need to create array, not the PHP code to create array.

Categories