Update tinyint(1) - php

I would like to update the status value -tinyint(1)- to activate and deactivate the user. Whenever I try to update I keep getting the message below which set to "Attendant update failed." Any help is appreciate it. Thanks
if (empty($errors)) {
// Perform Update
$id = $attendant["id"];
$status = mysql_prep($_POST["status"]);
$query = "UPDATE attendant SET ";
$query .= "status = '{$status}', ";
$query .= "WHERE id = {$id} ";
$query .= "LIMIT 1";
$result = mysqli_query($connection, $query);
if ($result && mysqli_affected_rows($connection) == 1) {
// Success
$_SESSION["message"] = "Attendant updated.";
redirect_to("activate_attendant.php");
} else {
// Failure
$_SESSION["message"] = "Attendant update failed.";
}
}
} else {
// This is probably a GET request
}

Remove the trailing comma in status = '{$status}', <=
MySQL would have thrown you an error by doing:
$result = mysqli_query($connection, $query) or die(mysqli_error($connection));
I would also like to note that your present code is open to SQL injection.
Use prepared statements, or PDO with prepared statements, they're much safer.

Related

Why MYSQLi does not update the DB record, but it does provide a successful message

Why MYSQLi does not update the DB record, but it does provide a successful message. Of course, with the following message: 0 records UPDATED successfully And no changes are made to the database.
my index php file code:
<?php
include 'connect.php';
$work = $_GET["work"];
if($work == "select"){
$query = "SELECT * FROM login ORDER BY City DESC";
$result = $connect->prepare($query);
$result ->execute();
$out = array();
while ($row = $result->fetch(PDO::FETCH_ASSOC)){
$record = array();
$record["InsID"] = $row["InsID"];
$record["Password"] = $row["Password"];
$record["Name"] = $row["Name"];
$record["City"] = $row["City"];
array_push($out,$record);
}
echo json_encode($out);
} elseif($work == "update"){
$name2 = $_REQUEST["Ali"];
$code2 = $_REQUEST["4779"];
$city2 = $_REQUEST["teh"];
$pass2 = $_REQUEST["123"];
$query2 = "UPDATE login SET Password='$pass2',Name='$name2',City='$city2' WHERE InsID = '$code2'";
$result2 = $connect->prepare($query2);
$result2 ->execute();
}
?>
I really do not know where my coding is wrong. Please help.
I don't get why you are updating InsID and also using 'where InsID like'
Also there is additional ; in query
You may try
$query2 = "UPDATE login SET Password='$pass2',Name='$name2',City='$city2' WHERE InsID like '$code2'";
Important = sanitize input data first**
if I understand what you're trying to accomplish then :
you don't have to set InsID again
you need to use = and not LIKE in the WHERE condition
i.e. this is the row you need :
$query2 = "UPDATE login SET Password='$pass2',Name='$name2',City='$city2' WHERE InsID = '$code2';";
also see Nico Haase's comment, it's super correct ! you must improve the code security, see : http://php.net/manual/en/security.database.sql-injection.php
Try this code
May be useful
$query2 = "UPDATE login SET Password='$pass2',Name='$name2',City='$city2' WHERE InsID = '$code2';
if(mysqli_affected_rows($connect)==1){
echo "updated successfully";
}
else{
echo "failed";
}

my function that checks if something is already in the database isn't working

I'm working on this project and I need help with something. I am trying to check if someone is already in the database upon logging in and if they are not, they will be added. However, my code always adds them to the database...
Login code:
<?php
if(isset($_POST["emaillogin"]) and isset($_POST["passwordlogin"])){
$sql = "SELECT `accnr`
FROM `Account`
WHERE '$emaillogin' = `emailadress`
AND '$passwordlogin' = `password` LIMIT 1";
$result = mysql_query($sql);
if ($result == false){
echo "E-mail or password incorrect! <br>";
}else{
$accnr = mysql_fetch_array($result);
setcookie("accnr", $accnr[0] , time() + (1800), "/");
$accnmr = $accnr[0];
if(check_firstest($accnmr) == false){
$query = "INSERT INTO `VRIENDEN`
(`accnr`,`vriendnr`)
VALUES ('$accnmr','$accnmr')";
$result = mysql_query($query);
}
header("location:home.php");
die();
}
}
?>
The function in functions.php:
function check_firstest($accnr){
$query = mysql_query("SELECT count(*) AS 'num' FROM `VRIENDEN` WHERE `accnr` = '$accnr' AND `vriendnr` = '$accnr'");
if($result > 0){
return true;
}
else{
return false;
}
}
The login on its own works just fine, so thats no problem.
Thank you!
Your first query is somewhat odd and you do not capture the values from $_POST into the variables that you are using in the query either
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(isset($_POST["emaillogin"]) and isset($_POST["passwordlogin"])){
$sql = "SELECT `accnr`
FROM `Account`
WHERE `emailadress` = '{$_POST['emaillogin']}'
AND `password` = '{$_POST['passwordlogin']}'
LIMIT 1";
$result = mysql_query($sql);
if ($result == false){
// something went REALLY WRONG, report it
echo mysql_error();
exit;
}
if ( mysql_num_rows($result) == 1 ) {
// found user and password matches
header("location:home.php");
exit;
}else{
// new user, create the account
$accnr = mysql_fetch_array($result);
setcookie("accnr", $accnr[0] , time() + (1800), "/");
$accnmr = $accnr[0];
if(check_firstest($accnmr) == false){
$query = "INSERT INTO `VRIENDEN`
(`accnr`,`vriendnr`)
VALUES ('$accnmr','$accnmr')";
$result = mysql_query($query);
}
// and go to home page
header("location:home.php");
die();
}
}
?>
And of course the fix for the check_firstest() is also required
function check_firstest($accnr){
$result = mysql_query("SELECT count(*) AS 'num'
FROM `VRIENDEN`
WHERE `accnr` = '$accnr'
AND `vriendnr` = '$accnr'");
if(mysql_fetch_field($result, 0) > 0){
return true;
} else{
return false;
}
}
But I have to add
Your script is at risk of SQL Injection Attack
Have a look at what happened to Little Bobby Tables Even
if you are escaping inputs, its not safe!
Use prepared parameterized statements
And
You should not be using the mysql_ database extension, it is deprecated and has been for years and is gone for ever in PHP7.
If you are just learning PHP, spend your energies learning the PDO or mysqli database extensions and prepared statements.
Start here
You have to count the resulting rows:
function check_firstest($accnr){
$result = mysql_query("SELECT count(*) AS 'num'
FROM `VRIENDEN`
WHERE `accnr` = '$accnr'
AND `vriendnr` = '$accnr'");
if(mysql_fetch_field($result, 0) > 0){
return true;
} else{
return false;
}
}
Here the mysql_num_rows() function gives the number of rows in the result set. If it is greater than 0 then it means that there is some data.

How can i use mysqli_fetch_assoc to fix "fatal error: cannot use object of type mysqli_result as array"

I was getting the fatal error while trying to run mysql delete transaction so i searched for similar issues and it became obvious using mysqli_fetch_assoc is the way to fix this. Tried a couple of times but am obviously doing something wrong, would appreciate any help.
Here's my code
<?php
$selected_admin = find_admin_by_id($_GET["admin"]);
if (!$selected_admin) {
redirect_to("sadmin.php");
}
while ($admin = mysqli_fetch_assoc($selected_admin)) {
$admin_id = $selected_admin["admin_id"];
}
$sql = "delete from admin where admin_id = {$admin_id} limit 1";
$result = mysqli_query($connection, $sql);
if ($result && mysqli_affected_rows($connection) == 1) {
$SESSION["message"] = "Admin successfully deleted.";
redirect_to("sadmin.php");
} else {
$SESSION["message"] = "Admin was not deleted successfully.";
redirect_to("sadmin.php?admin={$admin_id}");
}
?>
And the function am calling is this
function find_admin_by_id($admin_id) {
global $connection;
$query = "select * from admin where admin_id = {$admin_id} LIMIT 1";
$current_admin = mysqli_query($connection, $query);
confirm_query($current_admin);
return $current_admin;
}
You are using wrong variable in while loop and my other mate also mentioned one hour ago, here is the correct code with minor changes:
<?php
$selected_admin = find_admin_by_id($_GET["admin"]);
if (!$selected_admin) { redirect_to("sadmin.php");
}
while ($admin = mysqli_fetch_assoc($selected_admin))
{
$admin_id = $admin["admin_id"];
}
if( intval($admin_id) > 0 ){
$sql = "delete from admin where admin_id = {$admin_id} limit 1";
$result = mysqli_query($connection, $sql);
if ($result && mysqli_affected_rows($connection) == 1)
{
$SESSION["message"] = "Admin successfully deleted.";
redirect_to("sadmin.php");
}
else {
$SESSION["message"] = "Admin was not deleted successfully."; redirect_to("sadmin.php?admin={$admin_id}");
}
}
?>
What I change:
Change $selected_admin as $admin.
And add if condition before executing DELETE STATEMENT.

postgresql check if exists while executing prepared statement

I'm preparing some statements and want to check if the row exists before I update. If it exists then update it, if it doesn't then output a message "No such animal". I have the update bit working, but unsure how to check if the row exists. Please assist.
$v = array();
$v[] = $_POST['status'];
$v[] = $_POST['id'];
$dbh = dbh_get();
$sql = 'UPDATE tap SET status=?
WHERE id =?';
$stmt = $dbh->prepare($sql);
$stmt->execute($v);
\\ if row isn't there display message "No such animal"
\\ otherwise print the below
printf("Status was changed to - %s", $v[0]);
\\then either way have my continue button for me to click on
print '<div class="button" style="float:left;" onclick="window.location.href=\'admin.php\';">Admin</div>' . "\n";
dbh_free($dbh)
According to your question, you want to check if the row exists before performing update. you can try this -
$id_exist = 0;
$sql = "SELECT id
FROM tap" ;
$sql_prepare = $dbh->prepare($sql);
$sql_prepare->execute();
while($row = $sql_prepare->fetchObject()) {
if($_POST['id'] == $row->id) {
$id_exist = 1;
}
}
if($id_exist == 1) {
// perform update here
} else {
echo 'No such animal';
}

Moving from MySQL to MySQLi message not displaying on no results

i'm currently trying to start using MySQLi instead of MySQL, but for some reason that I don't understand this is working for the first part of changing the password, but then failing on the error message. Can anyone tell me why? Cheers
$sql1 = <<<SQL
SELECT *
FROM Users
WHERE UserID = '$UserID'
&& Password = '$hashedPW'
SQL;
if ($db->query($sql1)) {
$sql2 = $db->query("UPDATE Users SET Password = '$NEWhashedPW' WHERE UserID=$UserID");
if($db->affected_rows === 0) { echo $_SESSION['changepass'] = 'error'; header('Location:'.$_SERVER["HTTP_REFERER"]);
} else {
$_SESSION['changepass'] = 'success'; header('Location:'.$_SERVER["HTTP_REFERER"]);
}
} else {
echo 'error';
}
$result1->free();
$db->close();
Question, why are you looping through the data if only 1 result is being returned?
$sql1 = "SELECT * FROM `Users` WHERE `UserID` = ".$UserID." AND `Password` = '".$hashedPW."'";
$result = $db->query($sql1);
if($db->num_rows($result)) { // Assuming you have a num_rows() function
$db->query("UPDATE `Users` SET `Password` = '".$NEWhashedPW."' WHERE `UserID` = ".$UserID);
$_SESSION['changepass'] = !$db->affected_rows() ? 'error' : 'success';
header('Location:'.$_SERVER["HTTP_REFERER"]);
} else
echo "User not found";
$result1->free();
$db->close();
This is also assuming that your query() function has some form of debugging ability and that you have a num_rows() function
If not, write one!
The num_rows() function should work similar to this (procedural style):
function num_rows($res) {
return mysqli_num_rows($res);
}
Simply whack that into your database class and you should be good to go.
May need edits, I don't know how your DB class is set up

Categories