I cannot update the values in my table with this code, if the update is successful the page should redirect in ('Location:ui.php'), how can this be achieved?
<?php
ob_start();
include('dbconnect.php');
$code=$_GET['stallcode'];
if(isset($_POST['submit']))
{
$pcost = $_POST['pcost'];
$tcost = $_POST['tcost'];
$cash = $_POST['cash'];
$change = $_POST['change'];
if (($cash == '0'))
{
$pstatus="0";
}
else
{
$pstatus="1";
}
$updated=mysql_query("UPDATE tbl_stallowner SET
paymentstatus='$pstatus', penaltycost='$pcost', totalcost='$tcost', cash='$cash', change='$change'
WHERE stallcode='$code'")or die();
if($updated)
{
$msg="Successfully Updated!!";
header('Location:ui.php');
}
} //update ends here
ob_end_flush();
?>
As you redirects users by checking if($updated) is true, this will not work, you should check the number of affected rows instead using mysql_num_rows.
Also remember to exit; after header() to stop the execution.
$num_rows = mysql_num_rows($updated);
if($num_rows > 0)
{
$msg="Successfully Updated!!";
header('Location:ui.php');
exit;
}
Tip: You should not be using MySQL as it has already been deprecated, use MySQLi instead.
You want to use mysqli, not it's predecessor, mysql. Mysql is vulnerable and open to exploitation, here's what you should write in each of your files:
dbconnect.php
<?php
$conn = mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
updatestallowner.php (or whatever you named it)
<?php
ob_start();
require('dbconnect.php');
$code = mysqli_real_escape_string($conn, $_GET['stallcode']);
if(isset($_POST['submit'])){
$pcost = mysqli_real_escape_string($conn, $_POST['pcost']);
$tcost = mysqli_real_escape_string($conn, $_POST['tcost']);
$cash = mysqli_real_escape_string($conn, $_POST['cash']);
$change = mysqli_real_escape_string($conn, $_POST['change']);
if ($cash == '0') {
$pstatus="0";
} else{
$pstatus="1";
}
$sql = "UPDATE tbl_stallowner SET paymentstatus='$pstatus', penaltycost='$pcost', totalcost='$tcost', cash='$cash', change='$change' WHERE stallcode='$code';";
$result = mysqli_query($conn, $sql);
if($result) {
$msg="Successfully Updated!!";
header('Location: ui.php');
exit;
} else {
die("Error updating!");
}
}
?>
Good luck!
Related
How to update a status from database if status is empty in using php? I have this condition in php. I have this if condition that decides if $getstatus is empty it will update from database to Avail. I tried refreshing the page after querying the database. But it will not update in database. Is there anyway to update this without using form submit in php?
<?php
session_start();
include "includes/connection.php";
// Display all parking slots
$sql = $connection->prepare('SELECT * FROM parkingslot where parkingslotid = 1');
$sql->execute(); // execute query
$result = $sql->get_result(); // fetch result
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$getstatus = $row["status"];
echo $getstatus;
}
}
if (empty($getstatus)) {
$sql = $connection->prepare("UPDATE parkingslot SET status = 'Avail' where parkingslotid = 1 ");
}
?>
Codes in connection for connecting to database
connection.php
<?php
$server = "localhost";
$username = "root";
$password = "";
// create connection
$connection = mysqli_connect($server,$username,$password);
// check connection
if(!$connection)
{
die("No connection found." . mysqli_connect_error());
}
else {
// select a database
$select_db = mysqli_select_db($connection,'smartparkingsystem');
if(!$select_db)
{
$sql = 'CREATE DATABASE sample';
// create database if no db found
if(mysqli_query($connection,$sql)) {
echo "Database Created";
}
else {
echo "Database not found" . mysqli_connect_error() . '\n';
}
}
else {
// Database already existed
// do nothing...
}
}
?>
If I understand your goal of: For row(s) whereparkingslotid=1 - Update status to 'Avail' but only if status is not currently set, this might help:
<?php
session_start();
include "includes/connection.php";
$connection->prepare("UPDATE `parkingslot` SET `status`=? WHERE `parkingslotid`=? AND (`status` IS NULL OR `status`=?)");
$connection->bind_param("sis", $status, $parkingslotid, $empty_str);
$status = 'Avail';
$parkingslotid = 1;
$empty_str = '';
$connection->execute();
echo $connection->affected_rows.' rows affected';
$connection->close();
?>
This saves a bit of processing by not checking with PHP first.
You can use this query:
"UPDATE parkingslot SET status = 'Avail' where status IS NULL OR status = '' "
Edited:
#lumonald gave the right anwser in the comment. You're not executing your second SQL statement.
I am trying to run Insert query on my php page but its not executing and takes me to else part.
I have checked query on MySQL its fine. Also I have couple of select queries on the same page, and those works fine. So I am sure there is no issue with the connection or accessing DB. Heres my code:
<?php
session_start();
include './db_config.php';
if ((!isset($_SESSION['first_name']) == true)) {
unset($_SESSION['first_name']);
}
$logged = $_SESSION['first_name'];
if ((!isset($_SESSION['id']) == true)) {
unset($_SESSION['id']);
}
$id = $_SESSION['id'];
if ((!isset($_SESSION['email']) == true)) {
unset($_SESSION['email']);
}
$email= $_SESSION['email'];
$query1 = "select * from user_master where id='$id'";
$result1 = mysqli_query($con, $query1);
$num1 = mysqli_num_rows($result1);
if ($num1 > 0) {
while ($data = $result1->fetch_assoc()) {
$branch_name = $data['branch_name'];
}
}
if(isset($_POST['save'])){
$cust_id=$_POST['cust_id'];
$meter_no=$_POST['meter_no'];
$lock_no=$_POST['lock_no'];
$customer_name=$_POST['customer_name'];
$customer_type=$_POST['customer_type'];
$customer_zone=$_POST['customer_zone'];
$status=$_POST['status'];
$phoneno=$_POST['phoneno'];
$city=$_POST['city'];
$address=$_POST['address'];
$houseno=$_POST['houseno'];
$ownership=$_POST['ownership'];
$landmark=$_POST['landmark'];
$opening_reading=$_POST['opening_reading'];
$opening_reading_date=$_POST['opening_reading_date'];
$branch_name=$_POST['branch_name'];
$created_on=$_POST['created_on'];
$created_by=$_POST['created_by'];
$email=$_POST['email'];
$consumption=0;
$current_reading=$opening_reading;
$status1="True";
$total_bill=0;
$total_paid=0;
$total_dues=0;
$select="insert into meter(cust_id,meter_no,lock_no,customer_name,customer_type,customer_zone,status,phoneno,city,address,houseno,ownership,landmark,opening_reading,opening_reading_date,created_on,branch_name,created_by,email)
VALUES('$cust_id','$meter_no','$lock_no','$customer_name','$customer_type','$customer_zone','$status','$phoneno','$city','$address','$houseno','$ownership','$landmark','$opening_reading','$opening_reading_date','$created_on','$branch_name','$created_by','$email')";
if ($r = mysqli_query($con, $select)) {
else {
echo '<script language="javascript">';
echo 'alert("Information Not Inserted!!!");';
//echo 'window.location.href="bill_generation.php";';
echo '</script>';
}
}
I have Checked on Godaddy HERE that one need just Localhost as host name.
I know I have pasted a long piece of code, however dont know where the issue is.
You have a typo at the end of your code.
if ($r = mysqli_query($con, $select)) {
echo 'data inserted successfully !';
// do something ?
} // this one is missing
else {
echo '<script language="javascript">';
echo 'alert("Information Not Inserted!!!");';
//echo 'window.location.href="bill_generation.php";';
echo '</script>';
}
I have a very simple use case where I am checking if a certain value is present in the table and it always seems to fail.This is my php code.
<?php
include "config.php";
$con = mysqli_connect($server_name,$mysql_user,$mysql_pass,$dbname);
if(!$con)
{
echo "Connection Error".mysqli_connect_error();
}
else{
//echo "";
}
$device_id = $_POST["device_id"];
$check = "SELECT magazine_id FROM registered_buyers WHERE device_id = $device_id";
$rs = mysqli_query($con,$check);
if(mysqli_num_rows($con,$rs) == 0)
{
$jsonarray = $_POST["jsonarray"];
echo "This will be inserted".$jsonarray;
}else
{
echo "User already registered";
}
?>
Can anyone please point out my mistake.Any help or suggestion is welcome.Thank you.
You can try to follow this code.
<?php
include "config.php";
$con = mysqli_connect($server_name,$mysql_user,$mysql_pass,$dbname);
if(!$con){
echo "Connection Error".mysqli_connect_error();
}
$device_id = $_POST["device_id"];
$check = "SELECT magazine_id FROM registered_buyers WHERE device_id = ".$device_id;
$rs = mysqli_query($con, $check);
if(mysqli_num_rows($rs) == 0){
$jsonarray = $_POST["jsonarray"];
echo "This will be inserted".$jsonarray;
}else{
echo "User already registered";
}
?>
since i dont have enough rep to add a comment, i will consider the device_id is string, if so try something like this:
"SELECT magazine_id FROM registered_buyers WHERE device_id = '$device_id'";
add '
Ok so I wrote some code to find records on a test database, it works if there is a record and does display the data, if there is no record it still says that it found stuff. It should say it did not. It even finds stuff that is not in the database but obviously has no data to display, its annoying.
I need a new pair of eyes.
I think the error is here:
$sql = "SELECT * FROM Kittenzz
WHERE KittenID='".$_POST['KittenID']."';";
$result = mysql_query($sql, $connection);
But just in case here is the full code minus the login credentials to the db.
<?php
if(isset($_POST['Find']))
{
$connection = mysql_connect("Login Info Deleted");
// Check connection
if (!$connection)
{
echo "Connection failed: " . mysql_connect_error();
}
else
{ //else 1
//select a database
$dbName="Katz";
$db_selected = mysql_select_db($dbName, $connection);
//confirm connection to database
if (!$db_selected)
{
die ('Can\'t use $dbName : ' . mysql_error());
}
else
{ //else 2
if ($_POST[KittenID]=='')
{
$OutputMessage = 'Must add a Kitten-ID';
}
else
{//exception else
$sql = "SELECT * FROM Kittenzz
WHERE KittenID='".$_POST['KittenID']."';";
$result = mysql_query($sql, $connection);
while($row = mysql_fetch_array($result))
{
$Name = $row['Name'];
$KittenID = $row['KittenID'];
$KittenAge = $row['KittenAge'];
$Email = $row['Email'];
$Comments = $row['Comments'];
$Gender = $row['Gender'];
$Passive = $row['Passive'];
$Playful = $row['Playful'];
$Activity = $row['Activity'];
}
if ($result)
{
$OutputMessage = 'Record Found';
//echo "<p>Record found<p>";
}
else
{
$OutputMessage = 'RECORD NOT FOUND';
}
}//exception else
}//else 2 end
}//else 1 end
mysql_close($connection);
}
?>
if ($result)
{
$OutputMessage = 'Record Found';
}
There is your mistake, that means if the query executed successfully (even with 0 records) you are saying records found. You should only say that if the number of records returned are more than 0.
if (mysql_num_rows($result)>0)
{
$OutputMessage = 'Record Found';
}
But the bigger problem with your code can be solved by this reading
How can I prevent SQL injection in PHP?
This may happen, because if $_POST['KittenID'] is empty, the sql query would look like : SELECT * FROM Kittenzz WHERE KittenID=""; you have to change the above if statement to:
if (!isset($_POST[KittenID]) || empty($_POST[KittenID]) || $_POST[KittenID]=='')
{
$OutputMessage = 'Must add a Kitten-ID';
}
Hi I am facing a unique issue with my PHP script.Here is my code. After writeToDB() is executed I dont see the echo ("<script> top.location.href=www.facebook.com</script>");
Can someone let me know why my script stops executing after writing to db?
<?php
function writeToDB($access_token,$uid,$username,$birthday,$gender,$age)
{
/* Database Connection */
$user = "xxxx";
$password = "xxxx";
$host = "xxxxxxxxxxxxxxxxxx";
//connect to database, where tsnames.ora is setup
$connect_obj = oci_connect($user, $password, $host);
if ($connect_obj) {
error_log("connected okay");
} else {
$err = OCIError();
echo "Oracle connection error " . $err[text];
return;
}
$select_query = "SELECT USER_ID FROM FBTABLE WHERE USER_ID= '$uid'";
$select_sql_stmt = oci_parse($connect_obj, $select_query);
//execute statement
try {
$r = oci_execute($select_sql_stmt, OCI_DEFAULT);
if (!$r) {
$p = oci_error($select_sql_stmt);
echo "Oci Execute error";
}
} catch (Exception $e) {
echo "<br>Failed to get database info" . $e->getMessage();
}
$user_id_in_db = null;
while (oci_fetch($select_sql_stmt)) {
$user_id_in_db = oci_result($select_sql_stmt, 'USER_ID');
}
// User already exists in db so update instead of insert
if ($user_id_in_db != null) {
$query ="UPDATE FBTABLE SET ACCESS_TOKEN='$access_token' WHERE USER_ID='$uid'";
} else {
$query = "INSERT INTO FBTABLE(ACCESS_TOKEN, USER_ID,USER_NAME,BIRTHDAY,GENDER,AGE)
VALUES
('$access_token','$uid','$username','$birthday','$gender','$age')";
}
//create sql statement
$sql_statement = oci_parse($connect_obj, $query);
//execute statement
try {
$r = oci_execute($sql_statement, OCI_DEFAULT);
if (!$r) {
$p = oci_error($sql_statement);
echo "Oci Execute error";
}
} catch (Exception $e) {
echo "<br>Failed to get database info" . $e->getMessage();
}
//Commit transaction
$committed = oci_commit($connect_obj);
//Test whether commit was successful. If error occurred, return error message
if (!$committed) {
$error = oci_error($conn);
echo 'Commit failed. Oracle reports: ' . $error['message'];
}
//close the connection
$oci_free_statement($sql_statement);
if (oci_close($connect_obj)) {
echo " oci connection not closed!!!";
}
//close the connection
$oci_free_statement($sql_statement);
}
?>
<html>
<body>
<?php
$access_token = $_GET['access_token'];
$uid = $_GET['uid'];
$username = $_GET['username'];
$birthday = $_GET['birthday'];
$gender = $_GET['gender'];
$age = $_GET['age'];
echo $username;
writeToDB($access_token,$uid,$username,$birthday,$gender,$age);
echo ("<script> top.location.href=www.facebook.com</script>");
?>
</body>
</html>
i think error is in $oci_free_statement($sql_statement); must be oci_free_statement($sql_statement); extra $ before oci_free_statement
http://php.net/manual/en/function.oci-free-statement.php
no any error show because of error_display is off
Your JavaScript code should be
echo ("<script> top.location.href='http://www.facebook.com';</script>");
It's happen because writeToDB() causes error. You don't see this error because error_display is off or error_reporting = 0
Also maybe you didn't install OCI8. So when you call oci_connect it will cause error.
Thanks.
you are not using quotes around the string:
www.facebook.com should be 'www.facebook.com'