I have the following small code which manipulate tweets data. I expect my loop to iterate 10 times. However, what happens is that it iterates only once and then exits, with no sign of any error relating to MySQL or otherwise.
$query = "select data from tweets where `screen_name` = 'username' limit 10";
$tweetsq = mysqli_query($mysqli, $query) or die(mysqli_error($mysqli));
$tweets = mysqli_fetch_assoc($tweetsq);
$tweets_count = mysqli_num_rows($tweetsq);
echo $tweets_count . '<br />'; //See output
$count = 0;
foreach ($tweets as $raw_tweet) {
$tweet = json_decode($raw_tweet);
$tweet_id = $tweet->id_str;
$is_reply = (isset($tweet->in_reply_to_screen_name) && strlen($tweet->in_reply_to_screen_name) > 0) ? 1 : 0;
$is_retweet = (isset($tweet->retweeted_status) && $tweet->retweeted_status != '') ? 1 : 0;
$entity_holder = array();
$has_hashtag = $has_url = $has_mention = $has_media = 0;
foreach ($tweet->entities as $type => $entity) {
if (is_array($entity) && count($entity) < 1) {
//continue;
} else {
$entity = array_pop($entity);
switch ($type) {
case 'hashtags' : $has_hashtag = 1; break;
case 'urls' : $has_url = 1; break;
case 'user_mentions' : $has_mention = 1; break;
case 'media' : $has_media = 1; break;
default :
}
}
}
echo 'Updating recorde... <br />';
$query = "UPDATE tweets SET is_reply='" . $is_reply . "' , is_retweet='" . $is_retweet . "', has_hashtag='" . $has_hashtag . "', has_url='" . $has_url . "', has_mention='" . $has_mention . "', has_media='" . $has_media . "' WHERE tweet_id='" . $tweet_id . "'";
$result = mysqli_query($mysqli, $query) or die(mysqli_error($mysqli));
var_dump($result); //See output
$count++;
echo '<br />';
}
echo $count;
Output:
10 //This is the value of $tweets_count
Updating recorde...
bool(true) //The result of the UPDATE query
1 //The value of $count at the end of script. It SHOULD be 10
mysqli_fetch_assoc fetches a single row as an associative array where the key is the column name and the value is the column value. The correct way to use it would be to iterate over the result set until the fetch returns NULL, indicating that there are no more rows to fetch:
while ($row = mysqli_fetch_assoc($tweetsq)) {
$raw_tweet = $row["data"];
$tweet = json_decode($raw_tweet);
$tweet_id = $tweet->id_str;
# etc...
Related
I have a form with three fields that I want to read separately from the database
$_POST['wkNumer1'];
$_POST['wkNumer2'];
$_POST['wkNumer3'];
How can I read this data without repeating the same code 3 times? In this code, only the variable $wkNumer value will be change.
<?php
if (isset($_POST['show_diagram'])) {
$goodname = $_POST['htDriver'];
$wkNumer = $_POST['wkNumer1'];
// Table with data
$sql = "SELECT WorkingDay, OrderNo, NameFinish, Type FROM `status` where WEEK(WorkingDay) = :wknumer AND NameFinish = :nameFinish"; // SQL with parameters
$stmt = $conn->prepare($sql);
$stmt->bindParam("wknumer", $wkNumer);
$stmt->bindParam("nameFinish", $goodname);
$stmt->execute();
$OCSdatas = $stmt->fetchAll(PDO::FETCH_ASSOC);
$count = $stmt->rowCount();
$countWithoutE = 0;
$countE = 0;
foreach ($OCSdatas as $data) {
if ($data['Type'] != 'E') {
$countWithoutE = $countWithoutE + 1 ;
}
if ($data['Type'] == 'E') {
$countE = $countE + 1 ;
}
}
echo $goodname . '<br />';
echo $wkNumer . '<br />';
echo $countWithoutE . '<br>';
echo $countE . '<br>';
$countE = $countE/2;
$countTotal = $countWithoutE + $countE;
echo $countTotal/5 . '<br>';
echo $count/5;
}
?>
You can put the numbers inside an array and iterate through that array to execute the same code.
$goodname = $_POST['htDriver'];
// Add the numbers to an array which we can iterate
$numbers = [
$_POST['wkNumber1'],
$_POST['wkNumber2'],
$_POST['wkNumber3'],
];
// Prepare the statement only once before the loop and reuse it
$sql = "SELECT WorkingDay, OrderNo, NameFinish, Type FROM `status` where WEEK(WorkingDay) = :wknumer AND NameFinish = :nameFinish";
$stmt = $conn->prepare($sql);
// Loop through the numbers
foreach ($numbers as $number) {
// Add the current number
$stmt->bindParam("wknumer", $number);
$stmt->bindParam("nameFinish", $goodname);
$stmt->execute();
// Now have everything as you had before
$OCSdatas = $stmt->fetchAll(PDO::FETCH_ASSOC);
$count = $stmt->rowCount();
$countWithoutE = 0;
$countE = 0;
foreach ($OCSdatas as $data) {
if ($data['Type'] != 'E') {
$countWithoutE = $countWithoutE + 1 ;
}
if ($data['Type'] == 'E') {
$countE = $countE + 1 ;
}
}
echo $goodname . '<br />';
echo $wkNumer . '<br />';
echo $countWithoutE . '<br>';
echo $countE . '<br>';
$countE = $countE/2;
$countTotal = $countWithoutE + $countE;
echo $countTotal/5 . '<br>';
echo $count/5;
}
How does this work for you?
$workNumbers = array($_POST['wkNumer1'],$_POST['wkNumer2'],$_POST['wkNumer3']);
foreach($workNumbers as $wkNumer){
//Your Code block here
}
I'm continuing my previous question.
Now I need to insert the value to DB. But ID inserted is not correct as on my database master.
$qModel = oci_parse($c1, "SELECT MODELID, MODEL_NAME FROM WA_LFO_TBL_MODEL
WHERE ACTIVE = 'Y'");
oci_execute($qModel);
while($dModel = oci_fetch_array($qModel))
{
$qDtl2 = oci_parse($c1, "SELECT * FROM WA_LFO_TBL_MODEL_CONFIGURATION WHERE MODELID_FK = '" . $dModel['MODELID'] . "'");
oci_execute($qDtl2);
while($dDtl2 = oci_fetch_array($qDtl2))
{
$q = oci_parse($c1, "SELECT * FROM WA_LFO_TBL_REJECT_PROCESS WHERE MODELID_FK = '" . $dModel['MODELID'] . "' ORDER BY SORT_NO ASC");
oci_execute($q);
while($d = oci_fetch_array($q))
{
$idkeys[] = $d['RP_ID'];
$keys[] = $d['RP_NAME'];
}
$values = array_fill(0, count($keys), 0);
$values = array_combine($keys, $values);
for($i = $readRowAfter; $i < count($linesReject); $i++)
{
// if the fileReject is "Tue, Sep 18<tab>2018<tab>23:59:53<tab>"
$dateobjReject = DateTime::createFromFormat($createFromFormat, $linesReject[$i]);
// check if date is in your Timespan
if($dateobjReject < $toDateTime && $dateobjReject > $fromDateTime)
{
$rowsintimespanReject++; // count if in timespan
$lineContent = explode("\t", $linesReject[$i]);
// loop through line elements and count them
$x = 0;
for ($j = 0; $j < count($keys); $j++) {
if (!isset($lineContent[$j])) {
continue;
}
// remember position of last not empty column
if (trim($lineContent[$j]) != '') {
$x = $j;
}
}
if ($x > 0) {
$values[$keys[$x]]++;
}
}
}
$i = 0;
$sql = "";
foreach ($values as $value)
{
if($value != 0)
{
$sql = oci_parse($c1,"INSERT INTO WA_LFO_TBL_REJECT_OUTPUT(MODELID_FK, QUANTITY, RPID_FK, CONFIGURATIONID_FK)VALUES('" . $dModel['MODELID'] . "', '" . $value . "', '" . $idkeys[$i] . "', '" . $dDtl2['CONFIGURATIONID'] . "')");
oci_execute($sql);
}
$i++;
}
}
}
As you can see that I'm trying to insert the date on foreach function.
But inserted data for ID is not correct for RPID_FK.
I realize maybe something wrong with the code, tried to get the solution but still stuck on it.
Is something wrong on that code?
I want to transform this PHP function.. that should return JSON data.
<?php
$query = 'SELECT * FROM `' . mix_player::table() . '` a';
if (isset($_GET['cat']) || isset($_GET['order']))
if (isset($_GET['cat'])) {
$query .= ' INNER JOIN `' . mix_player::table_cat_rel() . '` b '
. "ON (a.`id` = b.`idtrack`) WHERE `idcat` = '" . $wpdb->escape($_GET['cat']) . "'";
$random = $wpdb->get_var('SELECT `random`, `order` FROM `' . mix_player::table_categories() . "` WHERE `id` = '"
. $wpdb->escape($_GET['cat']) . "'");
if (!$random)
$order = $wpdb->get_var(NULL, 1);
}
if (isset($_GET['order']))
$order = $_GET['order'];
if ($order != '') {
if (isset($_GET['cat']))
$query .= ' AND ';
else
$query .= ' WHERE ';
$tracks = mix_player::order_list($query, $order);
}
} else {
$random = '0';
}
$query .= ' ORDER BY `id` ASC';
if (isset($tracks) || ($tracks = $wpdb->get_results($query, ARRAY_A))) {
// option "shuffle = true" not always working into mix. Do it our own way...
if ($random == 1) { // shuffle tracks?
list($usec, $sec) = explode(' ', microtime());
mt_srand((float) $sec + ((float) $usec * 100000));
$nrows = count($tracks);
for ($i = 0; $i < $nrows; $i++) {
$j = mt_rand(0, $nrows - 1); // pick j at random
$row = $tracks[$i]; // swap i, j
$tracks[$i] = $tracks[$j];
$tracks[$j] = $row;
}
}
foreach ($tracks as $row) {
$artist = (mix_player::entities($row['artist']));
echo ($artist);
$title = (mix_player::entities($row['title']));
echo ($title);
$url =(xspf_player::entities($row['url']));
echo ($url);
}
}
?>
to display like this json file :
{"title":"title", "artist":"artist","media":"url media.mp3","color":"#56B0E8" },
Can you help me?
Thanks in advance.
You can simply create an array and populate it with your desired values, then return it as JSON:
function tracks2json( $tracks )
{
$retval = array();
foreach( $tracks as $row )
{
$array = array();
$array['artist'] = mix_player::entities($row['artist']);
$array['title'] = mix_player::entities($row['title']);
$array['media'] = 'url '.xspf_player::entities($row['url']);
$array['color'] = '#56B0E8';
$retval[] = $array;
}
return json_encode( $retval );
}
if( isset($tracks) || ($tracks = $wpdb->get_results($query, ARRAY_A)) )
{
// Your MySQL routine here
$json = tracks2json( $tracks );
}
echo json_encode(array("title"=>$title,"artist"=>$artist,"url"=>$url));
i used unset method to empty my array it does but when i initilize same array again to reuse it in my code it gives the fatal error
Unsupported operand types
although other unset are working fine but only one array with integer type values have problem.
Any kind of help would be appreciated
here is my piece of code:
<?php
for ($citycount = 0; $citycount < $count; $citycount ++) {
$loc_qry = "SELECT `ID` as LocationID, `name` as LocationName FROM `territories` where `formatID` = 43 and `territorylevelID` = 77 and `parentID` = '" . $cityID_arr[$citycount] . "'";
$loc_qry_res = mysql_query($loc_qry) or die($loc_qry . "<br><br>" . mysql_error());
while ($rs_loc = mysql_fetch_array($loc_qry_res)) {
$location_id_arr[] = $rs_loc['LocationID'];
$location_name_arr [] = $rs_loc['LocationName'];
}
$count_loc = count($location_id_arr);
for ($i = 0; $i < $count_loc; $i++) {
$location_scores = "SELECT ((SUM(sa.achievedScore) / SUM(sa.totalScore)) * 100) as Score
FROM `scoreanalysis` as sa
WHERE `formatID` = 43 and `waveID` = '" . $wave_id_arr[0] . "' and `territoryID` = '" . $location_id_arr[$i] . "'";
$location_scores_res = mysql_query($location_scores);
while ($res_location_score = mysql_fetch_array($location_scores_res)) {
$location_scores_arr[] = intval($res_location_score['Score']);
}
if ($location_scores_arr[$i] != NULL) {
$divider = $divider + 1;
}
$cityscore = $cityscore + $location_scores_arr[$i];
//echo $location_id_arr[$i];
//echo $location_name_arr[$i]."<br>";
}
$total = $cityscore / $divider;
$city_qry = "SELECT `ID` as cityID, `name` as cityName FROM `territories` where `ID` = '" . $cityID_arr[$citycount] . "'";
$city_qry_rs = mysql_query($city_qry) or die($city_qry . "<br><br>" . mysql_error());
while ($city_name = mysql_fetch_array($city_qry_rs)) {
$cityname = $city_name['cityName'];
}
echo $cityname;
echo intval($total) . "%";
$total = 0;
$cityscore = 0;
unset($location_id_arr);
unset($location_name_arr);
$location_id_arr[] = array();
$location_name_arr[] = array();
unset($location_scores_arr);
$location_scores_arr[] = array();
$city_scores_arr [] = intval($total);
}
?>
The [] syntax is for adding an element to the end of an array; it's not valid for a variable you have just unset. Instead of trying to clear the array at the end of each iteration of the loop, you should be creating a new array at the beginning of each iteration, i.e.:
for ($citycount = 0; $citycount< $count; $citycount ++)
{
$location_id_arr = array();
$location_name_arr = array();
$location_scores_arr = array();
$loc_qry = "SELECT `ID` as LocationID, `name` as LocationName FROM `territories` where `formatID` = 43 and `territorylevelID` = 77 and `parentID` = '".$cityID_arr[$citycount]."'";
$loc_qry_res = mysql_query($loc_qry) or die($loc_qry."<br><br>".mysql_error());
...
}
I have a follow up question on something I got help with here the other day (No Table Three Column Category Layout).
The script is as follows:
$res = mysql_query($query);
$system->check_mysql($res, $query, __LINE__, __FILE__);
$parent_node = mysql_fetch_assoc($res);
$id = (isset($parent_node['cat_id'])) ? $parent_node['cat_id'] : $id;
$catalist = '';
if ($parent_node['left_id'] != 1)
{
$children = $catscontrol->get_children_list($parent_node['left_id'], $parent_node['right_id']);
$childarray = array($id);
foreach ($children as $k => $v)
{
$childarray[] = $v['cat_id'];
}
$catalist = '(';
$catalist .= implode(',', $childarray);
$catalist .= ')';
$all_items = false;
}
$NOW = time();
/*
specified category number
look into table - and if we don't have such category - redirect to full list
*/
$query = "SELECT * FROM " . $DBPrefix . "categories WHERE cat_id = " . $id;
$result = mysql_query($query);
$system->check_mysql($result, $query, __LINE__, __FILE__);
$category = mysql_fetch_assoc($result);
if (mysql_num_rows($result) == 0)
{
// redirect to global categories list
header ('location: browse.php?id=0');
exit;
}
else
{
// Retrieve the translated category name
$par_id = $category['parent_id'];
$TPL_categories_string = '';
$crumbs = $catscontrol->get_bread_crumbs($category['left_id'], $category['right_id']);
for ($i = 0; $i < count($crumbs); $i++)
{
if ($crumbs[$i]['cat_id'] > 0)
{
if ($i > 0)
{
$TPL_categories_string .= ' > ';
}
$TPL_categories_string .= '' . $category_names[$crumbs[$i]['cat_id']] . '';
}
}
// get list of subcategories of this category
$subcat_count = 0;
$query = "SELECT * FROM " . $DBPrefix . "categories WHERE parent_id = " . $id . " ORDER BY cat_name";
$result = mysql_query($query);
$system->check_mysql($result, $query, __LINE__, __FILE__);
$need_to_continue = 1;
$cycle = 1;
$column = 1;
$TPL_main_value = '';
while ($row = mysql_fetch_array($result))
{
++$subcat_count;
if ($cycle == 1)
{
$TPL_main_value .= '<div class="col'.$column.'"><ul>' . "\n";
}
$sub_counter = $row['sub_counter'];
$cat_counter = $row['counter'];
if ($sub_counter != 0)
{
$count_string = ' (' . $sub_counter . ')';
}
else
{
if ($cat_counter != 0)
{
$count_string = ' (' . $cat_counter . ')';
}
else
{
$count_string = '';
}
}
if ($row['cat_colour'] != '')
{
$BG = 'bgcolor=' . $row['cat_colour'];
}
else
{
$BG = '';
}
// Retrieve the translated category name
$row['cat_name'] = $category_names[$row['cat_id']];
$catimage = (!empty($row['cat_image'])) ? '<img src="' . $row['cat_image'] . '" border=0>' : '';
$TPL_main_value .= "\t" . '<li>' . $catimage . '' . $row['cat_name'] . $count_string . '</li>' . "\n";
++$cycle;
if ($cycle == 7) // <---- here
{
$cycle = 1;
$TPL_main_value .= '</ul></div>' . "\n";
++$column;
}
}
if ($cycle >= 2 && $cycle <= 6) // <---- here minus 1
{
while ($cycle < 7) // <---- and here
{
$TPL_main_value .= ' <p> </p>' . "\n";
++$cycle;
}
$TPL_main_value .= '</ul></div>'.$number.'
' . "\n";
}
I was needing to divide the resulting links into three columns to fit my html layout.
We accomplished this by changing the numbers in the code marked with "// <---- here".
Because the amount of links returned could be different each time, I am trying to figure out how to change those numbers on the fly. I tried using
$number_a = mysql_num_rows($result);
$number_b = $number_a / 3;
$number_b = ceil($number_b);
$number_c = $number_b - 1;
and then replacing the numbers with $number_b or $number_c but that doesn't work. Any ideas?
As mentioned before, you can use the mod (%) function to do that.
Basically what it does is to get the remainder after division. So, if you say 11 % 3, you will get 2 since that is the remainder after division. You can then make use of this to check when a number is divisible by 3 (the remainder will be zero), and insert an end </div> in your code.
Here is a simplified example on how to use it to insert a newline after every 3 columns:
$cycle = 1;
$arr = range (1, 20);
$len = sizeof ($arr);
for ( ; $cycle <= $len; $cycle++)
{
echo "{$arr[$cycle - 1]} ";
if ($cycle % 3 == 0)
{
echo "\n";
}
}
echo "\n\n";