How to get the next row in mysqli result? - php

I want to get the next row in a cycle of a mysql result to write a list with the next and previous element code like this example:
<?php $previous = null;
$next = null;
while ($row = $result->fetch_assoc()) {
$next = ??????????????? // how to get it?
?>
<li code="<?php echo $row['code']; ?>" previous="<?php echo $previous; ?>" next="<?php echo $next; ?>">Hello world!</li>
<?php
$previous = $row['code']; // previous is easy to get...
} ?>

Not sure with MySQLi but here is how I do it in PDO:
$data = $stmt->fetchAll(\PDO::FETCH_ASSOC);
for($i = 0; $i < count($data); $i++) {
$next = isset($data[$i+1]) ? $data[$i+1] : null;
}
if there is no fetchAll in mysqli then do:
while ($row = $result->fetch_assoc()) {
$data[] = $row;
}
if ( ! empty($data)) {
for($i = 0; $i < count($data); $i++) {
$next = isset($data[$i+1]) ? $data[$i+1] : null; // next
$prev = isset($data[$i-1]) ? $data[$i-1] : null; // previous
$curr = isset($data[$i]) ? $data[$i] : null; //current
}
}

How about something on the lines of this:
SELECT * FROM table WHERE id > '$currentID' ORDER BY id LIMIT 1;
to get the single next possible row.

Look at this solution, what do you think about it? it works, but will be more slow? this algorithm requires at least double pass or not? what do you think?
$db = DB::getConnection();
$result = $db->query( "SELECT * FROM objects" );
$next = null;
$previous = null;
$temp_previous = null;
$print = false;
$row = null;
$fetchit = false;
$code = null;
echo "<ul>";
while (true)
{
if ($print) {
if ($fetchit) {
$row = $result->fetch_assoc();
$next = $row['code'];
}
echo "<li code='$code' next='$next' previous='$previous'>{$row['description']}</li>" . endl();
$previous = $temp_previous;
$print = false;
}
else {
if (!$fetchit)
$row = $result->fetch_assoc();
$code = $row['code'];
$temp_previous = $row['code'];
$print = true;
$fetchit = true;
}
if(!is_array($row)) break;
}
echo "</ul>";

Related

While loop doesn't wait before displaying

In this code section, the query gets all the teachers and appends their assigned classes within the object
The weird thing is it works perfectly on local but not online, it is almost it doesn't wait for the while loop
<?php
$SID = mysqli_real_escape_string($con, htmlspecialchars($_POST["SID"], ENT_QUOTES));
$allTeachersArr = [];
$test = [];
$q = "SELECT onderwysers.*,klasse.Klas,klasse.Datum,klasse.Vak FROM `onderwysers` LEFT JOIN klasse ON onderwysers.ID = klasse.Teacher WHERE `SID` = '$SID'";
// echo $q;
$result = $con->query($q);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$subjectItem = new stdClass();
$filtered_array = [];
$isIn = false;
$var1 = $row['ID'];
$var2 = $row['Teacher'];
if (count($allTeachersArr) > 0)
foreach ($allTeachersArr as $item) {
if ($item->ID == $var1 && $item->Teacher == $var2) {
// do something
$filtered_array = $item;
$isIn = true;
}
}
if ($isIn == true) {
$notAdd = false;
// echo "updates";
$subjectItem->Klas = $row["Klas"];
$subjectItem->Datum = $row["Datum"];
$subjectItem->Vak = $row["Vak"];
foreach ($filtered_array->displaySubjects as $item) {
if ($item->Klas == $row["Klas"] && $item->Vak == $row["Vak"] && $item->Datum == $row["Datum"]) {
// do something
$filtered_array = $item;
$notAdd = true;
}
}
if ($notAdd == false) {
$temp = $filtered_array->displaySubjects;
array_push($temp, $subjectItem);
$filtered_array->displaySubjects = $temp;
}
} else {
//add new entry
$subjectItem->ID = $row["ID"];
$subjectItem->Title = $row["Title"];
$subjectItem->Name = $row["Name"];
$subjectItem->Surname = $row["Surname"];
$subjectItem->Afkorting = $row["Afkorting"];
$subjectItem->IdentityNumber = $row["IdentityNumber"];
$subjectItem->Geslag = $row["Geslag"];
$subjectItem->ContactDetails = $row["ContactDetails"];
$subjectItem->Email = $row["Email"];
$subjectItem->RegKlas = $row["RegKlas"];
$subjectItem->Status = $row["Status"];
$subjectItem->UID = $row["UID"];
$subjectItem->displaySubjects = [];
array_push($allTeachersArr, $subjectItem);
}
}
}
echo json_encode($allTeachersArr);
$con->close();
THE EXPECTED RETURNED DATA(This is local, online returns nothing)

How to save multiple results in the array with for loop php

I'm working with a CSV file. when the user uploads the file. I parse the CSV then select the data from the array that I need. after that, I'm running a for loop to validate that data and saving the results in the array. but the problem is when I print the results array there's only result for 1 email and there are 4 emails. any suggestions?
$results = [];
$valid_emails = 0;
$invalid_emails = 0;
for ($i = 0; $i < $csv_array['row_count']; $i++) {
$email = $csv_array['data'][$i][$email_column];
$result = validate_email($email);
$results['Email'] = $email;
if ($result) {
$results['Result'] = 'valid';
$valid_emails++;
} else {
$results['Result'] = 'invalid';
$invalid_emails++;
}
}
echo '<pre>';
print_r($results);
echo '</pre><br>';
echo $valid_emails . '<br>';
echo $invalid_emails . '<br>';
Use $results[] to add one or more elements :
$results = [];
$valid_emails = 0;
$invalid_emails = 0;
for ($i = 0; $i < $csv_array['row_count']; $i++) {
$email = $csv_array['data'][$i][$email_column];
$result = validate_email($email);
$res['Email'] = $email;
if ($result) {
$res['Result'] = 'valid';
$valid_emails++;
} else {
$res['Result'] = 'invalid';
$invalid_emails++;
}
$results[] = $res;
}
echo '<pre>';
print_r($results);
echo '</pre><br>';
echo $valid_emails . '<br>';
echo $invalid_emails . '<br>';
You are overriding results every time in your loop, try this
$results = [];
$valid_emails = 0;
$invalid_emails = 0;
for ($i = 0; $i < $csv_array['row_count']; $i++) {
$email = $csv_array['data'][$i][$email_column];
$rowResult=[];
$result = validate_email($email);
$rowResult['Email'] = $email;
if ($result) {
$rowResult['Result'] = 'valid';
$valid_emails++;
} else {
$rowResult['Result'] = 'invalid';
$invalid_emails++;
}
$results[]=$rowResult;
}
echo '<pre>';
print_r($results);
echo '</pre><br>';
echo $valid_emails . '<br>';
echo $invalid_emails . '<br>';
$results contains only the last email validation.
You should store multiple results, and not only the last ;-)
Something like :
$results[$i]['Email'] = $email;
if ($result) {
$results[$i]['Result'] = 'valid';
$valid_emails++;
} else {
$results[$i]['Result'] = 'invalid';
$invalid_emails++;
}
if ($result) {
$results[$i] = 'valid';
$valid_emails++;
} else {
$results[$i] = 'invalid';
$invalid_emails++;
}

PHP look-and-say sequence

I'm trying to code Conway look-and-say sequence in PHP.
Here is my code:
function look_and_say ($number) {
$arr = str_split($number . " ");
$target = $arr[0];
$count = 0;
$res = "";
foreach($arr as $num){
if($num == $target){
$count++;
}else{
$res .= $count . $target;
$count = 1;
$target = $num;
}
}
return $res;
}
As I run the function, look_and_say(9900) I am getting value I expected: 2920.
My question is for assigning $arr to be $arr = str_split($number) rather than $arr = str_split($number . " "), the result omits the very last element of the $arr and return 29.
Is it normal to add empty space at the end of the $arr foreach to examine the last element or is there any better way to practice this code - besides regex way.
There are 2 methods I was able to come up with.
1 is to add concatenate at the result after the loop too.
function look_and_say ($number) {
$arr = str_split($number);
$target = $arr[0];
$count = 0;
$res = "";
foreach($arr as $num){
if($num == $target){
$count++;
}else{
$res .= $count . $target;
$count = 1;
$target = $num;
}
}
$res .= $count . $target;
return $res;
}
And the 2nd one is to add another if clause inside the loop and determine the last iteration:
function look_and_say ($number) {
$arr = str_split($number);
$target = $arr[0];
$count = 0;
$res = "";
$i=0;
$total = count($arr);
foreach($arr as $num){
if($i == ($total-1))
{
$count++;
$res .= $count . $target;
}
elseif($num == $target){
$count++;
}else{
$res .= $count . $target;
$count = 1;
$target = $num;
}
$i++;
}
return $res;
}
I want to suggest you other way using two nested while loops:
<?php
function lookAndSay($number) {
$digits = str_split($number);
$result = '';
$i = 0;
while ($i < count($digits)) {
$lastDigit = $digits[$i];
$count = 0;
while ($i < count($digits) && $lastDigit === $digits[$i]) {
$i++;
$count++;
}
$result .= $count . $lastDigit;
}
return $result;
}

explode/implode from database php

I'm want string out of the column data.
But it failed.
<?php
$conn = mysql_connect("localhost", "nantawat", "12345678") or die(mysql_error());
$select_db = mysql_select_db("my_db", $conn) or die(mysql_error());
$select_tbl = mysql_query("SELECT * FROM log", $conn);
while ($fetch = mysql_fetch_object($select_tbl)) {
$r = $fetch->data;
$i = explode(",", $r);
if (!isset($i[1])) {
for ($j = 0; $j <= 200; $j++) {
$i[$j] = null;
}
}
$name = $i[0];
$mama = $i[1];
$no = $i[2];
$a = $i[3];
$b = $i[4];
echo $name . "</br>";
echo $mama . $no . $a . $b . "</br>";
}
while ($data = mysql_fetch_object($select_tbl)) {
echo $data->data . "<br>";
}
?>
But i want output =
bus
car
bike
aabus
car
bike
aabus
car
bike
aabus
ddd
ee
And i not
Notice: Undefined offset: 3 in C:\xampp\htdocs\logs\New folder
(2)\explode.php on line 21
Notice: Undefined offset: 4 in C:\xampp\htdocs\logs\New folder
(2)\explode.php on line 22
Thank You.
You should just do what you want to do.
You want to connect to database then do it:
$conn = mysql_connect("localhost", "nantawat", "12345678") or die(mysql_error());
I suggest you to use mysqli library instead of mysql (mysql is deprecated in new php versions and totally removed in php7)
$conn = mysqli_connect("localhost", "nantawat", "12345678", "my_db") or die(mysql_error());
You want to query on log table, then do it:
$select_tbl = mysqli_query($conn, "SELECT * FROM log");
You want to fetch info from your result, then do it:
while ($row = mysqli_fetch_array($select_tbl)) {
echo $row['id_user'];
echo $row['id_doc'];
echo $row['date'];
echo $row['data'];
}
You want to explode data, then do it:
while ($row = mysqli_fetch_array($select_tbl)) {
echo $row['id_user'];
echo $row['id_doc'];
echo $row['date'];
$data = explode(',', $row['data']);
foreach ($data as $d) {
if ($d !== '') { // because before first comma or after last can be empty
echo $d . PHP_EOL;
}
}
}
If you want to save database result in variables:
If you are getting only one row of database, you can save them in variables directly:
$id_user = '';
$id_doc = '';
$date = '';
$data = array();
id ($row = mysqli_fetch_array($select_tbl)) {
$id_user = $row['id_user'];
$id_doc = $row['id_doc'];
$date = $row['date'];
$tempData = explode(',', $row['data']);
foreach ($tempData as $d) {
if ($d !== '') {
$data[] = $d;
}
}
}
And if you have multiple rows of database you need to save them all in a total array:
$array = array();
id ($row = mysqli_fetch_array($select_tbl)) {
$id_user = $row['id_user'];
$id_doc = $row['id_doc'];
$date = $row['date'];
$data = array();
$tempData = explode(',', $row['data']);
foreach ($tempData as $d) {
if ($d !== '') {
$data[] = $d;
}
}
$array[] = array(
'id_user' => $id_user,
'id_doc' => $id_doc,
'date' => $date,
'data' => data,
);
}
And finally use this to see what structure your final array has:
echo '<pre>';
pront_r($array);
echo '</pre>';
First off it is not wise to store comma seperated values in a single cell and you are using deprecated mysql_ functions. I think your solution can be found in using a foreach instead of the isset part:
while ($fetch = mysql_fetch_object($select_tbl)) {
$r = $fetch->data;
$i = explode(",", $r);
foreach ($i as $q){
echo $q . '<br/>';
}
}
If you still want to access your variables $name, $mama, $no and $ab, you can use isset for those specifically.
while ($fetch = mysql_fetch_object($select_tbl)) {
$r = $fetch->data;
$i = explode(",", $r);
if (isset($i[0])){
$name = $i[0];
echo $name . '<br>'; //only echo if it exists
}
if (isset($i[1])){
$mama= $i[1];
echo $mama. '<br>'; //only echo if it exists
}
//try it yourself for $no and $ab
}
Try:
while ($row = mysqli_fetch_array($select_tbl)) {
extract($row);
/* Using extract method can get the array key value as variable
Below variables are available
$id_user;
$id_doc;
$date;
$data; */
}

PHP: JSON Returning NULL Values

I am currently working on a search function for my site and I returning the results in JSON. However, some values are returning after returning the first results like the following:
{"fullname":"test name","occupation":"test","industry":"testing","bio":"i am testing stuff.","gender":"f","website":"http:\/\/yhisisasite.com","skills":["writing","reading","math","coding","baseball"],"interests":["coding","sampling","googling","typing","playing"]},{"fullname":null,"occupation":null,"industry":null,"bio":null,"gender":null,"website":null,"skills":["coding","docotrs","soeku","spelling"],"interests":["testing","wintro","skating","hockey","code"]}
I currently have a class to work as a template for the results which looks like this:
class SearchResultUserProfile {
public $fullname = "";
public $occupation = "";
public $industry = "";
public $bio = "";
public $gender = "";
public $website = "";
public $skills = array();
public $interests = array();
}
Then to populate those fields I have a few loops during the mysqli fetch:
while ($row = mysqli_fetch_array($result))
{
$max = sizeof($user_id_array);
for($i = 0; $i < $max; $i++)
{
//create a new instance or object
$searchResultUserProfile = new SearchResultUserProfile();
$searchResultUserProfile->fullname = $row['fullname'];
$searchResultUserProfile->occupation = $row['occupation'];
$searchResultUserProfile->industry = $row['industry'];
$searchResultUserProfile->bio = $row['bio'];
$searchResultUserProfile->gender = $row['gender'];
$searchResultUserProfile->website = $row['website'];
//grab the interests and skills
$skillDetails = fetchAllUserSkills($user_id_array[$i]);
foreach($skillDetails as $row) {
$thistest = $row['skills'];
array_push($searchResultUserProfile->skills, $thistest);
}
$interestDetails = fetchAllUserInterests($user_id_array[$i]);
foreach($interestDetails as $row) {
$thistests = $row['interests'];
array_push($searchResultUserProfile->interests, $thistests);
}
array_push($results, $searchResultUserProfile);
}
echo json_encode($results);
}
Any idea why this is happening? Is it how I am iterating through the loop or the set up? I am sure I am overlooking something simple but I cannot figure out what it is.
The problem is that you are overwriting your $row variable in the inner loops:
while ($row = mysqli_fetch_array($result))
^^^^ this is a result row from your query
{
$max = sizeof($user_id_array);
for($i = 0; $i < $max; $i++)
{
$searchResultUserProfile = new SearchResultUserProfile();
$searchResultUserProfile->fullname = $row['fullname'];
...
foreach($skillDetails as $row) {
^^^^ here you are overwriting your query result
...
}
...
}
echo json_encode($results);
}
So if $max is more than 1, from the second iteration on you will be using the last result of your last inner loop. And that will not be the result from the query that you expect it to be.

Categories