Mark as read/unread button data sheet php/mysql [closed] - php

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I'm new to coding and I'm using php and mysql to make a admin panel to show clients data from a form.
Now I want to make a button to show wether the data has been processed or not.
The idea is, I have a column named star and if star == read that display "green" and if star =! read display "red".
Then if the button is pressed, if star == read update to unread but if star =! read update to read.
I have the button like this:
<td>star</td>
And read.php like this:
<?php
include("db.php");
$id = $_GET['id'];
$query = "UPDATE users SET star='read' WHERE id = '$id'";
mysqli_query($link, $query) or die('Database error!');
header('location:admin_main.php');
?>
This just updates the row to read and doesn't have the ability to become unread again.
But I don't know how to formulate the if statements.
If anyone has any suggestions, that is much appreciated.
EDIT
To show a bit of what I tried:
I added a new column to the data sheet:
<td>".$star."</td>
And then I tried to use the code below to check the database:
$query = "SELECT star FROM users";
$selectie = mysqli_query($link, $query) or die($query."<br>".mysql_error());
if($selectie == 'read') {
$star = 'read';
} else {
$star = 'unread';
}
And for the read.php:
<?php
include("inc/verbinden.php");
$id = $_GET['id'];
$query = "SELECT star FROM users";
$selectie = mysqli_query($link, $query) or die($query." <br>".mysql_error());
if($selectie == 'read') {
$query = "UPDATE users SET star='unread' WHERE id = '$id'";
mysqli_query($link, $query) or die('Database error!');
} else {
$query = "UPDATE users SET star='read' WHERE id = '$id'";
mysqli_query($link, $query) or die('Database error!');
}
header('location:admin_main.php');
?>
But I realize that the if/else is wrong.

You're almost there. What you missed is looping over (successful) results, such as using a while loop for instance:
Side note: I added (int) for the GET array which helps to safeguard against a possible SQL injection and corrected the use of mysql_error(). That api does not intermix with the mysqli_* api.
<?php
include("inc/verbinden.php");
if(!empty($_GET['id'])){
$id = (int)$_GET['id'];
}else{
echo "The GET array is empty.";
exit; // Stops further execution.
}
$query = "SELECT star FROM users";
$selectie = mysqli_query($link, $query) or die($query." <br>".mysqli_error($link));
while($row = mysqli_fetch_array($selectie)){
if($row['star'] == 'read') {
$query = "UPDATE users SET star='unread' WHERE id = '$id'";
mysqli_query($link, $query) or die('Database error!'); // use mysqli_error($link)
}else{
$query = "UPDATE users SET star='read' WHERE id = '$id'";
mysqli_query($link, $query) or die('Database error!'); // use mysqli_error($link)
}
}
header('location:admin_main.php');
exit; // Stops further execution.
Note: You could substitute mysqli_fetch_array() with mysqli_fetch_assoc().
Also, it's best to use mysqli_affected_rows() when using UPDATE in order to get actual truthness.
You can read up on those functions:
http://php.net/manual/en/mysqli-result.fetch-array.php
http://php.net/manual/en/mysqli-result.fetch-assoc.php
http://php.net/manual/en/mysqli.affected-rows.php
One thing to note though is that read and Read, as well as unread and Unread are two different animals. So make absolutely sure that those are indeed the values in your database as well is what is going in the database.

Related

PHP I have a database connect file, should i put my database querie functions in the same file [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
to explain my question better, i have two files: dbh.inc.php
$dbServername = "localhost";
$dbUsername = "xxxxx";
$dbPassword = "secret";
$dbName = "databasename";
$conn = mysqli_connect($dbServername, $dbUsername, $dbPassword, $dbName);
mysqli_set_charset($conn,"utf8");
if (!$conn) {
die("Connection failed: ".mysqli_connect_error());
}
$table1 = "users";//1
$table2 = "userprofile";//2
$table3 = "twofactorauth";//3
And: database-query.func.php
function selectdb($data, $values, $url) {
include ('dbh.inc.php');
extract($data);
extract($values);
switch ($data['table']) {
case '1':
$table = $table1;
break;
case '2':
$table = $table2;
break;
case '3':
$table = $table3;
break;
}
$sql = "SELECT $rows FROM $table WHERE $where;";
print_r($sql);
die();
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
mysqli_stmt_close($stmt);
mysqli_close($conn);
header("Location: ".$url."?error=sqlerror");
die();
} else {
$amount = str_repeat('s', count($values));
$values = array_values($values);
mysqli_stmt_bind_param($stmt, $amount, ...$values);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$getResult = mysqli_fetch_assoc($result);
mysqli_stmt_close($stmt);
mysqli_close($conn);
$new = array_push($getResult, 'true');
return $getResult;
}
}
So the first holds database connection, and the latter has dynamic querys for insert, update and select for the moment. And i am wondering should i combine the two files, to one. Since every time i need my connect i always use one of my querys and same on the other way around?
Also 2 bonus questions: as you see in my connect file i have my table names and i use numbers in my other files and in the functions connect numbers to names.
Lastly should i use PDO, why?
To answer your question in general - yes, you can put a helper function in the same file where sql connection is made.
However, the code of your actual function is questionable at the very least. Or, to tell you truth, your function selectdb() is a torture for a programmer and shouldn't be stored anywhere. Stick to natural SQL queries written as is. You don't need numbers to represent tables. You don't need $rows variable. Everything could be written right in the SQL string. All you will need is a simple helper function that would reduce the amount of code required to run a query.
Here is an example of such mysqli include file
Once it's included in in your script, you can use it to run any mysql query, to any table, with any list of variables. Check out the following example (you can copy and paste the following code block to your file and run it as is):
<?php
require 'mysqli.php';
#Create a temporary table
$conn->query("CREATE temporary TABLE tmp_mysqli_helper_test
(id int auto_increment primary key, name varchar(9))");
# populate it with sample data
$sql = "INSERT INTO tmp_mysqli_helper_test (name) VALUES (?),(?),(?)";
$stmt = prepared_query($conn, $sql, ['Sam','Bob','Joe']);
echo "Affected rows: $stmt->affected_rows\n";
echo "Last insert id: $conn->insert_id\n";
# Getting rows in a loop
$sql = "SELECT * FROM tmp_mysqli_helper_test WHERE id > ?";
$res = prepared_query($conn, $sql, [1])->get_result();
while ($row = $res->fetch_assoc())
{
echo "{$row['id']}: {$row['name']}\n";
}
# Getting one row
$id = 1;
$sql = "SELECT * FROM tmp_mysqli_helper_test WHERE id=?";
$row = prepared_query($conn, $sql, [$id])->get_result()->fetch_assoc();
echo "{$row['id']}: {$row['name']}\n";
# Update
$id = 1;
$new = 'Sue';
$sql = "UPDATE tmp_mysqli_helper_test SET name=? WHERE id=?";
$affected_rows = prepared_query($conn, $sql, [$new, $id])->affected_rows;
echo "Affected rows: $affected_rows\n";
# Getting an array of rows
$start = 0;
$limit = 10;
$sql = "SELECT * FROM tmp_mysqli_helper_test LIMIT ?,?";
$all = prepared_query($conn, $sql, [$start, $limit])->get_result()->fetch_all(MYSQLI_ASSOC);
foreach ($all as $row)
{
echo "{$row['id']}: {$row['name']}\n";
}
As you can see, a proper helper function can keep all the flexibility and readability of SQL and reduce the amount of code at the same time.

Can't delete a row from MySQL [duplicate]

This question already has answers here:
How can I get useful error messages in PHP?
(41 answers)
Closed 4 years ago.
I have a problem with a project made with PHP and MySQL.
I want to delete a row from my document but I can't.
It's very strange because when I click my button delete, he goes to index.php but it doesn't delete the row from the database.
if(isset($_POST['delete'])){
$sql = "DELETE FROM account WHERE idAccount = '".$id."'";
$result = $conn->query($sql);
header("location: index.php");
}
Try this, you have inserted ' after ".$id."
if(isset($_POST['delete'])){
$sql = "DELETE FROM account WHERE idAccount = ".$id."";
$result = $conn->query($sql);
header("location: index.php");
}
or
if(isset($_POST['delete'])){
$sql = "DELETE FROM account WHERE idAccount = '".$id."'";
$result = $conn->query($sql);
header("location: index.php");
}
As #nico-haase already mentioned your statement is wrong:
$sql = "DELETE FROM account WHERE idAccount = ".$id."'";
evaluates to (check the trailing quote):
DELETE FROM account WHERE idAccount = NUMBER'
Additionally I agree #ramraider that it's one big sql injection here. You should sanitise your input at minimum (int $_POST['id']) or use PDO at best.

Function/Trigger already in use?

Im having problems getting an update function to work. The function marks badges as seen so that they are hidden from a notification window.
The function is called when the user clicks a button to mark them as seen.
I have two triggers on the table its trying to update which I think may be causing the problem.
The problem is : Can't update table 'users' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.
Triggers:
Function:
function markAsSeen() {
require "connect.php";
$seen = mysqli_query($connection,"Update userbadges
INNER JOIN users ON users.id = userbadges.user_id
SET seen='1'
WHERE studentid = '".$_SESSION["studentid"]."' && seen=0") or die(mysqli_error($connection));
while ($data = mysqli_fetch_array($seen)) {
echo 'Done';
}
}
Is there any way around this?
Your issue is that the update_users_trigger trigger makes changes to the contents of the table users, while the query that is triggering the execution of this trigger also uses the table users.
You will need to adjust your query so that this deadlock doesn't occur. It isn't clear which fields are from each table, but I suspect that in your initial query you need to join on users so that you can query on studentid.
You could create a different function to get the userID that you need something like the following:
require_once "connect.php";
function getUserIDFromStudentID($student_id, mysqli $connection)
{
$query = 'SELECT id FROM users WHERE studentid = ? LIMIT 1';
$stmt = $connection->prepare($query);
// Replace the below s to an i if it's supposed to be an integer
$stmt->bind_param("s", $student_id);
$stmt->execute();
$result = $stmt->get_result();
$record = $result->fetch_object();
$result->free();
if ($record) {
return $record->id;
}
}
function markAsSeen(mysqli $connection) {
$user_id = getUserIDFromStudentID($_SESSION["studentid"], $connection);
if (! $user_id) {
throw new Exception('Unable to get user id');
}
$seen_query = 'UPDATE userbadges SET seen = 1 WHERE user_id = ? and seen = 0';
$stmt = $connection->prepare($seen_query);
// Replace the below s to an i if it's supposed to be an integer
$stmt->bind_param("s", $user_id);
$result = $stmt->execute();
if (! $result) {
die(mysqli_error($connection));
}
echo 'Done';
}
Passing the connection object around rather than requiring a global file to be required every time will allow for more flexibility.

Check if an user is in a database

I have developed a game with Javascript and when the user finishes it, I must save his record in a database. Here you see the code:
$temp = $_POST['playername']; //username
$text = file_get_contents('names.txt'); //list with all usernames
//this text file contains the names of the players that sent a record.
$con=mysqli_connect("localhost","username","pass","my_mk7vrlist");
if (stripos(strtolower($text), strtolower($temp)) !== false) {
//if the username is in the list, don't create a new record but edit the correct one
mysqli_query($con, "UPDATE `my_mk7vrlist`.`mk7game` SET `record` = '".$_POST['dadate']."' WHERE `mk7game`.`playername` = ".$temp." LIMIT 1 ");
} else {
//The username is not in the list, so this is a new user --> add him in the database
mysqli_query($con, "INSERT INTO `mk7game` (`playername`,`record`,`country`,`timen`) VALUES ('".$_POST['playername']."', '".$_POST['dadate']."', '".$_POST['country']."', '".$_POST['time_e']."')");
file_put_contents("names.txt",$text."\n".$temp);
//update the list with this new name
}
//Close connection
mysqli_close($con);
When I have a new user (the part inside my "else") the code works correctly because I have a new row in my database.
When the username already exists in the list, it means that this player has already sent his record and so I must update the table. By the way I cannot edit the record on the player that has alredy sent the record.
mysqli_query($con, "UPDATE `my_mk7vrlist`.`mk7game` SET `record` = '".$_POST['dadate']."' WHERE `mk7game`.`playername` = ".$temp." LIMIT 1 ");
It looks like this is wrong, and I can't get why. I am pretty new with PHP and MySQL.
Do you have any suggestion?
You're missing quotes around $temp in the UPDATE statement:
mysqli_query($con, "UPDATE `my_mk7vrlist`.`mk7game`
SET `record` = '".$_POST['dadate']."'
WHERE `mk7game`.`playername` = '".$temp."'
^ ^
LIMIT 1 ") or die(mysqli_error($con));
However, it would be better to make use of prepared statements with parameters, rather than inserting strings into the query.
Escape your user input!
$temp = mysqli_real_escape_string($con, $_POST['playername']);
Make sure to stick your mysqli_connect() above that
$select = mysqli_query($con, "SELECT `id` FROM `mk7game` WHERE `playername` = '".$temp."'");
if(mysqli_num_rows($select))
exit("A player with that name already exists");
Whack that in before the UPDATE query, and you should be good to go - obviously, you'll need to edit it to match your table setup

seat reservation not working

I've been doing a lot of research but I guess I still didn't find the answers. This is a seat reservation and I'm not so good in php and mysql. So here's my code:
reservation.php code:
<?php
mysql_connect("localhost","root","") or die (mysql_error());
mysql_select_db('seat_reservation') or die (mysql_error());
$insert = mysql_query("INSERT INTO reservation (chair_status, room_id, chair_number) VALUES (0, 400, 05)");
?>
</td>
<div id="popupContact">
<a id="popupContactClose">x</a>
<center><form method = "POST" action="reserve.php">
<?php
$query = mysql_query("SELECT chair_status FROM reservation WHERE room_id = '400' AND chair_number = '05'");
while($row = mysql_fetch_array($query)) {
$_SESSION['roomno'] = $row['room_id'];
$_SESSION['chairnum'] = $row['chair_number'];
}
?>
reserve.php code:
<?php
$name = $_POST['student_name'];
$stud_id = $_POST['stud_id'];
$room_id = $_SESSION['roomno'];
$chair_num = $_SESSION['chairnum'];
mysql_connect("localhost", "root", "") or die (mysql_error());
mysql_select_db('seat_reservation') or die (mysql_error());
$query = mysql_query("SELECT chair_status FROM reservation WHERE room_id = '$room_id' AND chair_number = '$chair_num'");
if($query == 0)
{
$insert = mysql_query("UPDATE reservation SET chair_status = 1, student_name = '$name', stud_id = '$stud_id' WHERE room_id = '$room_id' AND chair_number = '$chair_num'");
}
else
die ("Sorry, seat taken! <br />Redirecting...<meta http-equiv='refresh' content=2;reservation.php>");
?>
my problem is that, when I reserve a seat, it tells me that the seat is taken even if the chair_status field is 0. When I checked the DB, it successfully inserted with chair_status of 0. I don't know which part is wrong. I really need your help, thank you!
In reservation.php, you SELECT only chair_status but then try to access $row['room_id'] and $row['chair_number']: neither are in the resultset. However, both are already known since they were fixed in the WHERE clause of the query, therefore one could use those values without resorting to the MySQL query.
Even if you wanted to use such a query to set the $_SESSION variables, it is daft to loop over the resultset overridding those variables with each result. Better to LIMIT the query and use only one resulting record.
However, you probably wanted to output form elements rather than set $_SESSION variables in order that the user can then choose which of the available seats they wish to reserve? In which case, you probably meant to include chair_status = 0 in your filter criteria.
The return value of the mysql_query function is a resource identifier; comparing this against 0 in reserve.php is probably not what you had intended. Perhaps you wanted mysql_num_rows instead?
Please stop writing new code with the ancient MySQL extension: it is no longer maintained and the community has begun the deprecation process. Instead you should use either the improved MySQLi extension or the PDO abstraction layer.
Please avoid putting variables (and especially those which come from your user) into your SQL, which makes you vulnerable to SQL injection. You should instead use prepared statements, with which your variables can be passed to MySQL as parameters that do not get evaluated for SQL. Read about Bobby Tables for more information.
You probably mean if (mysql_num_rows($query) == 0) {. The way it is your are checking if there is an error with the query, not the number of rows returned. Check the docs for more information.
Also, this might be optional, but use braces to enclose your else statement. And it might be better to use mysqli instead of mysql_... functions as mentioned in your comments. Or just escape the user input before adding it to the query string.
use mysql_num_rows for checking if records exist..
$query = mysql_query("SELECT chair_status FROM reservation WHERE room_id = '$room_id' AND chair_number = '$chair_num'");
$rows = mysql_num_rows($query);
if($rows == 0)
{
$insert = mysql_query("UPDATE reservation SET chair_status = 1, student_name = '$name', stud_id = '$stud_id' WHERE room_id = '$room_id' AND chair_number = '$chair_num'");
}

Categories