Issues updating record using mysqli - php

I want to update/edit my user form, but when I click the "edit" button, I'm not getting the expected results. It should display the new data, but It displays the old data instead.
coding:
<?php
include"errorReporting.php";
include "conn.php";
$conn = connect();
$conndb = connectdb();
$wardID = $_REQUEST["wardID"];
$RequestName = $_REQUEST["RequestName"];
$Department = $_REQUEST["Department"];
$Position = $_REQUEST["Position"];
$Date= $_REQUEST["Date"];
$TypeOfRequest = $_REQUEST["TypeOfRequest"];
$PleaseSpecify = $_REQUEST["PleaseSpecify"];
$DateRequire = $_REQUEST["DateRequire"];
$DateReturn = $_REQUEST["DateReturn"];
mysqli_select_db($conn,"misadmin") or die ($conn->error ."\n");
$query = "select * from requestform";
$result2= $conn->query($query) or die ($conn->error ."\n");
$row_result =mysqli_fetch_assoc($result2);
mysqli_select_db($conn,"misadmin") or die ($conn->error ."\n");
$conn ->query("UPDATE requestform SET RequestName='$RequestName',Department='$Department',Position='$Position',Date='$Date',TypeOfRequest='$TypeOfRequest',PleaseSpecify='$PleaseSpecify',DateRequire='$DateRequire',DateReturn='$DateReturn' where wardID='$wardID'",$conn->affected_rows);
$result_update=mysqli_fetch_assoc($result);
header("Location:requestform3.php");
?>
output:

try it:
$conn ->query("UPDATE requestform SET RequestName='$RequestName',Department='$Department',Position='$Position',Date='$Date',TypeOfRequest='$TypeOfRequest',PleaseSpecify='$PleaseSpecify',DateRequire='$DateRequire',DateReturn='$DateReturn' where wardID=$wardID ");

in where wardID='???' Must retrieve the data before it changes. i mean "4f" not "med".
you can add a textbok in your post form :
<input type="hidden" id="original_wardID" value="<?php echo $wardID?>" />
in your php code add :
$ori_wardID=$_REQUEST['original_wardID'];
then change your sql :
UPDATE requestform SET wardID='$wardID',RequestName='$RequestName',Department='$Department',Position='$Position',Date='$Date',TypeOfRequest='$TypeOfRequest',PleaseSpecify='$PleaseSpecify',DateRequire='$DateRequire',DateReturn='$DateReturn' where wardID='$ori_wardID'

"UPDATE requestform SET RequestName='$RequestName',Department='$Department',Position='$Position',Date='$Date',TypeOfRequest='$TypeOfRequest',PleaseSpecify='$PleaseSpecify',DateRequire='$DateRequire',DateReturn='$DateReturn' where wardID='$wardID'"
change to
"UPDATE requestform SET RequestName='".$RequestName."',Department='".$Department."',Position='".$Position."',Date='".$Date."',TypeOfRequest='".$TypeOfRequest."',PleaseSpecify='".$PleaseSpecify."',DateRequire='".$DateRequire."',DateReturn='".$DateReturn."' where wardID=".$wardID
or like this demo code
$db_sql="select id ,uid,regdate from `newtable` where id=?";
$stmt=$mysqli->prepare($db_sql);//
$stmt->bind_param("i",$id);// i int d double s string b blob
$result = $stmt->execute();
but I guess use pdo will be better

You are not using if ($_SERVER['REQUEST_METHOD'] == 'POST'){//save database} or if (isset $_POST['edit']){//save database} for the edit button in order to save data when edit button is clicked.
Plus you are using Date in your UPDATE query (Date =). DATE is also as a native function used in MYSQL, you need to change it. In case you changed it to DateChanged use prepared statement it helps your code to be more readable.
if ( $_SERVER['REQUEST_METHOD'] == 'POST' )
{
$stmt = $conn->prepare("UPDATE requestform SET RequestName=?,
Department=?, Position=?, DateChanged=?, TypeOfRequest=?,
PleaseSpecify=?, DateRequire=?, DateReturn=? WHERE wardID=?");
$stmt->bind_param("sssssssss", $RequestName, $Department,
$Position, $DateChanged, $TypeOfRequest, $PleaseSpecify,
$DateRequire, $wardID);
$stmt->execute();
$stmt->close();
$conn->close();
}

i had found my answer. after i redo back my coding using the old template
here are the code.
<?php
// to connect with the database system
include "errorReporting.php";
include "conn.php";
$conn = connect();
$conndb = connectdb();
$wardID = $_REQUEST["wardID"];
$RequestName = $_REQUEST["RequestName"];
$Department = $_REQUEST["Department"];
$Position = $_REQUEST["Position"];
$DateRequest = $_REQUEST["DateRequest"];
$TypeOfRequest = $_REQUEST["TypeOfRequest"];
$PleaseSpecify = $_REQUEST["PleaseSpecify"];
$DateRequire = $_REQUEST["DateRequire"];
$DateReturn = $_REQUEST["DateReturn"];
mysqli_select_db($conn,"misadmin") or die (mysql_error()."\n");
$query = "select * from requestform" ;
$result = $conn->query($query) or die (mysql_error()."\n".$query);
$row_result=mysqli_fetch_assoc($result);
mysqli_select_db($conn,"misadmin")or die (mysql_error(). "\n");
//to update the data
$update="update requestform SET
RequestName='$RequestName' ,Department='$Department' ,Position='$Position' ,DateRequest='$DateRequest' ,TypeOfRequest='$TypeOfRequest',PleaseSpecify='$PleaseSpecify' ,DateRequire='$DateRequire' ,DateReturn='$DateReturn' where wardID='$wardID'";
$rowinsert=$conn->query($update);
header("Location:requestform3.php");
?>
thanks for those who gave the suggestions.I had learnt a lot from you all.

Related

Data which is succesfully added in database, doesnt show in database

im adding data in databese with php and received "succesful" but when i look into the database the data which is i have just added doesnt show. Here my codes
<?php
require ('db.php');
#$name = $_POST['name'];
#$surname = $_POST['surname'];
#$number = $_POST['number'];
#$mail = $_POST['mail'];
#$note = $_POST['note'];
$sql = "INSERT INTO customersinfo (name,surname,number,email,notes) VALUES ($name,$surname,$number,$mail,$note)";
$con->query($sql);
if ($sql)
{
echo "Succesful";
}
else
{
echo "error";
}
?>
this is also my db.php codes ;
<?php
$con = mysqli_connect("localhost","root","","customers");
if (mysqli_connect_errno()) {
printf(" Connection error :( %s\n", mysqli_connect_error());
exit();
}
?>
i also have one more question. When i try to add data in databese with mysqli_query() function, it doesnt work. for example;
mysqli_query($con, "INSERT INTO customersinfo (name,surname,number,email,notes) VALUES($name,$surname,$number,$email,$note)");
because of this , i had to use this code,its working now but i have no idea why mysqli_query() function is doesnt work
$sql = "INSERT INTO customersinfo (name,surname,number,email,notes) VALUES ($name,$surname,$number,$mail,$note)";
$con->query($sql);
if you help me it would be great, thank you.
Put single quote(') in values like this
$sql = "INSERT INTO customersinfo (name,surname,number,email,notes) VALUES ('$name','$surname','$number','$mail','$note')";
You are checking just $sql variable which doesn't provide sql resul, it's just a query.
Try
$result = $con->query($sql);
if($result)
{
echo "Succesful";
}else{
echo "error";
}
More proper way:
$sql = "INSERT INTO `customersinfo`
(`name`,`surname`,`number`,`email`,`notes`) VALUES
('{$name}','{$surname}','{$number}','{$mail}','{$note}')";
$result=$con->query($sql);
if (!$result) {
// Query has failed
}
You checked $sql in if condition which is not right because $sql is always true so that u get the result successful but actually value is not getting inserted in database.
take the result in some variable and used that in if condition.
after that you will get what actual error in your code.

Issues with PHP while statement

I'm attempting to run a while statement that will set a column in a mysql database, based on a uniqueID.
I've done this many times, and I'm not sure what I am doing wrong this time.
Basically, it works properly until I actually tell it to save the table. Here is my code
$alertAdmin = mysqli_query($con, "SELECT * FROM tickets WHERE notified='0'");
$tcheckNotifs = mysqli_num_rows($alertAdmin);
if($tcheckNotifs > 0) {
echo "test<br><br>";
while($row = mysqli_fetch_array($alertAdmin))
{
$Unique = $row['UniqueID'];
echo $Unique.' ';
$sql = "UPDATE tickets SET `notified`='1' WHERE `UniqueID`='$Unique'";
//mysqli_query($con, $sql);
}
}
And this works for echoing the UniqueID, and it echos the correct one. The problem comes in when I uncomment the mysqli_query($con, $sql);
in which case, nothing inside the loop is echo'd, but it DOES save the database.
For example:
Lets say this while statement loops through and finds 3 iterations of rows that have notified equal to 0 (UniqueID's 29, 26, 25), while the mysqli_query is commented, it will display these numbers on the page just fine. But as soon as I uncomment it, the database will save but it does not display any of the rest of the while loop on the page.
I need this desperately, because I plan to send a desktop notification at the same time the loop is played.
FOLLOW UP:
It also does not display the echo "test<br><br>"; on the page when the query is uncommented either.
Another follow up:
The query is saving all the data like its meant to. The problem is nothing else inside the tcheckNotifs IF statement are showing (echo's and such), like they aren't being executed. Almost like the end of the while statement is executing before anything else, including the "test" echo before the while statement.
Could anyone help me figure out why this isn't working as expected?
Here is all of my current code, with some suggestions from you guys added in, but still not working properly.
The while statement will save the query, but no other output is shown on the page.
$configs = include("config.php");
$con = mysqli_connect($configs['SQL-Host'], $configs['SQL-User'], $configs['SQL-Pass'], $configs['SQL-Database']) or die("Error " . mysqli_error($con));
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
$alertAdmin = mysqli_query($con, "SELECT * FROM tickets WHERE notified='0'");
$tcheckNotifs = mysqli_num_rows($alertAdmin);
if($tcheckNotifs > 0) {
echo "test<br><br>";
flush(); ob_flush();
while($row = mysqli_fetch_array($alertAdmin))
{
$Unique = $row['UniqueID'];
echo $Unique.' ';
updateTickets($con, $Unique);
}
echo "test<br><br>";
}
function updateTickets($con, $id){
$sql = "UPDATE tickets SET notified=1 WHERE UniqueID=$id";
mysqli_query($con, $sql);
}
FINAL UPDATE
With the help of Alex Andrei as well, we moved to PDO
$dsn = 'mysql:dbname=domains;host=localhost';
$user = 'root';
$password = '';
try {
$db = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$st = $db->prepare('SELECT UniqueID FROM tickets WHERE notified=0');
$st->execute();
$result = $st->fetchAll(PDO::FETCH_ASSOC);
foreach($result as $d){
echo $d['UniqueID'] . "<br/>";
$id = $d['UniqueID'];
$st = $db->prepare("UPDATE tickets SET notified=1 WHERE UniqueID=$id");
$st->execute();
}
SECOND UPDATE
Try putting your query in a variable and run the loop like this...
while($row = mysqli_fetch_array($alertAdmin))
{
$Unique = $row['UniqueID'];
echo $Unique.' ';
$sql = "UPDATE tickets SET notified=1 WHERE UniqueID=$Unique";
$update = mysqli_query($con, $sql);
}
UPDATE
There is a chance the query runs first like you said. Maybe you can create an independent function to run the query and call the function from inside the while loop.
function updateTickets($con, $id){
$sql = "UPDATE tickets SET notified=1 WHERE UniqueID=$id";
mysqli_query($con, $sql);
}
And your loop would look like this...
while($row = mysqli_fetch_array($alertAdmin))
{
$Unique = $row['UniqueID'];
echo $Unique.' ';
updateTickets($con, $Unique);
}
ORIGINAL ANSWER
I would modify your query like this...
$sql = "UPDATE tickets SET notified=1 WHERE UniqueID=$Unique";
You do not need all the back ticks nor single quotes here. Might be causing an issue.
Also, I assume 1 is an integer so no need to quote that.
The Fix: PDO OF COURSE!
$configs = include("config.php");
$dsn = 'mysql:dbname='.$configs['SQL-Database'].';host='.$configs['SQL-Host'].'';
$user = $configs['SQL-User'];
$password = $configs['SQL-Pass'];
try {
$db = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$st = $db->prepare('SELECT UniqueID FROM tickets WHERE notified=0');
$st->execute();
$result = $st->fetchAll(PDO::FETCH_ASSOC);
foreach($result as $d){
echo $d['UniqueID'] . "<br/>";
$id = $d['UniqueID'];
$st = $db->prepare("UPDATE tickets SET notified=1 WHERE UniqueID=$id");
$st->execute();
}
$sql = "UPDATE tickets SET notified='1' WHERE UniqueID='$Unique'";
The error I think it's here. You can't use $Unique between single quotes (although you already are between double quotes).
Try to fixing this replacing the line with:
$sql = "UPDATE tickets SET `notified`='1' WHERE `UniqueID`=$Unique";
Firstly in your query you are passing a string in: ...WHERE "UniqueID"="$Unique" because of the quotes around your php variable. So your query looks like this: WHERE UniqueID = "10". Not a big deal but generally if your looking up a number your should drop the quotes.
And i suspect something is causing your query in the loop to fail, so add something to check for errors:
if(!$queryResult){
echo $con->error;
}
Run the loop and see if something is causing errors in your query. But really you should get rid of most of the backticks you have in your queries.

Trying to convert old mysql code to mysqli

I'm having to convert my inspection app to MySQLi but have been having many issues doing so since Amazon EC2 updated their MySQL
With not knowing much about php/mysql to begin with, I'm at a loss. Most of my searches have been way beyond what I understand.
This is what the file used to look like.
<?php
include("connect.php"); // Connect to RDS
$query="SELECT id, username, oldurl, homedata, clientemail, general_info, company_name, company_hours, company_phone, company_support_email, beyondscope FROM inspector WHERE username='{$_SESSION['username']}' ";
$result=mysql_query($query);
$num = mysql_num_rows ($result);
$username = mysql_result($result,$i,"username");
$oldurl = mysql_result($result,$i,"oldurl");
$homedata = mysql_result($result,$i,"homedata");
$clientemail = mysql_result($result,$i,"clientemail");
$general_info = mysql_result($result,$i,"general_info");
$company_name = mysql_result($result,$i,"company_name");
$company_hours = mysql_result($result,$i,"company_hours");
$company_phone = mysql_result($result,$i,"company_phone");
$company_support_email = mysql_result($result,$i,"company_support_email");
$beyondscope = mysql_result($result,$i,"beyondscope");
mysql_close();
?>
This is what I have so far. One error I'm getting line 17 has unexpected ',' (comma), even that every line has the same setup.
Thanks in advance for any help with this.
<?php
include("connect.php"); // Connect to RDS
$query="SELECT id, username, oldurl, homedata, clientemail, general_info, company_name, company_hours, company_phone, company_support_email, beyondscope FROM inspector WHERE username='{$_SESSION['username']}' ";
$result=mysqli_query($GLOBALS["___mysqli_ston"], $query);
$num = mysqli_num_rows($result);
$username = mysqli_fetch_array($result,$i,"username");
$oldurl = mysqli_fetch_array($result,$i,"oldurl");
$homedata = mysqli_fetch_array($result,$i,"homedata");
$clientemail = mysqli_fetch_array($result,$i,"clientemail");
$general_info = mysqli_fetch_array($result,$i,"general_info");
$company_name = mysqli_fetch_array($result,$i,"company_name");
$company_hours = mysqli_fetch_array($result,$i,"company_hours");
$company_phone = mysqli_fetch_array($result,$i,"company_phone");
$company_support_email = ($result,$i, "company_support_email");
$beyondscope = mysqli_fetch_array($result,$i,"beyondscope");
((is_null($___mysqli_res = mysqli_close($GLOBALS["___mysqli_ston"]))) ? false : $___mysqli_res);
?>
UPDATE: To add connect.php
<?php
$hostname='.rds.amazonaws.com';
$user='username';
$pass='password';
$dbase='dbasename';
$connection = ($GLOBALS["___mysqli_ston"] = mysqli_connect("$hostname" , "$user" , "$pass"))
or die ("Can't connect to MySQL");
$db = ((bool)mysqli_query( $connection, "USE " . $dbase)) or die ("Can't select database.");
?>
I've taken the liberty of rebuilding a bit on how you fetch your values, this should be a bit more easier to read and (in my opinion) a better structure. Also, you can specify the database in your connection, like this (just makes for easier reading, up to you really).
$connection = mysqli_connect($hostname, $user, $pass, $dbase);
if (!$connection) {
echo "An error occurred connecting to the database.";
exit;
}
Below is how your query could look. This will loop through all the results, and put them into the variables, only if we actually have a result.
<?php
include "connect.php"; // Connect to RDS
$query = "SELECT id, username, oldurl, homedata, clientemail, general_info, company_name, company_hours, company_phone, company_support_email, beyondscope FROM inspector WHERE username='{$_SESSION['username']}' ";
if (!$result = mysqli_query($connection, $query)) {
// An error occured, do something
// This means no results could be fetched
}
$num = mysqli_num_rows($result);
if (!$result) { // This means that we only fetch if we have a result
while($row = mysqli_fetch_assoc($result)) {
// Fetching all the rows
$username = $row['username'];
$oldurl = $row['oldurl'];
$homedata = $row['homedata '];
$clientemail = $row['clientemail'];
$general_info = $row['general_info'];
$company_name = $row['company_name'];
$company_hours = $row['company_hours'];
$company_phone = $row['company_phone'];
$company_support_email = $row['company_support_email'];
$beyondscope = $row['beyondscope'];
}
}
?>
JFYI.
There is absolutely no point in converting your inspection app to MySQLi the way it offered in the other answer.
The only point in such a conversion is to make your queries safe while with such a direct conversion it remained congenially vulnerable. So, you might saved yourself a lot of trouble by leaving this code alone, with exactly the same outcome.
Proper way is described in this answer, but you will have to find another volunteer to write a code for you.

how to insert value from radio button into mysql using php

i have tried this code to insert value into database, but i don't Know why, the value was not send into the databases. The table i have created in the mysql :
<?php
require_once "connection.php";
$conn = connect();
$db = connectdb();
mysql_select_db($db,$conn) or die (mysql_error() . "\n");
$query_usr = "select * from soalselidik";
$usr = mysql_query($query_usr,$conn) or die(mysql_error()."\n".$query_usr);
$row_usr=mysql_fetch_assoc($usr);
//to insert in database
$a1=$_POST['a1'];
$a2=$_POST['a2'];
$a3=$_POST['a3'];
$a4=$_POST['a4'];
$b1=$_POST['b1'];
$b2=$_POST['b2'];
$b3=$_POST['b3'];
$b4=$_POST['b4'];
$c1=$_POST['c1'];
$c2=$_POST['c2'];
$c3=$_POST['c3'];
$c4=$_POST['c4'];
$d1=$_POST['d1'];
$d2=$_POST['d2'];
$d3=$_POST['d3'];
$d4=$_POST['d4'];
$e1=$_POST['e1'];
$f1=$_POST['f1'];
echo $query ="insert into soalselidik (a1,a2,a3,a4,b1,b2,b3,b4,c1,c2,c3,c4,d1,d2,d3,d4,e1,f1) values('$a1','$a2','$a3','$a4','$b1','$b2','$b3','$b4','$c1','$c2','$c3','$c4''$d1','$d2','$d3','$d4','$e1','$f1')";
$result = mysql_query($query);
echo "<script languange = 'Javascript'>
alert('thankyou ! Penilaian anda diterima ');
location.href = 'home.php';</script>";
?>
'$c4''$d1'
Find that in your query and fix it :) And please do some error checking, and please stop using MySQL_* for your own good. Why should people not run any error checking mechanism that's already provided in the language and expect others to debug typos?
In case you didn't get it, there's a comma missing
How can I prevent SQL injection in PHP?

Update existing mysql record using php

Trying to update existing records in phpMyAdmin, but the following code doesn't seem to be working.
<?php
$id = stripslashes($_POST['id']);
$title = stripslashes($_POST['title']);
$first = stripslashes($_POST['first']);
$surname = stripslashes($_POST['surname']);
$email = stripslashes($_POST['email']);
$promotion = stripslashes($_POST['promotion']);
$maths11 = stripslashes($_POST['maths11']);
$english11 = stripslashes($_POST['english11']);
$english13 = stripslashes($_POST['english13']);
$science13 = stripslashes($_POST['science13']);
$maths133 = stripslashes($_POST['maths133']);
$maths132 = stripslashes($_POST['maths132']);
$address = stripslashes($_POST['address']);
$address2 = stripslashes($_POST['address2']);
$town = stripslashes($_POST['town']);
$county = stripslashes($_POST['county']);
$code = stripslashes($_POST['code']);
$tel = stripslashes($_POST['tel']);
//database connection
$query="UPDATE Promotions SET address='$address', address2='$address2', town='$town', county='$county', postcode='$code', tel='$tel' WHERE id = '$id'";
mysql_query($query) or die(mysql_error());
include 'confirm.php';
include 'registerEmail.php';
?>
Any help? Thanks
Instead of rather useless die ('Error updating database'); handle your errors in more informative way
mysql_query($query) or trigger_error(mysql_error().' in '.$query);
and read what it says
Use mysql_error() like Col. Shrapnel showed.
But what troubles me ... Is that all the code for that page? Because you have //database connection but I don't see any database connection. Are you sure you are connecting to your database and included that connection in your file?
EDIT:
what does your query look like when you echo it? maybe the id is empty ... that way you can see what exactly is going to be send to the db
echo $query;

Categories