Comparison for in SQL row selection not working? - php

This is the code that is not working:
$query = "SELECT * FROM $table WHERE text_id > '$last_id'"; //SELECT NEW MESSAGES
$result = mysqli_query($connection,$query);
if ($result && mysqli_num_rows($result) > 0)
{
//THIS SHOULD NOT BE RUNNING
}
I've verified over and over in phpMyAdmin and the text_id in the table and $last_id are both the integer value '1'. That being said, the condition equates to true every time the code runs.
Am I messing this code up, or is my thinking improper?
Here is entire script:
<?php
session_start();
$alias = $_SESSION['username'];
$host = 'localhost';
$user = '*';
$pass = '*';
$database = 'vethergen_db_accounts';
$table = 'table_messages';
$last_id_table = 'table_chat_sync';
$connection = mysqli_connect($host, $user, $pass) or die ("Unable to connect!");
mysqli_select_db($connection,$database) or die ("Unable to select database!");
$last_id_query = "SELECT alias FROM $last_id_table WHERE alias = '$alias'";
$last_id_result = mysqli_query($connection,$last_id_query);
$last_id_rows = mysqli_fetch_array($last_id_result);
if ($last_id_rows['alias'] === $alias)
{
$last_id = $last_id_rows['last_id'];
$query = "SELECT * FROM $table WHERE text_id > '$last_id'"; //SELECT NEW MESSAGES
$result = mysqli_query($connection,$query);
if ($result && mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
if ($row['alias'] === "Vether")
{
echo '<p id = "chat_text">'.'<b>'.$row['alias'].'</b>'.': '.$row['text']."</p>";
echo '<p id = "time_stamp">'.$row['time'].'</p>';
echo '<p id = "chat_number">'.$row['text_id'].'</p>';
}
else
{
echo '<p id = "chat_text">'.'<b class = "bold_green">'.$row['alias'].'</b>'.': '.$row['text']."</p>";
echo '<p id = "time_stamp">'.$row['time'].'</p>';
echo '<p id = "chat_number">'.$row['text_id'].'</p>';
}
echo '<hr class = "chat_line"></hr>';
$last_row_id = $row['text_id'];
}
}
//UPDATE LAST SYNC ID
$update_query = "UPDATE $last_id_table SET last_id = '$last_row_id' WHERE alias = '$alias'";
mysqli_query($connection,$update_query);
}
else
{
$update_query = "INSERT INTO $last_id_table (alias, last_id) VALUES('$alias','-1')";
mysqli_query($connection,$update_query);
}
?>

You should change ;
WHERE text_id > '$last_id'
to
WHERE text_id > $last_id
text_id column is integer and can't be compared like string.

Related

Group By Not working - only displaying 1st entry

I have over 40'000 entries and each is assigned to a "list_name"
I am basically trying to get just the list_name value echo'd out
$groupq = mysqli_query($dbc, "SELECT * FROM `products-full` GROUP BY `list_name`");
$groupr = mysqli_fetch_assoc($groupq);
do {
echo $groupr['list_name'];
} while($groupr = mysqli_fetch_assoc($groupq));
however its only displaying 1 entry then no more ..
https://imgur.com/a/3rnXGet
Try this.
$groupq = mysqli_query($dbc, "SELECT * FROM `products-full` GROUP BY `list_name`");
while($groupr = mysqli_fetch_assoc($groupq)){
echo $groupr['list_name'];
}
$database = "sample" //replace your database name here
$conn=new mysqli("localhost","root","",$database); // here username is root and password is null , change it according to yours
if($conn->connect_error)
{
echo $conn->connect_error;
die("sorry database connection failed");
}
$sql = "SELECT * FROM products-full GROUP BY list_name";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row['list_name'];
}
}
thats it
try this
$groupq = mysqli_query($dbc, "SELECT list_name, count(*) FROM `products-full` GROUP BY
`list_name`");
while($groupr = mysqli_fetch_assoc($groupq)) {
echo $groupr['list_name'];
}

How to properly update a SQL table row using PHP

Current update: I've cleaned up the code, and there are still some issues.
NOTE this code runs every 3 seconds. The outermost 'else' statement seems to run, setting the time to 0 in the database table, but then there is no activity.
After the initial time of running, the outermost 'else' statement should never run, and the time value stored under the user's alias should keep updating with the latest time stamp, but it just sits at '0'.
This is the JS that runs the php file:
//CHECK FOR NEW CHAT MESSAGES
setInterval(function()
{
$.post("chat_update.php", function(data) { $("#rect_comments_text").append(data);} );
}, 3000);
Code:
<?php
session_start();
$alias = $_SESSION['username'];
$host = 'localhost';
$user = '*';
$pass = '*';
$database = 'vethergen_db_accounts';
$table = 'table_messages';
$time_table = 'table_chat_sync';
$connection = mysqli_connect($host, $user, $pass) or die ("Unable to connect!");
mysqli_select_db($connection,$database) or die ("Unable to select database!");
$timestamp = time();
$last_time_query = "SELECT alias FROM $time_table";
$last_time_result = mysqli_query($connection,$last_time_query);
$last_time_rows = mysqli_fetch_array($last_time_result);
if ($last_time_rows['alias'] === $alias)
{
$last_time = $last_time_rows['time'];
$query = "SELECT * FROM $table WHERE time > $last_time ORDER BY text_id ASC"; //SELECT NEW MESSAGES
$result = mysqli_query($connection,$query);
//APPEND NEW MESSAGES
while($row = mysqli_fetch_array($result))
{
if ($row['alias'] === "Vether")
{
echo '<p id = "chat_text">'.'<b>'.$row['alias'].'</b>'.': '.$row['text']."</p>";
echo '<p id = "time_stamp">'.$row['time'].'</p>';
echo '<p id = "chat_number">'.$row['text_id'].'</p>';
}
else
{
echo '<p id = "chat_text">'.'<b class = "bold_green">'.$row['alias'].'</b>'.': '.$row['text']."</p>";
echo '<p id = "time_stamp">'.$row['time'].'</p>';
echo '<p id = "chat_number">'.$row['text_id'].'</p>';
}
echo '<hr class = "chat_line"></hr>';
}
//UPDATE LAST SYNC TIME
$update_query = "UPDATE $time_table SET time = '$timestamp' WHERE alias = '$alias'";
mysqli_query($connection,$update_query);
}
else
{
echo '<p> HERE </p>';
$update_query = "INSERT INTO $time_table (alias, time) VALUES('$alias','0')";
mysqli_query($connection,$update_query);
}
?>
You try this
$sql_update = "UPDATE time_table SET time= '$timestamp' WHERE alias = '$alias'";
if ($con->query($sql_update ) === TRUE) {
}
else{
echo "Error: " . $sql_update . "<br>" . $con->error;
}
You need to only check mysqli_num_rows to whether to insert or update data. You have to add ' around $alias in select query also. change your code as below:
//EITHER UPDATE THE EXISTING VALUE OR CREATE ONE FOR FIRST TIME VISITORS...
$last_time_query = "SELECT * FROM $time_table WHERE alias = '$alias'"; //change here add '
$last_time_result = mysqli_query($connection,$last_time_query);
if (mysqli_num_rows($last_time_result) == 0) //Only check number of rows
{
$update_query = "INSERT INTO $time_table (alias, time) VALUES('$alias','$timestamp')";
mysqli_query($connection,$update_query);
}
else
{
$update_query = "UPDATE $time_table SET time = '$timestamp' WHERE alias = '$alias'";
mysqli_query($connection,$update_query);
}

php mysql trying to use empty to only add a new record in table if a primary key exists in a different table

I am trying to only allow a submission via the form only if a party_id exists in a table using empty, here is my code at the moment it is still allowing everything through even if there is no party_id.
Any help would be great.
if($_SERVER["REQUEST_METHOD"]== "POST") {
$party_id = (int)$_POST["partyid"];
$name = $_POST["name"];
$date = $_POST["date"];
$length = (int)$_POST["length"];
$sql = "SELECT * FROM `party` WHERE `party_id`='" . $party_id . "'";
$res = mysqli_query($link, $sql);
if(empty($party_id)) { #Were any records found?
print '<p>No Parties with that ID found! please press the back button to select another party</p>';
} else {
$record = mysqli_fetch_assoc($res);
$party_name = $record["party_name"];
$price = $record["price"];
$cost = $price * $length;
$bookable = true;
$sql2 = "SELECT * FROM `reservations`" or die("Unable to connect to database");
A simpler way might be to just check if the query returned any results like this.
if($_SERVER["REQUEST_METHOD"]== "POST") {
$party_id = (int)$_POST["partyid"];
$name = $_POST["name"];
$date = $_POST["date"];
$length = (int)$_POST["length"];
$sql = "SELECT * FROM `party` WHERE `party_id`='$party_id'";
$res = mysqli_query($link, $sql);
if ( mysqli_num_rows($res ) == 0 ) {
print '<p>No Parties with that ID found! please press the back button to select another party</p>';
} else {
$record = mysqli_fetch_assoc($res);
$party_name = $record["party_name"];
$price = $record["price"];
$cost = $price * $length;
$bookable = true;
$sql2 = "SELECT * FROM `reservations`" or die("Unable to connect to database");

Simplify php code - connect to a database

Here I have a php code that connects to a database, selects a row by id and creates an associative array from this row using a while loop. Do I have to write this code over and over again to create arrays from other rows by id? Maybe there is a chance to simplify this php code somehow? Please look at my code. BTW I am new in php...
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db = '_erica';
$conn = new mysqli($dbhost, $dbuser, $dbpass,$db);
$sql1 = "SELECT * FROM pics WHERE id = 1;";
$sql2 = "SELECT * FROM pics WHERE id = 2;";
$sql3 = "SELECT * FROM pics WHERE id = 3;";
$sql4 = "SELECT * FROM pics WHERE id = 4;";
$sql5 = "SELECT * FROM pics WHERE id = 5;";
$sql6 = "SELECT * FROM pics WHERE id = 6;";
$result1 = $conn->query($sql1);
$result2 = $conn->query($sql2);
$result3 = $conn->query($sql3);
$result4 = $conn->query($sql4);
$result5 = $conn->query($sql5);
$result6 = $conn->query($sql6);
while($row1 = $result1->fetch_assoc()) {
$bcgrnd = $row1["link"];
}
while($row2 = $result2->fetch_assoc()) {
$recipes = $row2["link"];
}
while($row3 = $result3->fetch_assoc()) {
$header = $row3["link"];
}
while($row4 = $result4->fetch_assoc()) {
$menu = $row4["link"];
}
while($row5 = $result5->fetch_assoc()) {
$beauty = $row5["link"];
}
while($row6 = $result6->fetch_assoc()) {
$kids = $row6["link"];
}
?>
You can do this in one query:
$sql = "SELECT * FROM pics WHERE id IN (1,2,3,4,5,6);";
$result = $conn->query($sql);
And then you can loop over all results like this:
$data = array();
while ($row = $result->fetch_assoc()) {
$id = $row["id"];
$link = $row["link"];
$data[$id]["link"] = $link;
// add more fields if you want
}
To access for example the link of ID 1, just do:
$data[1]["link"];
You can write one or two simple functions for this. Moreover, please note that your code is vulnerable to SQL Injection. Here is an example how you can achieve this with some simple functions:
<?php
function DB() {
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db = '_erica';
return new mysqli($dbhost, $dbuser, $dbpass,$db);
}
function query($id) {
$query = "SELECT * FROM `pics` WHERE `id` = $id";
return DB()->query($query);
}
$result = query(1); // will fetch records for ID 1
while($row = $result->fetch_assoc()) {
$bcgrnd = $row["link"];
}
$result = query(2); // will fetch records for ID 2
while($row = $result->fetch_assoc()) {
$bcgrnd = $row["link"];
}
?>
By adapting this approach, you can fetch data for a specific ID. If you don't like this solution, consider using MySQL IN clause.
Try this.
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db = '_erica';
$conn = new mysqli($dbhost, $dbuser, $dbpass,$db);
$sql = "SELECT * FROM pics WHERE id IN (1,2,3,4,5,6);";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
$bcgrnd[$row["id"]][] = $row["link"];
}
?>
Why not try a Query and Limit it to 6 results, it takes up less resources just pulling 6 results:
SELECT * FROM `pics` ORDER BY `[PRIMARY KEY]` LIMIT 6
MySQL in() function finds a match in the given arguments, you can use it
select pics where id IN(1,2,3,4,5,6)

Cant base64 decode from mysqli

I'm currently trying to echo information from my SQL database which I had to encode in order for it to efficiently write into the table; now when I try to echo the information, WHILE decoding it, the page displays nothing, I'm not entirely sure what I'm doing wrong at this point.
<?php
$type = $_SESSION['SESS_ACC_TYPE'];
$login = $_SESSION['SESS_LOGIN_NAME'];
$log = base64_decode(''.$row['log'].'');
if ($type == '2') {
$qry = "SELECT log FROM logs ";
$result = mysqli_query($GLOBALS["___mysqli_ston"], $qry);
while($row = mysqli_fetch_assoc($result)){
echo ''.$log.'';
}
}
if ($type == '1') {
$qry = "SELECT log FROM logs WHERE login = '.$login.'";
$result = mysqli_query($GLOBALS["___mysqli_ston"], $qry);
while($row = mysqli_fetch_assoc($result)){
echo ''.$log.'';
}
} else {
//do nothing
}
?>
There are many errors with your code:
I fixed them.
$type = $_SESSION['SESS_ACC_TYPE'];
$login = $_SESSION['SESS_LOGIN_NAME'];
if ($type == '2') {
$qry = "SELECT `log` FROM `logs`;";
}
if ($type == '1') {
$qry = "SELECT `log` FROM `logs` WHERE `login` = '" . $login . "';";
}
$result = mysqli_query($GLOBALS["___mysqli_ston"], $qry);
while($row = mysqli_fetch_assoc($result)) {
echo base64_decode($row['log']);
}
since mysql 5.6.1 there are mysql base64 decode/encode functions
select FROM_BASE64('....') ...
select TO_BASE64('....') ...
http://base64decode.net/mysql-from-base64

Categories