counter in php when client press button - php

I have this part of code in php . when player press button in client (using ajax) I want my database show next record. but I won't.
if(isset($_POST['req'])){
$counter++;
$sql = "SELECT question FROM mytable WHERE id = $counter";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row["id"]." ". $row["question"]. " " . "<br>";
}
} else {
echo "0 results";
}
}

I would suggest storing your counter in a session. Then each time a player does this action you can give them the next row like so :-
session_start();
if(isset($_POST['req'])){
if ( ! isset($_SESSION['counter']) ) {
$_SESSION['counter'] = 1;
} else {
$_SESSION['counter'] = $_SESSION['counter'] + 1;
}
$sql = "SELECT question FROM mytable WHERE id = {$_SESSION['counter']}";
$result = $conn->query($sql);
if ( ! $result ) {
// log error to error log
error_log(print_r($conn->errorinfo(),true), 3, 'app_error.log');
echo "Temporary database issues, please try again later";
header('Location: error_page.php');
exit;
}
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
echo $row["id"]." ". $row["question"]. " " . "<br>";
} else {
echo "0 results";
}
}

The easy way is to send the current id along in the Ajax request. Increment it then use it to pull the next question from your database

Related

PHP new strings update in DB with unshift?

I have a problem to adding more strings in my database.
The idea is: SELECT information, then added array together, after these UPDATE to database.
These are in one code, but UPDATE not working with summed arrays only separately.
With echo I see the array_unshift is working well, the data is good, but not updating.
Need I change something on the server? Maybe version?
(I don't get mysqli_error!)
//CHECKBOX KIOLVASÁSA DB-BŐL!
$sql = ("SELECT id, checkbox FROM osszesito WHERE id = '$id'");
//$result = mysqli_query($conn, $sql);
//if (mysqli_num_rows($result) > 0) {
if ($result = mysqli_query($conn, $sql)) {
while($row = mysqli_fetch_assoc($result)) {
//EREDETI SOR LISTÁZÁSA
$original_array = array( $row["checkbox"] );
$x ="";
echo 'Eredeti sor: ';
foreach ($original_array as $x)
{
echo "$x "."<br><br>";
}
//EREDETI SOR KIEGÉSZÍTÉSE AZ ÚJ ADATTAL
array_unshift($original_array, $chb);
$last ="";
echo "Új sor: "."<br>";
foreach ($original_array as $last)
{
echo $last."<br>";
}
//ÚJ SOR FRISSÍTÉSE A DB-BEN!
//$sqla = "UPDATE osszesito SET checkbox = '$chb' WHERE id = '$id' ";
$sqla = "UPDATE osszesito SET checkbox = '$last' WHERE id = '$id' ";
if (mysqli_query($conn, $sqla)) {
echo "ÚJ SOR ELMENTVE!";
//header("Location: /megrendelesek/index.php");
} else {
echo "Hiba a beírás során: " . mysqli_error($conn);
}
}
///////////////////////////////////////////////
//LEZÁRÁS
} else {
echo "Jelenleg nincs megrendelés az adatbázisban!";
}
mysqli_close($conn);

data output from the database does not work

I have an authorization page, it works everything is ok, but when I log in I want to see additional data from the database for this user.
code
knocks out only one user and everything, when I exit the session and switch on as a new user, nothing is knocked out .... connection to the database works
session_start();
require ('vendor/connect.php');
$FIRSTNAME=$_SESSION['FIRSTNAME'];
$sql = "SELECT BIRTHDAY from users WHERE FIRSTNAME='$FIRSTNAME'";
$result = ibase_query($db, $sql);
if (ibase_fetch_row($result) > 0) {
while($row = ibase_fetch_assoc($result)) {
echo "You BIRTHDAY: " . $row["BIRTHDAY"]. " ";
}
} else {
echo "0 results";
}
Your code should be like below :
$sql = "SELECT BIRTHDAY from users WHERE FIRSTNAME='$FIRSTNAME'";
$result = ibase_query($db, $sql);
$row = ibase_fetch_row($result);
while ($row) {
echo $row[0] . "\t";
}

PHP is loading the same content endlessly

How can i prevent it from loading the same table row all over again and never stopping ? My head can't take it ... I know i somehow created an infinite loop so i searched on internet and i saw people doing almost the same but somehow it worked for them.
include_once "additional_code/dbh.inc.php";
session_start();
$savedUsername = $_SESSION["username"];
if (!isset($savedUsername) || empty($savedUsername)) {
header("location: login.php");
exit;
}
$sql = "SELECT * FROM messages WHERE sender = $savedUsername";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
if ($row > 0) {
echo "it works";
while($row) {
echo htmlspecialchars($row["sender"] . ": " . $row["msg"]);
echo "<br><br>";
}
}
else {
echo "It doesn't work";
}
?>
When you use
while($row) {
You are effectively creating an endless loop. Because $row is a defined variable, it's a turthy value - this makes it essentially become
while (true) {
What you want instead is to fetch each row, meaning that you must supply the mysqli_fetch_assoc() as the argument to your while. You also want to check the number of rows instead, as you are now fetching the first row (and it will not be visible in the loop).
if (mysqli_num_rows($result)> 0) {
echo "it works";
while($row = mysqli_fetch_assoc($result)) {
echo htmlspecialchars($row["sender"] . ": " . $row["msg"]);
echo "<br><br>";
}
}
else {
echo "It doesn't work";
}
You should also be aware that your code is vulnerable for SQL-injection attacks, and you should use prepared statements with MySQLi and bind your values instead of injecting the variables directly in your query.
How can I prevent SQL injection in PHP?
Change this:
$row = mysqli_fetch_assoc($result);
if ($row > 0)
{
echo "it works";
while($row)
{
echo htmlspecialchars($row["sender"] . ": " . $row["msg"]);
echo "<br><br>";
}
}
To this:
if (mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
echo htmlspecialchars($row["sender"] . ": " . $row["msg"]);
echo "<br><br>";
}
}
You can first count with mysqli_num_rows if your query contains any records or not and then can use mysqli_fetch_assoc if records are there like below:
$sql = "SELECT * FROM messages WHERE sender = $savedUsername";
$result = mysqli_query($conn, $sql);
$count = mysqli_num_rows($result);
if ($count > 0) {
echo "it works";
while($row = mysqli_fetch_assoc($result)) {
echo htmlspecialchars($row["sender"] . ": " . $row["msg"]);
echo "<br><br>";
}
}
Always use Prepared Statements to make Queries more Secure

How to make a PHP page have two "column" regions?

Basically I'm doing digital signage and I'm trying to get names to be pulled from a MySQL database to a PHP page. Right now its all centered in one column, but I want the results to be in two columns side by side. How can I do this?
$sql = "SELECT * FROM donor WHERE DonationAmount = 5000 AND Category = '1' or DonationAmount = 5000 AND Category IS NULL ORDER BY LastName ASC";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
// test if the DisplayName field is empty or not
if(empty($row['DisplayName']))
{
// it's empty!
if(empty($row['FirstName'])){
echo $row['LastName']. "<br>";
}
else{
echo $row["LastName"]. ", " . $row["FirstName"]. "<br>";
}
}else{
// Do stuff with the field
echo $row["DisplayName"]. "<br>";
}
}
} else {
}
Basically I want this data to be spread across two columns instead of 1 single page.
output the strings like this:
echo "<span style=\"width:50%;float:left;\">".$row['LastName']."</span>";
do not forget to remove <br /> from each output
You can use tables, and count the rows to determine if you need to start a new table row.
$i = 0;
$total_rows = $result->num_rows;
echo "<table><tr>";
while($row = mysqli_fetch_assoc($result)) {
// test if the DisplayName field is empty or not
echo "<td>";
if(empty($row['DisplayName']))
{
// it's empty!
if(empty($row['FirstName'])){
echo $row['LastName'];
}
else{
echo $row["LastName"]. ", " . $row["FirstName"];
}
}else{
// Do stuff with the field
echo $row["DisplayName"]. "";
}
echo "</td>";
$i++;
if($i % 2 == 0 && $i != $total_rows) {
echo "</tr><tr>";
}
}
echo "</tr></table>";
if your content is in <div id="myDiv"> use this JS function and call it after the content loads
function splitValues() {
var output = "";
var names = document.getElementById('myDiv').innerHTML.split("<br>");
for(var i in names) {
output += "<span style=\"width:50%;float:left;display:inline-block;text-align:center;\">"+names[i]+"</span>";
}
document.getElementById('myDiv').innerHTML = output;
}

If value in certain cell equals "Certain Text" echo "Text"

I'm trying to get this to echo a warning message when the cell contains a certain text like "0" or "N/A". It would work when there was no value entered in the first place, but I can't get it to echo when there is already a certain value. Any help would be great. Thanks!
<?php
$listing = "$_POST[listing]";
$sql = "SELECT open_house_attended FROM property_flyers WHERE street_property = '$listing' ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "</span><span class='report_bignumber'><br>". $row["open_house_attended"]."</span>";
}
} else {
echo "<br> ". $noresults . "</span>";
}
?>
You can use a little regex -
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
preg_match(trim($row["open_house_attended"]), '/[0]|[N\/A]/', $matches); // try to match '0' or 'N/A'
if(count($matches) == 0) { // do we have matches?
echo "</span><span class='report_bignumber'><br>". $row["open_house_attended"]."</span>";
} else {
echo "<br> ". $noresults . "</span>";
}
}
}
?>
Or you can go a little more directly -
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$ohCount = $row["open_house_attended"];
if(( $ohCount != '0') && ($ohCount != 'N/A')) { // do we have matches?
echo "</span><span class='report_bignumber'><br>". $ohCount ."</span>";
} else {
echo "<br> ". $noresults . "</span>";
}
}
}
?>
preg_match()
$sql = "SELECT open_house_attended FROM property_flyers WHERE street_property = '$listing' AND open_house_attended NOT IN ('0', 'N/A')";
use NOT IN and a list of values to reject. It's one option anyway. The preg match option works as well, just it asks php to do the work and this asks sql to do it.

Categories