Show result count after while loop - php

I am trying to show the points outside whileloop. I am fetching result like this.
Facebook
Twitter,Facebook,Instagram,Youtube
Facebook
Facebook
It fetches Facebook from each row and count no of times in the end.
<?php
$q = "select * FROM users";
$r = mysql_query($q);
$total = mysql_num_rows($r);
while($row = mysql_fetch_assoc($r)) {
$fb= $row['social'];
$dbreq = implode(',',explode(',', $fb));
$fa=array("Twitter,",",Instagram,","Youtube");
$newstring = str_replace($fa, "", $dbreq);
echo $points= count(explode(',', $newstring));
}
?>

Please try like this,
<?php
$q = "select * FROM users";
$r = mysql_query($q);
$total = mysql_num_rows($r);
$cnt =0 ;
while($row = mysql_fetch_assoc($r)) {
$fb= $row['social'];
if (strpos($fb,'facebook') !== false) {
$cnt++;
}
}
echo "TOTAL:".$cnt;
?>

Related

PHP if statements being ignored

I'm new to PHP and SQL. I'm trying to make a rule so that it will only show certain information for certain pages. The code I'm using is
include 'dbh-login.php';
$id = $_GET['id'];
$i = 1;
while ($i != 100) {
$sql = "SELECT * FROM ui_off WHERE id='$i'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
if ($row['link'] = $id) {
echo $row['title']."<br>";
}
$i++;
}
The if statement seems to have no effect on weather the script echoes the title or not.
You are missing == assignment. Here is the working code.
$id = $_GET['id'];
$i = 1;
while ($i != 100) {
$sql = "SELECT * FROM ui_off WHERE id='$i'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
if ($row['link'] == $id) {
echo $row['title']."<br>";
}
$i++;
}
Your code does not make any sense.
You are using a while loop and looping in it 100 times just to check if 1 row have the given id.
Why don't you search directly for the id? Your code will be cleaner and you will free some memory on the server by deducting 100 queries each time the page is opened.
$id = $_GET['id'];
$sql = "SELECT * FROM ui_off WHERE id!='100' AND link='$id'" ;
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
if ($row['link'] != '') {
echo $row['title']."<br>";
}

how to encode json from array push?

i had this php code :
<?php
include "../mainmenu/koneksi.php";
// Start with the list of animals
$sql = "SELECT * FROM data_binatang";
$rows = array();
$res = mysql_query($sql);
for($i=0; $i<mysql_num_rows($res); ++$i){
$row1 = mysql_fetch_assoc($res);
$id_binatang = $row1['id_binatang'];
$sql = "SELECT * FROM data_waktu_vaksinasi WHERE id_binatang = $id_binatang AND (status_vaksin = 'belum' OR status_vaksin IS NULL) ORDER BY tanggal_vaksin ASC LIMIT 1";
$res2 = mysql_query($sql);
$row2 = mysql_fetch_assoc($res2);
$arr[$id_binatang] = array();
array_push($arr[$id_binatang], $row1['nama_binatang'], $row1['id_user'], $row1['jenis_binatang'], $row1['ras_binatang'], $row1['foto_binatang'], $row2['nama_vaksin'], $row2['id_data_waktu_vaksinasi'], $row2['status_vaksin'], $row2['tanggal_vaksin'], $row2['tanggal_datang']);
}
echo "RESULT:";
echo "<table border=1><tr><th>id binatang</th><th>nama binatang</th><th>id user</th><th>jenis binatang</th><th>ras binatang</th><th>foto binatang</th><th>nama vaksin</th><th>id data waktu vaksin</th><th>status vaksin</th><th>tanggal vaksin</th><th>tanggal datang</th></tr>";
foreach($arr as $key => $val){
echo "<tr><td>$key</td><td>".implode("</td><td>", $val)."</td></tr><br>";
}
?>
and here's the result
now i want to generate the table into json, but i don't know what to put inside the json encode, i tried:
echo '{"data_vaksinasi_menu":'.json_encode($arr[$id_binatang]).'}';
but instead it gave me null
Try this:
echo json_encode(array('data_vaksinasi_menu' => $arr));

Returning mysqli results outside of function

Given the following code:
function fetchData($mysqli){
$sql = "select * from `test`";
$result = mysqli_query($mysqli,$sql);
return $result;
}
$result = fetchData($mysqli);
while($row = mysqli_fetch_array($result)){
echo $row['id'];
}
My code is obviously more complicated than this. It loops itself until it yields some results changing some variables at each iteration.
$result is empty. What am I doing wrong? Thank you!
FULL CODE:
function fetchItem($itemID, $period, $mysqli){
$periodArray = array('7', '30', '60', '90', '180');
while (current($periodArray) !== $period) next($periodArray);
$currentPeriod = current($periodArray);
$sql = "SELECT * from `test` where `period` = '$period'";
$result = mysqli_query($mysqli,$sql);
$row_count = $result->num_rows;
if($row_count < 5){
$currentPeriod = next($periodArray);
fetchItem($itemID, $currentPeriod, $mysqli);
} else if($row_count >= 5){
$currentPeriod = current($periodArray);
$rows = array();
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
// var_dump($rows); <-- returns all results
return $rows;
}
}
$output = fetchItem($itemID, $period, $mysqli);
echo '<pre>';
print_r($output); <-- NULL
echo '</pre>';
As you can see if I don't get results for a given period it moves onto the next one.
Your code should be:
function fetchData($mysqli){
$sql = "select * from `test`";
$init = mysqli_query($mysqli, $sql);
$result = $init->fetch_array(MYSQLI_ASSOC);
return $result;
}
$result = fetchData($mysqli);
foreach($result as $row){
echo $row['id'];
}

$i not incrementing in while loop

Following is my PHP code which is only giving i =0 though in a loop I am incrementing the $i but it always return i as 0 and while loop is only working one time, though my query SELECT * FROM events WHERE DATE(event_date) < CURDATE() is returning 7 records when exectuing in phpmyadmin. Let me know what i am doing wrong here ?
Code -
<?php
include_once $_SERVER['DOCUMENT_ROOT'].'/app/'."config.php";
error_reporting(E_ALL);
if( $_POST['number'] == 'all' ) {
$eventArr = array();
$myarray = array();
$query = "SELECT * FROM events WHERE DATE(`event_date`) < CURDATE()";
$result = mysql_query($query);
$i =0;
while($row = mysql_fetch_assoc($result)) {
$eventArr[$i] = array('event_data'=> $row);
// Get image For an event
$event_id = $row['id'];
$query = "SELECT * FROM event_images WHERE event_id = $event_id ORDER BY `uploaded_date` DESC LIMIT 0,1";
$result = mysql_query($query);
$eventImgArr = array();
while($row = mysql_fetch_assoc($result)) {
$eventImgArr[] = $row;
}
$eventArr[$i]['event_image'] = $eventImgArr;
// Get venue details for the event
$venue_id = $row['venue_id'];
$eventVenArr = array();
$query = "SELECT * FROM `venues` WHERE id = $venue_id";
while($row = mysql_fetch_assoc($result)) {
$eventVenArr[] = $row;
}
$eventArr[$i]['venue_detail'] = $eventVenArr;
echo $i, " -- ";
$i++;
}
$myarray = array('response'=>'1','message'=>'Event data', 'data'=>$eventArr);
echo json_encode($myarray);
return;
}
You are re-using the $result variable for the other queries, which is destroying its value needed for the main loop.
P.S. Also, you're not actually executing the query for the venue details.

function call inside a function in php not working

This code is a function calling a function in php. The function call is never called.
function saveSubject(){
$result = mysql_query("select * from term where description='".$_POST['term']."'");
$row = mysql_fetch_array($result, MYSQL_NUM);
global $term;
$term = $row[0];
$x=1;
while(isset($_POST['subCode'.$x])and isset($_POST['subTitle'.$x]) and isset($_POST['subUnit'.$x])){
$code = $_POST['subCode'.$x];
$title = $_POST['subTitle'.$x];
$unit = $_POST['subUnit'.$x];
$query = "INSERT INTO subject(subcode, description, units, termid)
VALUES('".$code."','".$title."',".$unit.",".$term.")";
$result = mysql_query("SELECT * from subject where subcode='".$code."'");
if(mysql_num_rows($result) > 0){
$message = "Subject Code : ".$code;
prompt($message);
}else{
mysql_query($query);
savePre($code, $x);
}
$x++;
}
}
function savePre($code, $y){
$pre = mysql_query("SELECT subject.subcode from subject left join term
on term.termid=subject.termid
left join curriculum on term.termid = curriculum.curriculumid
where term.courseid =".$_POST['course']);
while($row = mysql_fetch_array($pre, MYSQL_NUM)){
$c = $row[0].$y;
if(isset($_POST[$c])){
$result = mysql_query("Select * from pre_requisite where pre_requisites=".$row[0]."and subject=".$code);
if(mysql_num_rows($result) > 0){
$message = "";
}else{
mysql_query("INSERT into pre_requisites(pre_requisite, subject)
values (".$row[0].", ".$code.")");
}
}
}
}
Calling function savePre() in saveSubjec() but the calling is not working. I cannot find out what is wrong. Please help!
Simple...
You code is
$query = "INSERT INTO subject(subcode, description, units, termid)
VALUES('".$code."','".$title."',".$unit.",".$term.")";
$result = mysql_query("SELECT * from subject where subcode='".$code."'");
if(mysql_num_rows($result) > 0)
{
$message = "Subject Code : ".$code;
prompt($message);
}else{
mysql_query($query);
savePre($code, $x);
}
from above code you can imagine that you are inserting record to database and then selecting that record using subcode match where condition so it will always return 1 as output so your else condition will never get execute.
That's the reason why you are not able to call savePre function.
You want to define savePre() function above the saveSubject() function. Use this.
function savePre($code, $y)
{
$pre = mysql_query("SELECT subject.subcode from subject left join term
on term.termid=subject.termid
left join curriculum on term.termid = curriculum.curriculumid
where term.courseid =".$_POST['course']);
while($row = mysql_fetch_array($pre, MYSQL_NUM))
{
$c = $row[0].$y;
if(isset($_POST[$c]))
{
$result = mysql_query("Select * from pre_requisite where pre_requisites=".$row[0]."and subject=".$code);
if(mysql_num_rows($result) > 0){
$message = "";
}else{
mysql_query("INSERT into pre_requisites(pre_requisite, subject)
values (".$row[0].", ".$code.")");
}
}
}
}
function saveSubject()
{
$result = mysql_query("select * from term where description='".$_POST['term']."'");
$row = mysql_fetch_array($result, MYSQL_NUM);
global $term;
$term = $row[0];
$x=1;
while(isset($_POST['subCode'.$x])and isset($_POST['subTitle'.$x]) and isset($_POST['subUnit'.$x]))
{
$code = $_POST['subCode'.$x];
$title = $_POST['subTitle'.$x];
$unit = $_POST['subUnit'.$x];
$result = mysql_query("SELECT * from subject where subcode='".$code."'");
if(mysql_num_rows($result) > 0){
$message = "Subject Code : ".$code;
prompt($message);
}
else
{
$query = "INSERT INTO subject(subcode, description, units, termid)
VALUES('".$code."','".$title."',".$unit.",".$term.")";
mysql_query($query);
savePre($code, $x);
}
$x++;
}
}

Categories