While-function for mysqli_fetch_assoc is infinite - php

I have two HTML pages inside a session. On my first page, I want to create an array, which is saved in a $_SESSION variable. On the second page, I want to display my array.
PHP code for my first page looks like that:
<?php
include ("../script/db_connect.php");
$select_questions = 'select * from questions ';
if (isset($_POST["own"]) && $_POST["own"] == "No") {
$select_questions .= 'where creator != '
. $_SESSION["id"];
}
$select_questions .= 'limit 3';
$questions_result = mysqli_query($con, $select_questions);
$_SESSION["questions"] = mysqli_fetch_assoc($questions_result);
mysqli_close($con);
?>
PHP code on my second page looks like that:
<?php while ($array = $_SESSION["questions"]) {
echo $array["question"]; } ?>
When I go to second page, an infinite loop is displayed, where only the first element of my array is displayed over and over again. What is the reason for that? I cannot find any mistake in my code.

Change this
$_SESSION["questions"] = mysqli_fetch_assoc($questions_result);
to (here we fetch all rows from the sql result, not only one)
while($row=mysqli_fetch_assoc($questions_result)) $_SESSION["questions"][] = $row;
And later do
foreach($_SESSION["questions"] as $quest) { echo $quest["question"]; }

Related

Json_encode not print anything

I'm building a PHP page, that return a list of items from my database. So I can't see any record because I think that the script go in overflow.
This is my script
<?php
ini_set('memory-limit','-1');
set_time_limit(0);
require_once('lib/connection.php');
$query_Articolo = "SELECT CodArticolo,NomeArticolo,Quantita,CodiceBarre, PrezzoAttuale, PrezzoRivenditore,PrezzoIngrosso
FROM VistaArticoli";
$result_Articoli = $connectiondb->query($query_Articolo);
//I HAVE JUST INSERT THIS LINE CODE
$answer[] =array();
while($row_Articoli = $result_Articoli->fetch_assoc()) {
$answer[] =array("id"=>$row_Articoli['CodArticolo'],"nome"=>$row_Articoli['NomeArticolo'],
"quantita"=>$row_Articoli['Quantita'],"codiceBarre"=>$row_Articoli['CodiceBarre']
,"codartFornitore"=>$row_Articoli['CodiceBarre'], "PrezzoAttuale"=>$row_Articoli['PrezzoAttuale'],
"prezzoRivenditore"=>$row_Articoli['prezzoRivenditore'],"prezzoIngrosso"=>$row_Articoli['prezzoIngrosso']);
}
//echo "risposta";
echo json_encode($answer);
?>
If I try tu call this page, I can't see any record. If I add at the query "limit 500" I can see the result.
How can I change the code?

Foreach: Proper way to add line breaks (paragraph) for specified number of rows

I have a bunch of random sentences in a mysql database and I have no issue pulling them out and displaying them using the code below, but, I'm stumped on this next process.
How can add nl or encapsulate in tags for every X number of rows? The selected rows are already limited to 14 (arbitrary) and my goal is to take those 14 rows and add a line break every 3 or 4 (also arbitrary) so they're more fluid looking paragraphs.
<?php
include $_SERVER['DOCUMENT_ROOT'] . '/dbConnect.php';
$q = $dbc->query("SELECT DISTINCT sentence FROM sentences ORDER BY rand() LIMIT 14");
while($r = $q->fetch_array(MYSQLI_ASSOC)):
foreach($r as $value) {
$value = str_replace('$keyword', '<b>replaced keyword</b>', $value);
echo $value." ";
}
endwhile;
?>
The code above works great for doing this:
Sample Output:
This is a complete sentence that I'm outputting to the page.
This is a complete sentence that I'm outputting to the page.
This is a complete sentence that I'm outputting to the page.
This is a complete sentence that I'm outputting to the page.
This is a complete sentence that I'm outputting to the page.
This is a complete sentence that I'm outputting to the page.
This is a complete sentence that I'm outputting to the page.
However, I'd like it to do something more like this without creating an inefficient 3 blocks of the same code with limits for 3, 2, and 4 or similar.
This is a complete sentence that I'm outputting to the page.
This is a complete sentence that I'm outputting to the page.
This is a complete sentence that I'm outputting to the page.
This is a complete sentence that I'm outputting to the page.
This is a complete sentence that I'm outputting to the page.
This is a complete sentence that I'm outputting to the page.
This is a complete sentence that I'm outputting to the page.
This is a complete sentence that I'm outputting to the page.
This is a complete sentence that I'm outputting to the page.
I guess this is what you are looking for:
<?php
include $_SERVER['DOCUMENT_ROOT'] . '/dbConnect.php';
$i=0; $j=0;
$seq=array(3, 2, 4);
$q = $dbc->query("SELECT DISTINCT sentence FROM sentences ORDER BY rand() LIMIT 14");
while($r = $q->fetch_array(MYSQLI_ASSOC)):
foreach($r as $value) {
$value = str_replace('$keyword', '<b>replaced keyword</b>', $value);
echo $value."<br>";
if($i==$seq[$j])
{
echo "<br>";
$j++;
$i=0;
if($j==count($seq)) $j=0;
} else {
$i++;
}
}
endwhile;
?>
Hope it helps!
Here's my approach to your question:
$numberOfSentencesPerParagraph = 4; // specify
$totalNumberOfSentences = 14; // or use a count function to calculate the number of returned MySQL records // or make this equal to a new variable you will introduce in your SQL query (after `LIMIT`)
while($r = $q->fetch_array(MYSQLI_ASSOC)):
$theCounter = 1;
foreach($r as $value) {
$value = str_replace('$keyword', '<b>replaced keyword</b>', $value);
echo $value." ";
$theCounter++;
if(($theCounter % $numberOfSentencesPerParagraph) == 0){
echo "<br>";
}
}
endwhile;
It simply runs a 'counter' and when its value is a multiple of the variable $numberOfSentencesPerParagraph, it echoes out a line break.

Array_Push not adding to end of array, it is replacing the whole array

I have tried to create a small 'bookmarking' feature for my website. Users are able to click on the ".bookmarkButton" which will execute the following script:
<!--Add To Bookmarks-->
$(".bookmarkButton").click(function() {
var pid=$(this).closest('div').attr('id');
$('#noBookmark').hide();
$.post('bookmarks/addBookmark.php', 'rid=' + pid, function (addBookmark) {
$("#bookmarkResults").add(addBookmark);
});
});
Here is the code for "addBookmark.php":
<?php
session_start();
if (isset($_SESSION['ridArray']) && count($_SESSION['ridArray'] > 0)){
addBookmark();
} else if (isset($_POST['rid']) && !isset($_SESSION['ridArray'])) {
$_SESSION['ridArray'] = array();
addBookmark();
}
function addBookmark() {
if (is_array($_SESSION['ridArray']) && isset($_SESSION['ridArray']) && isset( $_POST['rid']) ) {
array_push($_SESSION['ridArray'], $_POST['rid']); //push the id value from post to the session array
//$_SESSION['ridArrayClean'] = array_unique($_SESSION['ridArray']); //remove duplicates
print_r($_SESSION['ridArray']);
foreach($_SESSION['ridArray'] as $x) {
// Get all the data from the "example" table
$result = mysql_query("SELECT * FROM example WHERE id = $x")
or die(mysql_error());
$row = mysql_fetch_array( $result );
echo $row['productname'];
}}}
?>
The variable $_SESSION['ridArray'] holds the array with all the id's that have been accumulated.
My problem is that this script works only when one item is bookmarked. When there is more than one product bookmarked, I only get the product name that was last bookmarked and not every thing that I've bookmarked.
So for example instead of getting multiple product id's after clicking the bookmarkButton class like this: 0,1,2,3 in the array. I only get the one that was clicked last i.e. 6.
I've been looking into this for a while now and I can't seem to see what I'm doing wrong.
The script only echos the productnames, if you posted a "rid".
Also you could write the if like this:
if (isset($_SESSION['ridArray'], $_POST['rid']) && is_array($_SESSION['ridArray'])) {
Checking isset() first. Also you could additionally check for
... && count($_SESSION['ridArray'] > 0)
I do not think that your session starts automatically (is it possible to set its autostart in php.ini, but it does not by default), so
<?php
session_start();
Other thoughts:
SELECT * FROM example WHERE id = $x
Have you ever heard about SQL Injection?
ps: no need in secondary check (they are checked before) and from the first condition follows the second one
is_array($_SESSION['ridArray']) && isset($_SESSION['ridArray'])
I would write it as
<?php
session_start();
if (isset($_POST['rid'])) {
addBookmark(intval($_POST['rid']));
}
function addBookmark($rid) {
$_SESSION['ridArray'][] = $rid;
$_SESSION['ridArray'] = array_unique($_SESSION['ridArray']);
foreach($_SESSION['ridArray'] as $x) {
$result = mysql_query("SELECT * FROM example WHERE id = '$x'")
or die(mysql_error());
$row = mysql_fetch_array( $result );
echo $row['productname'];
}
}
?>

Adding commas to a loop within a loop

I'm trying to create a list using a loop within a loop. I have 3 tables.
T1: faculty
T2: keywords
T3: facID, keywordID
I've created a select statement to cross join the rows and spit out something like this:
Faculty Name A
keyword-a keyword-b keyword-c
Faculty Name B
keyword-a keyword-d keyword-f
Everything works great except I need to add commas to the keyword list and my code isn't doing the trick. My keywords are still looping through without the comma.
<?php while ($row = mysql_fetch_assoc($result)) { ?>
<?php if ($row['facID'] !== $lastID ) { ?>
<?php echo $row['facname']; ?><br />
<?php $lastID = $row['facID']; ?>
<?php } ?>
<?php $kwords = array();
foreach($row as $k => $v) {
if (strpos($k, 'kword') === 0) {
$kwords[] = $v;
}
}
echo implode(', ', $kwords);
} ?>
Any suggestions? I'm a noob and I'm hoping it's something very obvious!
There seem to be a few issues with your code, so I'll try to address them all.
First, you have a lot of opening and closing <?php> tags, and it's really messing with the readability of your code. Consider keeping as much code as possible contained into a single <?php> code block. For example, instead of this:
<?php if ($row['facID'] !== $lastID ) { ?>
<?php echo $row['facname']; ?><br />
<?php $lastID = $row['facID']; ?>
<?php } ?>
...you can consolidate all of that PHP code into this:
<?php
if ($row['facID'] !== $lastID ) {
echo $row['facname'] . "<br />";
$lastID = $row['facID'];
}
?>
Next, you're not outputting any sort of visual break after echoing out your implode()ed array. This would lead to the next heading being output on the same line as the output of your previous heading. For example, your first two headings will end up like this:
Faculty Name A
keyword-a keyword-b keyword-cFaculty Name B
keyword-a keyword-d keyword-f
Notice how Faculty Name B is at the end of the line of keywords?
Finally, I think the problem you're reporting is that you're getting two keywords that are linked together. For example, if you had two rows of data with the same facility id, one with keywords keyword-a and keyword-b and another with keyword-c and keyword-d, you would see that output visually without a comma between keyword-b and keyword-c.
In other words, instead of this:
keyword-a, keyword-b, keyword-c, keyword-d
...you're instead seeing this:
keyword-a, keyword-bkeyword-c, keyword-d
This is also caused by the lack of a visual break between implodeed lines, but I believe the problem is deeper than that. I believe you want all keywords for a given facility to be shown on a single line, not broken across multiple lines. For that, you need to move where you reinitialize your array so that it gets reinitialized at the same time you switch to a new heading. Try something like this:
$kwords = array();
while ($row = mysql_fetch_assoc($result)) {
if ($row['facID'] !== $lastID ) {
if ($kwords) {
echo implode(", ", $kwords) . "<br />";
$kwords = array();
}
echo $row['facname'] . "<br />";
$lastID = $row['facID'];
}
foreach($row as $k => $v) {
if (strpos($k, 'kword') === 0) {
$kwords[] = $v;
}
}
}
if ($kwords) {
echo implode(", ", $kwords);
}
echo "<br />";
This still isn't the best code, but you can refactor it.
The idea here is that the array gets output and reset every time the facility changes, so that the array encompasses all keywords for that facility and they all get output together, rather than being reported only as part of the database row they were returned with. After the loop completes, you have to manually report the last row since the usual reporting is taken care of within the loop.

setting a link on a while loop php

$query = mysql_query("SELECT * FROM mailtbl WHERE fromuser = '$adminsess' AND sent = '1'");
echo "To Subject Date View message";
while($fetch = mysql_fetch_assoc($query)) {
$mid = $fetch['mid'];
$to = $fetch['touser'];
$subject2 = $fetch['subject'];
$message2 = $fetch['message'];
$date2 = $fetch['datesent'];
$rand = $fetch['rand'];
$view = "<a href = 'messages.php?mode=".$sent."&view=".$rand."'>View message</a>";
echo "$to$subject2$date2$view";
}
echo "</table>";
if (isset($view)) {
$viewget = $_GET['view'];
if ($viewget== $rand) {
echo "hi";
echo "$message2";
}
}
The $view there suppose to open the content of each message. The main problem is, if I have multiple values in the table, after clicking the link in each row in the table, the only link that is functioning is in the last row. The previous rows in the table with links doesn't show the content of the message (which is echo "hi" & echo "$message2";).
What exactly is wrong with my code? thanks.
Your code to display the message is outside the while loop. If you want it to run for every message, then put it in the loop that is iterating over every message.
The problem is that $rand is not set inside the isset($view) check. $rand still contains the last value from the while loop above, so only the last $viewget/$rand will work.
My guess is that messages.php shows all available messages (the message list) and if clicked on one message, the message list and that selected message.
So first, before the while loop, you fetch the message identifier of the message to be shown:
$ViewRequested = isset($_GET['view']) ? $_GET['view'] : -1;
$ViewRequestedData = NULL;
Next, inside the while loop, you check if the user is allowed to view the selected message, and remember the record:
if ($rand == $ViewRequested) {
$ViewRequestedData = $fetch;
}
Finally, after the while loop, you check whether there is a valid message requested:
if (is_array($ViewRequestedData) {
echo $ViewRequestedData['message2'];
}

Categories