can someone please help me with this update table - php

I would like to update my database table with first name and last name where email is equal to session email but I cant update the table where the email is equal to the signed in email of the user please help me.
<?php
session_start();
if(!session_is_registered(email)){
header("location: login.html");
}?>
<?php
echo"<a href = logout.php> Logout </a>";
?>
<?php
include('config.php');
session_start();
if(isset($_SESSION['email'])) {
echo "Welcome ".$_SESSION['email']."";
}
?>
<?php
$dbhost = 'localhost';
$dbuser = 'user';
$dbpass = 'password';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql="UPDATE nametable SET fname='$fname', lname='$lname' WHERE email='" . $_SESSION ['email'] . "'";
echo $row['fname']." - ".$row['lname']. "<br />";
if($result) {
echo "success";
} else {
echo "no success";
}
mysql_select_db('db');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";
mysql_close($conn);
?>
this id the data that is going to be submitted depending on the first name and last name that is is going to be updated don't worry about the other tags I just put this together to get an idea of what is going to be updated on the above code please tell me what I did wrong
<html>
<head>
<title>Update a Record in MySQL Database</title>
</head>
<body>
<form method="post" action="update1.php">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<td width="100"> first name</td>
<td><input name="fname" type="text" id="fname"></td>
</tr>
<tr>
<td width="100">last name</td>
<td><input name="lname" type="text" id="lname"></td>
</tr>
<tr>
<td width="100"> </td>
<td> </td>
</tr>
<tr>
<td width="100"> </td>
<td>
<input name="submit" type="submit" id="submit" value="submit">
</td>
</tr>
</table>
</form>
</body>
</html>

First, you need qoutes "" around strings in your SQL
$sql="UPDATE nametable SET fname='$fname', lname='$lname' WHERE email='" . $_SESSION ['email'] . "'";
should be
$sql='UPDATE nametable SET fname="'.$fname.'", lname="'.$lname.'" WHERE email="'.$_SESSION['email'].'"';
next, you are not executing the query at all. Think you in the following
echo $row['fname']." - ".$row['lname']. "<br />";
if($result) {
echo "success";
} else {
echo "no success";
}
really mean :
$result = mysql_query($sql);
if (mysql_affected_rows()>-1) {
// success
// do here what you want
}

I think session_is_registered function is already deprecated so instead of
session_is_registered('email')
You might want to use:
if ( isset( $_SESSION['email'] ) ){}
and in one page of php you can only have 1 session_start() function.
If it's still not working, try to debug your code by printing out the $sql variable.
Let me know if that help.

Related

Add Edit Delete form not adding into MySQL no errors

I have this Add Edit Delete form, the problem is:
when I put everything and I click on ADD it says "Data added successfully." but the data isn't in my table of phpAdmin and it not shows in the page...
Or is simply because my hoster doens't work with MySQLi but with MySQL?
Without talking about SQL Injections because Im not so expert and dont know how protect from that, this pages will be protected with login area so only restricted members will access to it.
index.php
<?php
//including the database connection file
include_once("config.php");
//fetching data in descending order (lastest entry first)
//$result = mysql_query("SELECT * FROM users ORDER BY id DESC"); // mysql_query is deprecated
$result = mysqli_query($mysqli, "SELECT * FROM `user` ORDER BY id DESC"); // using mysqli_query instead
?>
<html>
<head>
<title>Homepage</title>
</head>
<body>
Add New Data<br/><br/>
<table width='80%' border=0>
<tr bgcolor='#CCCCCC'>
<td>Steam Username</td>
<td>Steam Password</td>
<td>Steam Guard Code</td>
<td>Update</td>
</tr>
<?php
//while($res = mysql_fetch_array($result)) { // mysql_fetch_array is deprecated, we need to use mysqli_fetch_array
while($res = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>".$res['steamUE']."</td>";
echo "<td>".$res['steamPW']."</td>";
echo "<td>".$res['steamGC']."</td>";
echo "<td>Edit | Delete</td>";
}
?>
</table>
</body>
</html>
add.html
<html>
<head>
<title>Add Data</title>
</head>
<body>
Home
<br/><br/>
<form action="add.php" method="post" name="form1">
<table width="25%" border="0">
<tr>
<td>Steam Username</td>
<td><input type="text" name="steamUE"></td>
</tr>
<tr>
<td>Steam Password</td>
<td><input type="text" name="steamPW"></td>
</tr>
<tr>
<td>Steam Guard Code</td>
<td><input type="text" name="steamGC"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="Submit" value="Add"></td>
</tr>
</table>
</form>
</body>
</html>
edit.php
<?php
// including the database connection file
include_once("config.php");
if(isset($_POST['update']))
{
$id = mysqli_real_escape_string($mysqli, $_POST['id']);
$steamUE = mysqli_real_escape_string($mysqli, $_POST['steamUE']);
$steamPW = mysqli_real_escape_string($mysqli, $_POST['steamPW']);
$steamGC = mysqli_real_escape_string($mysqli, $_POST['steamGC']);
// checking empty fields
if(empty($steamUE) || empty($steamPW) || empty($steamGC)) {
if(empty($steamUE)) {
echo "<font color='red'>Steam Username field is empty.</font><br/>";
}
if(empty($steamPW)) {
echo "<font color='red'>Steam Password field is empty.</font><br/>";
}
if(empty($steamGC)) {
echo "<font color='red'>Steam Guard Code field is empty.</font><br/>";
}
} else {
//updating the table
$result = mysqli_query($mysqli, "UPDATE `user` SET steamUE='$steamUE',steamPW='$steamPW',steamGC='$steamGC' WHERE id='$id'");
//redirectig to the display page. In our case, it is index.php
header("Location: index.php");
}
}
?>
<?php
//getting id from url
$id = $_GET['id'];
//selecting data associated with this particular id
$result = mysqli_query($mysqli, "SELECT * FROM `user` WHERE id='$id'");
while($res = mysqli_fetch_array($result))
{
$steamUE = $res['steamUE'];
$steamPW = $res['steamPW'];
$steamGC = $res['steamGC'];
}
?>
<html>
<head>
<title>Edit Data</title>
</head>
<body>
Home
<br/><br/>
<form name="form1" method="post" action="edit.php">
<table border="0">
<tr>
<td>Steam Username</td>
<td><input type="text" name="steamUE" value="<?php echo $steamUE;?>"></td>
</tr>
<tr>
<td>Steam Username</td>
<td><input type="text" name="steamPW" value="<?php echo $steamPW;?>"></td>
</tr>
<tr>
<td>Steam Guard Code</td>
<td><input type="text" name="steamGC" value="<?php echo $steamGC;?>"></td>
</tr>
<tr>
<td><input type="hidden" name="id" value=<?php echo $_GET['id'];?>></td>
<td><input type="submit" name="update" value="Update"></td>
</tr>
</table>
</form>
</body>
</html>
delete.php
<?php
//including the database connection file
include("config.php");
//getting id of the data from url
$id = $_GET['id'];
//deleting the row from table
$result = mysqli_query($mysqli, "DELETE * FROM `user` WHERE id='$id'");
//redirecting to the display page (index.php in our case)
header("Location: index.php");
?>
add.php
<html>
<head>
<title>Add Data</title>
</head>
<body>
<?php
//including the database connection file
include_once("config.php");
if(isset($_POST['Submit'])) {
$steamUE = mysqli_real_escape_string($mysqli, $_POST['steamUE']);
$steamPW = mysqli_real_escape_string($mysqli, $_POST['steamPW']);
$steamGC = mysqli_real_escape_string($mysqli, $_POST['steamGC']);
// checking empty fields
if(empty($steamUE) || empty($steamPW) || empty($steamGC)) {
if(empty($steamUE)) {
echo "<font color='red'>Steam Username field is empty.</font><br/>";
}
if(empty($steamPW)) {
echo "<font color='red'>Steam Password field is empty.</font><br/>";
}
if(empty($steamGC)) {
echo "<font color='red'>Steam Guard Code field is empty.</font><br/>";
}
//link to the previous page
echo "<br/><a href='javascript:self.history.back();'>Go Back</a>";
} else {
// if all the fields are filled (not empty)
//insert data to database
$result = mysqli_query($mysqli, "INSERT INTO `user` (steamUE,steamPW,steamGC) VALUES ('$steamUE','$steamPW','$steamGC')");
//display success message
echo "<font color='green'>Data added successfully.";
echo "<br/><a href='index.php'>View Result</a>";
}
}
?>
</body>
</html>
config.php
<?php
/*
// mysql_connect("database-host", "username", "password")
$conn = mysql_connect("localhost","root","root")
or die("cannot connected");
// mysql_select_db("database-name", "connection-link-identifier")
#mysql_select_db("test",$conn);
*/
/**
* mysql_connect is deprecated
* using mysqli_connect instead
*/
$databaseHost = 'sql.website.com';
$databaseName = '';
$databaseUsername = '';
$databasePassword = '';
$mysqli = mysqli_connect($databaseHost, $databaseUsername, $databasePassword, $databaseName);
?>
It not doesn't says or shows any errors or any other problems, it says only data added successfully and nothing else. I don't understand why it doesn't add any data in my tables, i checked everything again and again, maybe because i'm tired but i tried to rename tables names but nothing change, is the same...
Spotted three errors,
add.php: Column names should be without ''. Check the following
$result = mysqli_query($mysqli, "INSERT INTO user (steamUE,steamPW,steam_GC) VALUES ('$steamUE','$steamPW','$steamGC')");
edit.php: '' missing from $id. Check the following
$result = mysqli_query($mysqli, "UPDATE user SET steamUE='$steamUE',steamPW='$steamPW',steamGC='$steamGC' WHERE id='$id'");
delete.php: '' missing from $id. Check the following
$result = mysqli_query($mysqli, "DELETE * FROM user WHERE id='$id'");
If the connection with DB is successful, it must work (and this answer deserves a green tick from you :D).
Or is simply because my hoster doens't work with MySQLi but with
MySQL?
Wherever I faced issues, I got some error or a blank page.
Check your dB connection. Turn to mysqli, declair it with $sql with (errno), but call your param before $sql. Use if condition to check your connection. On your add please use prepared with $stmnt and execute it.

adding record to MYSQL database wont work in PHP

Ive written PHP code to add a record to my database. When I click on the save button, then it should say "saved successfully", But all that happens is that the page refreshes with no added records in the database and no "saved successfully" message pops up.
My database connection works properly. So I cant figure out what the problem could be.
here is the PHP code:
<?php
error_reporting(0);
$con = mysqli_connect("localhost", "root", "password") or die("error");
if($con) {
mysqli_select_db("maplibrary",$con);
}
if (isset($_POST["save"])) {
$sql = mysqli_query("INSERT INTO member (memberID, firstName, surname, contactDetails)
VALUES('{$_POST['memberID']}',
'{$_POST['firstName']}',
'{$_POST['surname']}',
'{$_POST['contactDetails']}'
)");
if ($sql) {
echo "save successfully";
}
}
?>
here is the HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>ViewMembers</title>
</head>
<body>
<form action="" method="post">
<table style="border:1 #F00 solid;width:500px;overflow:auto;margin:auto;background:#999;">
<tr>
<td>Member ID</td>
<td><input type="text" name"memberID" /></td>
</tr>
<tr>
<td>First Name</td>
<td><input type="text" name"firstName" /></td>
</tr>
<tr>
<td>Surname</td>
<td><input type="text" name"surname" /></td>
</tr>
<tr>
<td>Contact Details</td>
<td><input type="text" name"contactDetails" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Save" name="save" /></td>
</tr>
</table>
</form>
</body>
</html>
You didn't add $conn as parameter of mysqli_query function.See usage :
http://www.w3schools.com/php/func_mysqli_query.asp
<?php
error_reporting(0);
$con = mysqli_connect("localhost","root","password") or die("error");
if($con)
{
mysqli_select_db("maplibrary",$con);
}
if (isset($_POST["save"]))
{
$sql = mysqli_query($con, "INSERT INTO member
(memberID,firstName,surname,contactDetails)
VALUES('{$_POST['memberID']}',
'{$_POST['firstName']}',
'{$_POST['surname']}',
'{$_POST['contactDetails']}'
)");
if ($sql)
{
echo "save successfully";
}
}
?>
Try this one:
<?php
$servername = "localhost";
$username = "username";//YOUR USER NAME!
$password = "password";//YOUR PASSWORD!
$dbname = "myDB"; //YOUR DB NAME!
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST["save"])){
$var1 = $_POST['memberID'];
$var2 = $_POST['firstName'];
$var3 = $_POST['surname'];
$var4 = $_POST['contactDetails'];
$sql = "INSERT INTO member(memberID,firstName,surname,contactDetails)
VALUES ('".$var1."', '".$var2."', '"$var3."', '"$var4."')";
if ($conn->query($sql) === TRUE) {echo "successfully saved";}
else {echo "Error: " . $sql . "<br>" . $conn->error;}
}
$conn->close();
?>
hope i understood your problem... :)
BTW i suggest you to create a php file that will contain only the connection, because you may will need to connect to the database again in some point so you do not want to copy your code again and again...
so you can create a connect.php that will contain only the connection lines, you can include it (connect.php) inside of any page you want. it will make kit much easier.
look at: php include

How do I update a specific row in a table using php form?

Please bear with me, I'm not familiar yet with the language. I have a table that lists an applicant record such as applicant number, name and status. I want to update an applicant status either 'hired' or 'failed' on a specific row using a PHP form. However, I'm not sure how to get the specific submit name on its row upon submission. Or if you have a workaround I would appreciate that. Thank you so much for your help.
<!DOCTYPE html>
<html>
<h2>Applicant Records</h2>
<?php
$mysql_hostname = "localhost";
$mysql_user = "root";
$mysql_password ="";
$mysql_database = "applicantrecord";
// Create connection
$conn = new mysqli($mysql_hostname, $mysql_user, $mysql_password, $mysql_database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sqli = "SELECT id, firstname, lastname, status FROM applicant";
$result = $conn->query($sqli);
if ($result->num_rows > 0) { ?>
<table class="table">
<thead>
<tr>
<th>Applicant No.</th>
<th>Lastname</th>
<th>Firstname</th>
<th>Status</th>
<th></th>
</tr>
</thead>
<?php
// output data of each row
echo "<tbody>";
while($row = $result->fetch_assoc())
{ ?>
<tr>
<td>
<?php echo $row["id"];
$appid = $row["id"];
?>
</td>
<td>
<?php echo $row["lastname"]; ?>
</td>
<td>
<?php echo $row["firstname"]; ?>
</td>
<td>
<?php echo $row["status"]; ?>
</td>
<td>
</td>
<td>
<div>
<form action="" role="form" method="post" name="form<?php echo $appid; ?>">
<select name="applicant_status">
<option value="Hired">Hire</option>
<option value="Failed">Fail</option>
</select>
</p>
<button type="submit" class="btn btn-default" name = "submit<?php echo $appid; ?>" data-dismiss="modal">Submit</button>
</form>
<?php
if(isset($_POST["submit"])){
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$newappid = $appid;
$newapptstatus = $_POST['applicant_status'];
$connect = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $connect ) {
die('Could not connect: ' . mysql_error());
}
$sql_sub = "UPDATE applicant ". "SET status = '$newappstatus'".
"WHERE id = '$newappid'" ;
mysql_select_db('applicantrecord');
$retval = mysql_query( $sql_sub, $connect );
if(! $retval ) {
die('Could not update data: ' . mysql_error());
echo "<script type= 'text/javascript'>alert('An error occured! Applicant status update failed!');</script>";
}
echo "<script type= 'text/javascript'>alert('Applicant status updated successfully!');</script>";
mysql_close($connect);
}
?>
</div>
</td>
</tr>
<?php }
echo "</tbody>";
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
</html>
In your if statement where you check that $_POST['submit'] is set, the index 'submit' does not exist. Thus isset($_POST['submit']) evaluates to false and your query to update the table is never being executed.
The variable $appid is being changed with each row that is added, so when the page is done loading and the submit button is pushed on a certain row, $appid won't necessarily contain the correct row number.
To get around this, you could use a hidden input in your form:
<input name="id" value="<?php echo $appid ?>" type="hidden">
Then you can replace isset($_POST['submit']) with isset($_POST['id']) and set $newappid = $_POST['id'] to get the row number to be changed.

MySQL update query makes new table row instead of updating table row

When trying to make an edit page for a table in PHP, I'm running into a problem on the edit.php page where when I click edit table row button, it brings me to the correct page obviously (edit.php), and then when I enter in the edited details and submit it, it makes a whole new table row entry instead of update the one I had selected for it to update.
I have checked to make sure the id is set correctly to the correct table row in the database and it is. I have no idea why it is doing this. Any help would greatly be appreciated.
<?php require("manage_post.php"); ?>
<?php
session_start();
if(!isset($_SESSION['userName'])){ //if login in session is not set
header("Location: login.php");
exit();
}
?>
<?php
$con = mysql_connect("localhost","root","");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("cad", $con)
or die('Could not select database');
$query="SELECT `town`, `location`, `incident_type`, `time_date`, `admin`, `id`
FROM `cad`
WHERE `id` =
$_GET[id]";
$result=mysql_query($query)
or die(mysql_error());
while( false!=($row=mysql_fetch_array($result)) )
{
echo '<h1>Town name: ', htmlspecialchars($row['town']), '</td>';
}
$town=$row['town'] ;
$location= $row['location'] ;
$incident_type=$row['incident_type'] ;
if(isset($_POST['save']))
{
$town = $_POST['town'];
$location = $_POST['location'];
$incident_type = $_POST['incident_type'];
mysql_query("UPDATE cad SET town ='{$town}', location ='{$location}',
incident_type ='{$incident_type}' WHERE `id` = $_GET[id]") or die(mysql_error());
echo "Saved! Redirecting back to the home page.";
}
mysql_close($con);
$id=$_GET['id'];
?>
<!DOCTYPE html>
<html>
<head>
<title>Edit Incident</title>
</head>
<body>
<?php
echo "<h1>You are editing incident number # $id</h1>";
?>
<form method="post">
<table>
<tr>
<td>Town</td>
<td><input type="text" name="town" value="<?php echo $town; ?>"/></td>
</tr>
<tr>
<td>Location</td>
<td><input type="text" name="location" value="<?php echo $location; ?>"/></td>
</tr>
<tr>
<td>Incident Type</td>
<td><input type="text" name="incident_type" value="<?php echo $incident_type; ?>"/></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="save" value="Save" /></td>
</tr>
</table>
</body>
</html>
You have to use query like below
mysql_query("UPDATE cad SET town ='{$town}', location ='{$location}',
incident_type ='{$incident_type}' WHERE `id` = {$_GET['id']}") or die(mysql_error()); ;
Add new hidden key to post
<input type="hidden" name="savedid" value="<?php echo $_GET['id']?>" />
And in the update sql
$town = $_POST['town'];
$location = $_POST['location'];
$incident_type = $_POST['incident_type'];
$savedid = $_POST['savedid'];
mysql_query("UPDATE cad SET town ='{$town}', location ='{$location}',
incident_type ='{$incident_type}' WHERE `id` = $savedid") or die(mysql_error());
echo "Saved! Redirecting back to the home page.";
and you should filter your vars if security concerns you consider using intval for ids

How to update the value from PHP variable into database

everyone.
I have a problem with updating value into database.
Now, I have $SumTotal as a PHP variable. I want to update value in database by using value in $SumTotal.
I try it but it doesn't work. The value in database is 0.
here is my code
$strSQL3 = "UPDATE OrderCustomer SET TotalPrice = '".$SumTotal."' WHERE OrderCustomerID = '".$_SESSION["OrderCustomerID"]."' ";
Thank you very much.
Try using this code, this code should work for you.
{
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$SumTotal="**Some value**";
//**QUERY**
$strSQL3= "UPDATE OrderCustomer".
"SET Totalprice= $SumTotal".
"WHERE emp_id = $emp_id" ;
mysql_select_db('test_db');
$retval = mysql_query( $strSQL3, $conn );
if(! $retval )
{
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";
mysql_close($conn);
}
First of all, I would make sure that $SumTotal and $_SESSION['OrderCustomerID'] are equal to what they are meant to be equal to.
I would do something like: echo "$SumTotal"; and echo $_SESSION['OrderCustomerID']; to check these variables.
Then, you could do the following:
Make sure that the database is actually selected (to select the database in your query, you can use UPDATE databasename.table (where table is equal to OrderCustomer in your case)
Check for errors in your query by adding or die(mysql_error()); to the end of your query.
Use the following at the very top of your PHP document to show all errors that have occurred: https://stackoverflow.com/a/6575502/3593228.
In addition to this, make sure that your query is actually being executed.
You can do this by using the mysql_query function as follows:
$strSQL3 = mysql_query("UPDATE databasename.OrderCustomer SET TotalPrice = '$SumTotal' WHERE OrderCustomerID = '" . $_SESSION["OrderCustomerID"] . "'");
Also, before someone beats me to it, you should be using PDO or MySQL Improved, yada yada yada.
You can have a look at this piece of code.
This will definitely work, i have tried this personally.
Edit: (Pulled from link)
<html>
<head>
<title>Update a Record in MySQL Database</title>
</head>
<body>
<?php
if(isset($_POST['update']))
{
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$emp_id = $_POST['emp_id'];
$emp_salary = $_POST['emp_salary'];
$sql = "UPDATE employee ".
"SET emp_salary = $emp_salary ".
"WHERE emp_id = $emp_id" ;
mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";
mysql_close($conn);
}
else
{
?>
<form method="post" action="<?php $_PHP_SELF ?>">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<td width="100">Employee ID</td>
<td><input name="emp_id" type="text" id="emp_id"></td>
</tr>
<tr>
<td width="100">Employee Salary</td>
<td><input name="emp_salary" type="text" id="emp_salary"></td>
</tr>
<tr>
<td width="100"> </td>
<td> </td>
</tr>
<tr>
<td width="100"> </td>
<td>
<input name="update" type="submit" id="update" value="Update">
</td>
</tr>
</table>
</form>
<?php
}
?>
</body>
</html>

Categories