Why the Loop not properly Looping through the data? - php

<?php
$id = array(
"UC4MubF2asPHQbXN44DVNeXg",
"UCXuDgoo_oiZf8UkIXs3Y_kw",
"UCMnDuOzzJrWzr5tfemDcqlQ",
"UC9FH1mkHLFQuPPEPu9CfR1A",
"UCfyEAw41i7PRetP2erYf9dg",
);
// Getting Emails from DB and Looping with Channel Title and Video Title
$conn = mysqli_connect("localhost","username","password","dbname");
$query = "SELECT * FROM prospects ORDER BY email";
$rows = mysqli_query($conn, $query);
while($row = mysqli_fetch_array($rows)) {
$to[] = $row['email'];
}
$size = sizeof($id);
//echo "<br>Number of channel Ids: ".$size."<br><br>";
// Looping each Url for Each Email to get Data
foreach($to as $t){
echo $t."<br>";
for ($i = 0; $i < $size; $i++) {
$url = "https://www.youtube.com/channel/$id[$i]";
// echo $url."<br>";
$channel = trim(explode('https://www.youtube.com/channel/', $url)[1]);
// echo $channel."<br>";
$rss = "https://www.youtube.com/feeds/videos.xml?channel_id=$channel";
// echo $rss."<br>";
$xml = simplexml_load_file($rss);
$title = $xml->title;
// echo $title."<br>";
$videoTitle = $xml->entry[0]->title;
// echo $videoTitle."<br>";
$id[$i] = $xml->id;
// echo $id[$i]."<br>";
// $idOnly = substr($id[$i] , strpos($id[$i] , "yt:channel:") + 11);
// echo $idOnly."<br>";
$pub[$i] = $xml->entry[0]->published;
// echo $pub[$i]."<br>";
$realDate_ = new DateTime($pub[$i]);
// var_dump($realDate_);
$realDate2_ = $realDate_->format("D, d M Y")."<br>";
//echo $realDate2_;
$today_ = new DateTime();
// $today2_ = $today_->format("D, d M Y")."<br>";
// echo $today2_;
// if ($today2_ == $realDate2_) {
// echo "true";
// This is the Result with Every Email
echo $content = "• <a href='https://bladingflix.com/render.php?email=$t&channel=$idOnly'>".$title." - ".$videoTitle."</a><br>";
// }
}
}
?>
For the First Email the Data Shows Properly but in for the others
Purpose = get collected links add the user email to each url repeat for each.

Please make below changes in your existing code
In the second for() loop you are replacing the $id array as below
$id[$i] = $xml->id;
Instead of replacing the $id[$i] value, create new variable as below
$xmlId = $xml->id;
$idOnly = substr($xmlId, strpos($xmlId , "yt:channel:") + 11);
And please uncomment the $idOnly variable.
It will work. And try to refactor this code.

Related

Using an If statement in PHP but not working

What I want to do is When I enter all my information (for client ID 199 in the picture) In my account being submit it, it goes into the database. BUT I want it to change to something and so i added an if statement
Here the code im adding to the existing code already at the BOTTOM of the code
if ($vpr_clid == 199) {
$vpr_cl_name = "Shelley Madsen And Associates";
}
if the ($vpr_clid = 199)
i want the clname to be "Shelley Madsen And Associates" then what is show in the table below instead of "Nice and White Smiles" (that an example of the results look like)
but when i chcek the database it not changing it and still show "Nice and White Smiles :(
I dont see any error, so it might be the placement of the code i have to put the IF statement in the huge php file? Dont know how to fix this issue
Thanks (the code below is the base code before i added the If statement)
I also insert the if statement before the function were called but still didnt work example
if ($vpr_clid == 199) {
$vpr_cl_name = "Shelley Madsen And Associates";
}
$result = InsertIntoPayReminder($link, $vars);
$result = GetVpr_Id($link, $vars);
<?php
session_start();
if ($_SESSION['company'] != "ACB") {
// redirect to the logout page
$redirect = 'logout.php';
include './includes/redirect.php';
}
class variables_obj {
var $vpr_plan = '';
var $vpr_id = '';
var $vpr_clid = '';
var $vpr_cl_name = '';
var $vpr_cl_phone = '';
var $vpr_call_start_date = '';
var $vpr_db_account = '';
var $vpr_db_fname = '';
var $vpr_db_mname = '';
var $vpr_db_lname = '';
var $vpr_rp_fname = '';
var $vpr_rp_mname = '';
var $vpr_rp_lname = '';
var $vpr_rp_address = '';
var $vpr_rp_city = '';
var $vpr_rp_state = '';
var $vpr_rp_zipcode = '';
var $vpr_rp_phonenum = '';
var $vpr_rp_phonetype = '';
var $vpr_date_entered = '';
var $newrecdt = '';
var $vpl_day_offset = '';
var $vpl_action = '';
var $vpr_promocode = '';
}
function ScrubPhone($old_phone_num) {
$phone_length = strlen($old_phone_num);
$new_phone_num = "";
for($i = 0; $i < $phone_length; $i = $i + 1) {
if(is_numeric($old_phone_num[$i])) {
$new_phone_num .= $old_phone_num[$i];
}
}
return $new_phone_num;
}
function ScheduleCreated($link, $vars) {
$query = "UPDATE v_payreminder SET vpr_schedule_created = '1' WHERE vpr_id='".$vars->vpr_id."'";
if (!mysql_query($query,$link)) {
die('Error: ' . mysql_error());
}
return true;
}
function CreateScheduleRow($link, $vars){
// echo "vpl_day_offset: ".$vars->vpl_day_offset."<br>";
// echo "vpl_action: ".$vars->vpl_action."<br>";
$plus_days = " +".$vars->vpl_day_offset." days";
// echo "plus days: ".$plus_days."<br>";
$date_offset = strtotime(date("Y-m-d", strtotime($vars->vpr_date_entered)).$plus_days);
$date_offset = date("Y-m-d", $date_offset);
// echo "date_offset: ".$date_offset."<br>";
// $date_offset = strtotime(date("Y-m-d",strtotime($vars->vpr_date_entered))." +".$vars->vpl_day_offset." days");
// $date_offset = strtotime(date("Y-m-d", strtotime($date)) . " +1 day");
// echo "date_offset: ".$date_offset."<br>";
$query = "INSERT INTO v_pr_schedule (
vpr_id,
vsc_plan,
vsc_date_entered,
vsc_action,
vsc_action_date,
vsc_status
) VALUES (
'$vars->vpr_id',
'$vars->vpr_plan',
'$vars->vpr_date_entered',
'$vars->vpl_action',
'$date_offset',
'VACT')";
//echo "query: ".$query."<br>";
if (!mysql_query($query,$link)) {
die('Error: ' . mysql_error());
}
return true;
}
function CreateSchedule($link, &$vars) {
// CREATE SCHEDULE
$query = " SELECT vpl_day_offset, vpl_action, vpl_condition
FROM v_plan
WHERE vpl_plan = '".$vars->vpr_plan."'";
// echo "query: ".$query."<br>";
$qresult = mysql_query($query);
if (!$qresult) {
print(mysql_error());
}
if ($qresult && mysql_num_rows($qresult) > 0 ) {
while ($row = mysql_fetch_array($qresult, MYSQL_ASSOC)) {
$vars->vpl_day_offset = $row['vpl_day_offset'];
$vars->vpl_action = $row['vpl_action'];
if ($row['vpl_condition'] == 'OO') {
CreateScheduleRow($link, $vars);
}
}
}
return true;
}
function InsertIntoPayReminder($link, &$vars) {
$vars->vpr_cl_name = strtr($vars->vpr_cl_name, "'", " ");
//echo "Client Name: ".$vars->vpr_cl_name."<br><br>";
//exit();
$sql="INSERT INTO v_payreminder (
vpr_clid,
vpr_cl_name,
vpr_cl_phone,
vpr_call_start_date,
vpr_db_account,
vpr_db_fname,
vpr_db_mname,
vpr_db_lname,
vpr_rp_fname,
vpr_rp_mname,
vpr_rp_lname,
vpr_rp_phonenum,
vpr_rp_phonetype,
vpr_rp_address,
vpr_rp_city,
vpr_rp_state,
vpr_rp_zipcode,
vpr_promo,
vpr_date_entered) VALUES (
'$vars->vpr_clid',
'$vars->vpr_cl_name',
'$vars->vpr_cl_phone',
'$vars->vpr_call_start_date',
'$vars->vpr_db_account',
'$vars->vpr_db_fname',
'$vars->vpr_db_mname',
'$vars->vpr_db_lname',
'$vars->vpr_rp_fname',
'$vars->vpr_rp_mname',
'$vars->vpr_rp_lname',
'$vars->vpr_rp_phonenum',
'$vars->vpr_rp_phonetype',
'$vars->vpr_rp_address',
'$vars->vpr_rp_city',
'$vars->vpr_rp_state',
'$vars->vpr_rp_zipcode',
'$vars->vpr_promocode',
'$vars->vpr_date_entered')";
if (!mysql_query($sql,$link)) {
die('Error2: ' . mysql_error());
}
return true;
}
function GetVpr_Id($link, &$vars) {
// Find out what vpr_id is
$query = "SELECT vpr_id FROM v_payreminder ";
$query .= "WHERE vpr_clid = '".$vars->vpr_clid."' AND vpr_date_entered = '".$vars->vpr_date_entered."'";
$qresult = mysql_query($query);
if (!$qresult) {
print(mysql_error());
}
if ($qresult && mysql_num_rows($qresult) > 0 ) {
$row = mysql_fetch_array($qresult, MYSQL_ASSOC);
$vars->vpr_id = $row['vpr_id'];
}
}
function InsertInActivity($link, $vars) {
// ENTER INTO ACTIVITY
$vaction_desc = 'PATIENT ENTERED';
$sql = "INSERT INTO v_pr_activity (
vpr_id,
va_plan,
va_action_dttm,
va_action_code,
va_action_desc,
va_disposition_code,
va_disposition_desc,
va_status_code,
va_status_desc
) VALUES (
'$vars->vpr_id',
'$vars->vpr_plan',
'$vars->vpr_date_entered',
'VINIT',
'$vaction_desc',
'SUCCESS',
'SUCCESS',
'VACT',
'ACTIVE'
)";
if (!mysql_query($sql,$link)) {
die('Error: ' . mysql_error());
}
}
include './includes/dblogin.php';
$vars = new variables_obj();
$vars->vpr_plan = 'VP01';
$vars->vpr_clid = $_SESSION['userid'];
//-------------------------------------------------------
// No commas can be in client name or they will
// mess up the Global Connect CSV file.
//-------------------------------------------------------
$vpr_cl_name = $_SESSION['username'];
$vpr_cl_name = str_replace(",", " ", $vpr_cl_name);
$vars->vpr_cl_name = $vpr_cl_name;
//-------------------------------------------------------
//-------------------------------------------------------
$vars->vpr_cl_phone = ScrubPhone($_SESSION['uphone']);
$vars->vpr_call_start_date = '0000-00-00';
$vars->vpr_db_account = $_POST['ndaccnum'];
$vars->vpr_db_fname = $_POST['ndfreqname'];
$vars->vpr_db_mname = $_POST['ndmname'];
$vars->vpr_db_lname = $_POST['ndlreqname'];
$vars->vpr_rp_fname = $_POST['ndrfreqname'];
$vars->vpr_rp_mname = $_POST['ndrmname'];
$vars->vpr_rp_lname = $_POST['ndrlreqname'];
$vars->vpr_rp_address = '';
$vars->vpr_rp_city = '';
$vars->vpr_rp_state = $_POST['ndrstatereqname'];
$vars->vpr_rp_zipcode = $_POST['ndrreqzipcode'];
$phonenumber = $_POST['1ndrreqphone'].$_POST['2ndrreqphone'].$_POST['3ndrreqphone'];
$vars->vpr_rp_phonenum = $phonenumber;
$vars->vpr_rp_phonetype = $_POST['treqphone'];
$vars->vpr_date_entered = date('Y-m-d H:i:s');
$vars->newrecdt = date('Ymd');
$vars->vpr_promocode = $_POST['promocode'];
// echo "vpr_plan: ".$vars->vpr_plan."<br>";
// echo "vpr_date_entered: ".$vars->vpr_date_entered."<br>";
// echo "newrecdt: ".$vars->newrecdt."<br>";
// echo "vpr_clid: ".$vars->vpr_clid."<br>";
// echo "vpr_id: ".$vars->vpr_id."<br>";
$result = InsertIntoPayReminder($link, $vars);
$result = GetVpr_Id($link, $vars);
$result = InsertInActivity($link, $vars);
$result = CreateSchedule($link, $vars);
$result = ScheduleCreated($link, $vars);
// echo "vpr_id: ".$vars->vpr_id."<br>";
mysql_close($link);
// redirect
$redirect = 'vpayremind.php';
include './includes/redirect.php';
?>
okay referencing the following lines..
if ( $vpr_clid == 199 ) {
$vpr_cl_name = "Shelley Madsen And Associates";
}
$result = InsertIntoPayReminder($link, $vars);
...and then:
function InsertIntoPayReminder($link, &$vars) {
$vars->vpr_cl_name = strtr($vars->vpr_cl_name, "'", " ");
so on and so forth... }
it doesnt seem as if you are actually setting the value of the class object. You seem to be setting some arbitrary php variable to the name you want, and then passing a totally different ' $vars ' object into the function. I don't see any reason to believe that the ' $vars ' you are passing into the function call contains the name value you want it to contain. You should be assigning the value of ' $vars ' before passing it in.
For instance:
if ( $vpr_clid == 199 ) {
$vars[ 'vpr_cl_name' ] = "Shelley Madsen And Associates";
}
then you can get rid of this line all together:
$vars->vpr_cl_name = strtr($vars->vpr_cl_name, "'", " ");

MySQL echos only one elemen

I've a problem with a MySQL script. The script should echo every element out of the table where "gruppe" is $gruppe. But I am only getting one single output.
<?php
if ( $_SERVER["REQUEST_METHOD"] == 'POST' ) {
$gruppe = $_POST["gruppe"];
$mail = $_POST["mail"];
$betreff = $_POST["betreff"];
$nachricht = $_POST["nachricht"];
if (!empty($nachricht)) {
$sql = new rex_sql;
$sql->debugsql = 0; //Ausgabe Query
$sql->setQuery("SELECT * FROM $db_users WHERE gruppe = '$gruppe'");
for($i=0;$i<$sql->getRows();$i++)
{
$id_mail = $sql->getValue("id");
$mail_mail = $sql->getValue("email");
$ausgabe_mail = $mail_mail;
$sql->next();
}
}
}
?>
<?php echo $ausgabe_mail ?>
Your echo-statement is outside the loop. The loop fetches all email addresses, one by one, and stores them in $mail_mail and $ausgabe_mail. Each iteration of the loop overwrites the previous contents of both variables.
After the loop ends, you echo the last value of $ausgabe_email.
Retry with the echo inside the loop:
<?php
if ( $_SERVER["REQUEST_METHOD"] == 'POST' ) {
$gruppe = $_POST["gruppe"];
$mail = $_POST["mail"];
$betreff = $_POST["betreff"];
$nachricht = $_POST["nachricht"];
if (!empty($nachricht)) {
$sql = new rex_sql;
$sql->debugsql = 0; //Ausgabe Query
$sql->setQuery("SELECT * FROM $db_users WHERE gruppe = '$gruppe'");
for($i=0;$i<$sql->getRows();$i++) {
$id_mail = $sql->getValue("id");
$mail_mail = $sql->getValue("email");
$ausgabe_mail .= ',' . $mail_mail;
$sql->next();
}
echo $ausgabe_mail;
}
}
?>
EDIT: as clarified, expanded the example with string concatenation and moved the echo outside the loop again.

Issue reading reading json tag in php

I am sending the following json to the server
{
"username":"abc#abc.com" ,
"password":"abc#123","access_key": "api_key",
"brands": [
{ "brandname": "Lee","xcoord": "1345",
"ycoord": "2345","color": {"colorId":8, "rvalue": "234",
"gvalue": "213","bvalue": "233" }
},
{ "brandname": "Pepe","xcoord": "432",
"ycoord": "4210","color": {"colorId":5, "rvalue": "234",
"gvalue": "213","bvalue": "233"}
}
],
"description": "free text",
"ocassion": 1, // an ocassion id goes here.
"other_tags": ["other1","other2"],
"upload_platform":"android|iOS|web"
}
When i try to read a specific object color, which resides brands array object as below I am unable to do so and the echo fails, printing nothing. I have never written php, its so easy in java to just use gson and define models that would fill every model up.
$userData = urldecode ( $_POST['form'] );
$json = json_decode ( $userData );
$brandTagsArr = $json->brands;
foreach ($brandTagsArr as $brandTag){
$brandName = $brandTag->brandName; // need to fetch the name and associate brand tag id
$xCoord = $brandTag->xcoord; //
$yCoord = $brandTag->ycoord;
$this->rest_image_upload_model->insertBrandTags($imageId, $brandName, $xCoord, $yCoord);
// insert colors
echo "insert brand tags <br>";
$color = $brandTag['color']; // returns nothing FAILS
$color = $brandTag->color; // returns nothing FAILS
echo "color id" . $color['colorId'];
$this->rest_image_upload_model->insertColorTag($imageId, $color['colorId'],$color['rValue'], $color['gValue'], $color['bValue']);
echo "insert color tags<br>";
// end inserting colors
}
the tag name for colors is rvalue,gvalue and bvalue, but you are using as rValue,gValue and bValue. I think thats the issue in your code.
$imageId = 1;
$a["username"] = "abc#abc.com";
$a["password"] = "abc#123";
$a["access_key"] = "api_key";
$a["description"] = "free text";
$a["ocassion"] = "1";
$a["brands"][0]["brandName"] = "Lee";
$a["brands"][0]["xcoord"] = "1345";
$a["brands"][0]["ycoord"] = "2345";
$a["brands"][0]["color"]["colorId"] = "8";
$a["brands"][0]["color"]["rvalue"] = "234";
$a["brands"][0]["color"]["gvalue"] = "213";
$a["brands"][0]["color"]["bvalue"] = "432";
$a["brands"][1]["brandName"] = "Lee";
$a["brands"][1]["xcoord"] = "1345";
$a["brands"][1]["ycoord"] = "2345";
$a["brands"][1]["color"]["colorId"] = "8";
$a["brands"][1]["color"]["rvalue"] = "234";
$a["brands"][1]["color"]["gvalue"] = "213";
$a["brands"][1]["color"]["bvalue"] = "432";
$json = json_decode(json_encode($a));
$brandTagsArr = $json->brands;
foreach ($brandTagsArr as $brandTag) {
// print_r($brandTag->color);exit;
$brandName = $brandTag->brandName; // need to fetch the name and associate brand tag id
$xCoord = $brandTag->xcoord; //
$yCoord = $brandTag->ycoord;
// $this->rest_image_upload_model->insertBrandTags($imageId, $brandName, $xCoord, $yCoord);
echo $imageId."===>".$brandName."===>".$xCoord."===>".$yCoord."<br>";
// insert colors
echo "insert brand tags <br>";
// $color = $brandTag['color']; // returns nothing FAILS
$color = $brandTag->color; // returns nothing FAILS
echo "color id =>" . $color->colorId;
echo $imageId."===>".$color->colorId."===>".$color->rvalue."===>".$color->gvalue."===>".$color->bvalue."<br>";
echo "insert color tags<br>";
// end inserting colors
}
For your convenience i ve created an array encoded and decoded there only.Hope it helps.

php code of troubling getting multiple value

I have codes that should be getting value from mysql database, I can get only one value but I have while loop so it can get value and output data separated with comma. But I only get one value and cannot get multiple value. the result should be like this, // End main PHP block. Data looks like this: [ [123456789, 20.9],[1234654321, 22.1] ] here is the code:
<?php
// connect to MySQL
mysql_connect('localhost','','') or die("Can't connect that way!");
#mysql_select_db('temperature1') or die("Unable to select a database called 'temperature'");
if(ISSET($_GET['t']) && (is_numeric($_GET['t'])) ){
// message from the Arduino
$temp = $_GET['t'];
$qry = "INSERT INTO tempArray(timing,temp) VALUES(".time().",'$temp')";
echo $qry;
mysql_query($qry);
mysql_close();
exit('200');
}
// no temp reading has been passed, lets show the chart.
$daysec = 60*60*24; //86,400
$daynow = time();
if(!$_GET['d'] || !is_numeric($_GET['d'])){
$dayoffset = 1;
} else {
$dayoffset = $_GET['d'];
}
$dlimit = $daynow-($daysec*$dayoffset);
$qryd = "SELECT id, timing, temp FROM tempArray WHERE timing>='$dlimit' ORDER BY id ASC LIMIT 1008";
// 1008 is a weeks worth of data,
// assuming 10 min intervals
$r = mysql_query($qryd);
$count = mysql_num_rows($r);
$i=0;
$r = mysql_query($qryd);
$count = mysql_num_rows($r);
while($row=mysql_fetch_array($r, MYSQL_ASSOC)) {
$tid=$row['id'];
$dt = ($row['timing']+36000)*1000;
$te = $row['temp'];
if($te>$maxtemp) $maxtemp=$te; // so the graph doesnt run along the top
if($te<$mintemp) $mintemp=$te; // or bottom of the axis
$return="[$dt, $te]";
echo $return; //here I get all values [1385435831000, 21][1385435862000, 23][1385435892000, 22][1385435923000, 25][1385435923000, 22]
$i++;
if($i<$count) $return= ","; echo $return; // if there is more data, add a ',' however, it return me ,,,[1385435923000, 22]
$latest = "$dt|$te"; // this will get filled up with each one
}
mysql_close();
// convert $latest to actual date - easier to do it here than in javascript (which I loathe)
$latest = explode('|',$latest);
$latest[0] = date('g:ia, j.m.Y',(($latest[0])/1000)-36000);
?>
You're just assigning $return to the values from the last row your while loop grabbed instead of concatenating it. Try this
$return = "[";
while($row=mysql_fetch_array($r, MYSQL_ASSOC)) {
$tid=$row['id'];
$dt = ($row['timing']+36000)*1000;
$te = $row['temp'];
if($te>$maxtemp) $maxtemp=$te; // so the graph doesnt run along the top
if($te<$mintemp) $mintemp=$te; // or bottom of the axis
$return.="[$dt, $te]";
$i++;
if($i<$count) $return .= ", ";// if there is more data, add a ','
$latest = "$dt|$te"; // this will get filled up with each one
}
$return .= "]";

How to loop through an array and add to it in JSON

I have an array containing several variables from my sql database.
{"gold":"0","silver":"0","bronze":"0","gdp":"12959563902","population":"3205000","country_name":"Albania"}, {"gold":"1","silver":"0","bronze":"0","gdp":"188681000000","population":"35468000","country_name":"Algeria"}
I have an additional variable called $score that uses information from the database to calculate this score. I want to know how I can loop through and add the correct score to each country in the array.
My Original Code:
$row = $res->fetchRow();
$resGold = $row['gold'];
$resSilver = $row['silver'];
$resBronze = $row['bronze'];
$resGdp = $row['gdp'];
$resPopulation = $row['population'];
$resCountry = $row['country_name'];
$gold_score = ($resGold * $gold_value);
$silver_score = ($resSilver * $silver_value);
$bronze_score = ($resBronze * $bronze_value);
if($population == true){
$score = (($gold_score + $silver_score + $bronze_score)/$resPopulation);
}
else if($gdp == true){
$score = (($gold_score + $silver_score + $bronze_score)/$resGdp);
}
$result = $res->fetchAll();
$result[] = array('score' => $score);
echo json_encode($result);
Your code will be something like this:
$json_data = '{"gold":"0","silver":"0","bronze":"0","gdp":"12959563902","population":"3205000","country_name":"Albania"},
{"gold":"1","silver":"0","bronze":"0","gdp":"188681000000","population":"35468000","country_name":"Algeria"}';
$countries_info_new = array();
$countries_info = json_decode($json_data);
foreach($countries_info as $country_info){
$country_info['score'] = Get_country_score($country_info['country_name']);
$countries_info_new[]=$country_info;
}
$new_json_data = json_encode($countries_info_new);

Categories