PHP/Mysqli check before update - php

Hey I am completely new to PHP/MySqli, I would like to check before update if Scanstatus field of given ID is already "Scanned". if its already Scanned display a message as "Already Scanned" else Update.
Below code only update and doesn't check if already exists.
<?php
$id = $_POST['id'];
$connection = mysqli_connect("localhost", "username", "passwd","dbname");
if(mysqli_connect_errno())
{
echo "failed to connect " . mysqli_connect_error();
}
if(isset($_POST['Submit']))
{
$query = "UPDATE `sales` SET `ScanStatus` = 'Scanned' WHERE `id` = $id";
$result = mysqli_query($connection,$query);
if (!$result) {
die('Error' . mysqli_error($connection));
}
else
{
echo "Successfully updated";
}
}
?>

Try following php code
$id = $_POST['id'];
$connection = mysqli_connect("localhost", "username", "passwd","dbname");
if(mysqli_connect_errno())
{
echo "failed to connect " . mysqli_connect_error();
}
else{
if(isset($_POST['Submit']))
{
$sql = "UPDATE sales SET ScanStatus = 'Scanned' WHERE id = '$id'";
$result = $connection->query($sql);
if ($result->num_rows > 0) {
echo "Successfully updated";
} else {
die('Error' . mysqli_error($connection));
}
}
}
When click SUBMIT button "isset($_POST['Submit'])" will be true and direct into if statement. then run sql command and is if there is any result that sql query affected go into next if statement after true the condition "$result->num_rows > 0" then echo "Successfully updated".

As I understand, you want to update only if the ScanStatus field is not Scanned
So you can modify you existing query like this without the need to fetch the record:
$query = "UPDATE `sales` SET `ScanStatus` = 'Scanned' WHERE `id` = $id AND `ScanStatus` != 'Scanned'";
Just change the query to above and use:
if(mysqli_affected_rows($result) > 0 ){
Here is a full code:
<?php
$connection = mysqli_connect("localhost", "username", "passwd","dbname");
if(mysqli_connect_errno()) {
echo "failed to connect " . mysqli_connect_error();
}
if(isset($_POST['Submit'])) {
$id = $_POST['id'];
$query = "UPDATE `sales` SET `ScanStatus` = 'Scanned' WHERE `id` = $id AND `ScanStatus` != 'Scanned'";
$result = mysqli_query($connection, $query);
if(mysqli_affected_rows($connection) > 0 ){
echo "Successfully updated";
}
else {
echo 'Already Scanned';
}
}

You can use this code:
Use if(mysqli_affected_rows($mysqli) > 0 ) or no comparison at all.
Replace your code with this:
<?php
$id = $_POST['id'];
$connection = mysqli_connect("localhost", "username", "passwd","dbname");
if(mysqli_connect_errno())
{
echo "failed to connect " . mysqli_connect_error();
}
if(isset($_POST['Submit']))
{
$my_query = mysqli_query($connection, "SELECT * FROM `sales` WHERE `id` = ". $id . " AND `ScanStatus` = 'Scanned'");
if(mysqli_num_rows($my_query) > 0){
echo "Already ScanStatus is Scanned";
}
else{
$query = "UPDATE `sales` SET `ScanStatus` = 'Scanned' WHERE `id` = ".$id;
//echo $query;die;
$result = mysqli_query($connection, $query);
if(mysqli_affected_rows($connection) > 0 ){
echo "Successfully updated";
/* get new updated data */
$new_query = mysqli_query($connection, "SELECT * FROM `sales` WHERE `id` = '$id' LIMIT 1");
$new_info = mysqli_fetch_array($new_query);
echo "<pre>"; print_r($new_info);
}
else
{
echo "Not updated";
}
}
}
?>

Related

I can't get any data output from the database, i only get "0 results" as the else statement, what's the case?

I'm having some troubles with fetching some database information with my php code.
All I'm getting is this message: "Connected successfully0 results".
Here's my code guys, thanks for the help in advance.
<?php
$servername = "example";
$username = "example1";
$password = "example2";
$row = array();
$conn = new mysqli($servername,$username,$password);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$sql = "Select Distinct subject from mobile_math_science_toc";
$result = mysqli_query($conn, $sql);
if ($result = $conn->query($sql)) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "Subject " ,$row["subject"];
}
} else {
echo "0 results ";
}
mysqli_close($conn);
?>
You should add dbname while creating your connection to database. You can use mysqli_num_rows function to count no. of rows.
<?php
$servername = "example";
$username = "example1";
$password = "example2";
$dbname = "your_db_name"; // Specify your db-name here.
$conn = new mysqli($servername,$username,$password,$dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$sql = "Select Distinct subject from mobile_math_science_toc";
$result = mysqli_query($conn, $sql);
// Checking if there are some records available.
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "Subject " ,$row["subject"];
}
} else {
echo "0 results ";
}
mysqli_close($conn);
?>
Change
$conn = new mysqli($servername,$username,$password);
To
$conn = new mysqli($servername,$username,$password, "<your database name>");
And
$result = mysqli_query($conn, $sql);
if ($result = $conn->query($sql)) {
}
To
$result = $conn->query($sql);
if ($result) {
}
Try
if (mysqli_num_rows($result) > 0) {
While checking you got the data or not

How update Data from mysql using PHP?

So I try to update data from input type, but when i click update button the data wont change, here's my code:
if (isset($_POST["update"])) {
$nim = $_POST["nim"]; $nama = $_POST["nama"]; $jurusan = $_POST["jurusan"];
$conn = mysqli_connect("localhost", "root", "root", "belajar");
$query ="UPDATE 'mahasiswa' SET nama = '".$nama."', jurusan = '".$jurusan."' WHERE nim = ".$nim."";
if (mysqli_query($conn, $query)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
}
Try This, Do not use single quotes in table name,
if (isset($_POST["update"])) {
$nim = $_POST["nim"]; $nama = $_POST["nama"]; $jurusan = $_POST["jurusan"];
$conn = mysqli_connect("localhost", "jimlyas", "shafira", "belajar");
$query ="UPDATE `mahasiswa` SET nama = '".$nama."', jurusan = '".$jurusan."' WHERE nim = '".$nim."' ";
if (mysqli_query($conn, $query)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
}
Use something like.
<?php
$conn = mysqli_connect("localhost", "root", "root", "belajar");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// update part
if (isset($_POST["update"])) {
$nim = mysqli_real_escape_string($conn,$_POST["nim"]);
$nama = mysqli_real_escape_string($conn,$_POST["nama"]);
$jurusan = mysqli_real_escape_string($conn,$_POST["jurusan"]);
$query ="UPDATE mahasiswa SET nama = '$nama', jurusan = '$jurusan' WHERE nim = '$nim'";
if (mysqli_query($conn, $query)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
}
mysqli_close($conn);
?>

PHP / MySql if '1' echo "Ok" else if '0' echo "No"

Phpmyadmin:
Phpmyadmin Image example
if (mysql_query("SELECT setup FROM users") === 1) {
echo "One";
} else if (mysql_query("SELECT setup FROM users") === 0) {
echo "Zero";
}
On register. As defined: 0.
If table shows 0, echo Zero.
Else if table shows ID 1, echo One.
How is this done?
Solution:
$setup = mysql_query("SELECT setup FROM users");
$row = mysql_fetch_assoc($setup);
if ($row['setup'] == 0) {
echo "Zero.";
} else {
echo "One!";
}
I think you need this
First of all use mysqli
//$connection = your mysqli connection. Dont use mysql
Then properly write query if you need admin row
$query = "SELECT `setup` FROM `users` WHERE `user_id`=1 AND `username` = 'admin'";
Then execute query
$result = mysqli_query($connection, $query);
Then search for $setup value
while($row = mysqli_fetch_assoc($result)){
$setup = $row['setup'];
}
Then echo what you need
if ($setup == 1) {
echo "One";
} else if ($setup == 0) {
echo "Zero";
}
See the docs. The 'Example (MySQLi Procedural)' example is similar to what you want.
Snippet:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
Changing
$sql = "SELECT id, firstname, lastname FROM MyGuests";
to
$sql = "SELECT setup FROM users";
then
if (mysqli_num_rows($result) > 0) {
to your various if checks should suffice. Not the cleanest. Seems like you could just print out the value of setup? Good luck!

UPDATE query isn't working when POST isset

I have this code that allows a user to reset their account from a url link
<?php
$servername = "localhost";
$username = " ";
$password = " ";
$dbname = " ";
$code = $_GET['code'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT com_code FROM user WHERE com_code = ".$_GET['code'];
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<form action='reset.php?code=" . $row["com_code"]. "' method='post'>Enter New Password: <input type='text' name='new_password' placeholder='New Password'><br><input type='submit' value='Submit'></form>";
}
} else {
echo "0 results";
}
$conn->close();
?>
<?php
$servername = "localhost";
$username = " ";
$password = " ";
$dbname = " ";
$pword = $_POST['new_password'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST['Submit'])) {
$sql1 = "UPDATE user SET password='$pword', com_code=NULL WHERE com_code = '$code'";
}
if ($conn->query($sql1) === TRUE) {
echo "Password has been change successfully!";
} else {
echo "Error updating record: " . $conn->error;
}
?>
I keep getting the error:
Warning: mysqli::query(): Empty query in
/home/u590953899/public_html/notify/reset.php on line 47 Error
updating record:
When you press the submit button, it is suppose to UPDATE the database where the com_code = the $GET url
BUT
What happens is that it only reloads the page, how do I fix this?
The link to it is: http://notify.bithumor.co/reset.php?code=123456789
You should change your code to be inside isset like this :
if (isset($_POST['Submit'])) {
$sql1 = "UPDATE user SET password='$pword', com_code=NULL WHERE com_code = '$code'";
if ($conn->query($sql1) === TRUE) {
echo "Password has been change successfully!";
} else {
echo "Error updating record: " . $conn->error;
}
}
Make following changes in your code:
if (isset($_POST['Submit'])) {
$sql1 = "UPDATE user SET password='$pword', com_code IS NULL WHERE com_code = '$code'";
if ($conn->query($sql1) === TRUE) {
echo "Password has been change successfully!";
} else {
echo "Error updating record: " . $conn->error;
}
}
We use IS NULL to check NULL in mysql
if (isset($_POST['Submit'])) {
$sql1 = "UPDATE user SET password='$pword', com_code IS NULL WHERE com_code = $code";
}
Read NULL Values in MYSQL
$_POST['Submit'] will never be set, when your submit button doesn't have name="submit". Just having type="submit", or value="submit", or id="submit" will not do it. You need the name attribute for that.
First check that your input type has name="Submit", if not add it.
After that echo your query first,
if (isset($_POST['Submit'])) {
echo "UPDATE user SET password='$pword', com_code=NULL WHERE com_code = '$code'";
$sql1 = "UPDATE user SET password='$pword', com_code=NULL WHERE com_code = '$code'";
if ($conn->query($sql1) === TRUE) {
echo "Password has been change successfully!";
} else {
echo "Error updating record: " . $conn->error;
}
}
And also all the code i.e. query executing and messages should be in the same if statement ( if(isset($_POST['Submit'])) ).
I hope this works for you.

mysql_query SELECT do not give the desired result

The following code always displays
rows = 0
eventhough the table contains Ravi in the field 'to'. Does anyone know what is wrong with this code?
<?php
$response = array();
$con = mysql_connect("localhost","root","");
if(!$con) {
die('Could not connect: '.mysql_error());
}
mysql_select_db("algopm1",$con);
//if (isset($_POST['to'])) {
$to = "Ravi";
$result = mysql_query("SELECT *FROM `events` WHERE to = '$to'");
if (!empty($result)) {
if (mysql_num_rows($result)>0) {
$result = mysql_fetch_array($result);
echo $result["to"] + " " + $result["from"];
} else {
echo 'rows = 0';
}
} else {
echo 'empty for Ravi';
}
//} else {
//}
?>
to is a reserved word in MySQL, if you want to use it you must encase it in backticks:
.... WHERE `to` = ...
I have not look at your code but I recommend looking at
http://php.net/manual/en/intro.mysql.php
this before you continue to use mysql and not mysqli. It isn't that different but mysqli seems to have a wrapper over mysql and uses the "->" to instantiate new classes for a connection. If that makes any sense.
Try this:
<?php
$response = array();
$con = mysql_connect("localhost","root","");
if(!$con) {
die('Could not connect: '.mysql_error());
}
mysql_select_db("algopm1",$con);
//if (isset($_POST['to'])) {
$to = "Ravi";
$result = mysql_query("SELECT *FROM `events` WHERE `to` = '$to'");
if (!empty($result)) {
if (mysql_num_rows($result)>0) {
$row = mysql_fetch_array($result);
echo $row["to"] + " " + $row["from"];
} else {
echo 'rows = 0';
}
} else {
echo "empty for $to";
}
//} else {
//}
?>
MYSQLI version + some adjustments:
<?PHP
$host = "localhost";
$user = "root";
$password = "";
$database="algopm1";
$link = mysqli_connect($host, $user, $password, $database);
IF (!$link){
echo ("Unable to connect to database!");
}
ELSE {
$query = "SELECT *FROM `events` WHERE `to` = '$to'";
$result = mysqli_query($link, $query);
if (mysql_num_rows($result)>0) {
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)){
echo $row["to"]. "+". $row["from"];
}
}
ELSE {
echo 'rows = 0';
}
}
mysqli_close($link);
?>
I would like to credit #njk and #Wezy for their contribution with regard to the reserved word to in mysql. The WHILE loop is not necessary if the table events can only contain one "to" in this case "Ravi". I suspect that the number of events can be greater than one.
#Wezy has a point but let's do the troubleshooting:
As #JonathanRomer in his comment suggested, do:
$result = mysql_query("SELECT *FROM `events` WHERE `to` = '$to'") or die(mysql_error());
What does it say? Does it fail at all?
Or, just before mysql_query do:
die("SELECT *FROM `events` WHERE `to` = '$to'");
this will print faulty query being executed. Next, fire up mysql console or PHPMyAdmin and try executing this query manually.
Again, what does it say?
Actually, my main purpose was to encode this message and receive it on a mobile device by using JSON. This is the full code. For normal checking purpose, instead of using json_encode(*), the values can be displayed individually. This is the solution I got and it is working perfectly for receiving the data in an android app on which I am working.
<?php
$host = "localhost";
$user = "root";
$password = "";
$database="algopm1";
$response = array();
$mysqli = new mysqli($host, $user, $password, $database);
if (mysqli_connect_errno()){
$response["success"] = 0;
$response["message"] = mysqli_connect_error();
echo json_encode($response);
}
if(isset($_POST['to'])) {
$to = $_POST['to'];
$query = "SELECT *FROM `events` WHERE `to` = '$to'";
if($stmt = $mysqli->prepare($query)) {
$stmt->execute();
$stmt->store_result();
$i = 0;
if($stmt->num_rows > 0) {
$stmt->bind_result($rowto, $rowfrom, $rowevent);
$response["events"] = array();
while($stmt->fetch()) {
$events = array();
$events["to"] = $rowto;
$events["from"] = $rowfrom;
$events["event"] = $rowevent;
array_push($response["events"], $events);
}
$response["success"] = 1;
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No events found";
echo json_encode($response);
}
$stmt->close();
}
} else {
$response["success"] = 0;
$response["message"] = "Required fields are missing";
echo json_encode($response);
}
$mysqli->close();
?>

Categories