PHP/MySQL allowing current user to edit their account information - php

I have created 2 pages
update.php
edit.php
We start on edit.php so here is edit.php's script
<?php
session_start();
$id = $_SESSION["id"];
$username = $_POST["username"];
$fname = $_POST["fname"];
$password = $_POST["password"];
$email = $_POST["email"];
mysql_connect('mysql13.000webhost.com', 'a2670376_Users', 'Password') or die(mysql_error());
echo "MySQL Connection Established! <br>";
mysql_select_db("a2670376_Pass") or die(mysql_error());
echo "Database Found! <br>";
$query = "UPDATE members SET username = '$username', fname = '$fname',
password = '$password' WHERE id = '$id'";
$res = mysql_query($query);
if ($res)
echo "<p>Record Updated<p>";
else
echo "Problem updating record. MySQL Error: " . mysql_error();
?>
<form action="update.php" method="post">
<input type="hidden" name="id" value="<?=$id;?>">
ScreenName:<br> <input type='text' name='username' id='username' maxlength='25' style='width:247px' name="username" value="<?=$username;?>"/><br>
FullName:<br> <input type='text' name='fname' id='fname' maxlength='20' style='width:248px' name="ud_img" value="<?=$fname;?>"/><br>
Email:<br> <input type='text' name='email' id='email' maxlength='50' style='width:250px' name="ud_img" value="<?=$email;?>"/><br>
Password:<br> <input type='text' name='password' id='password' maxlength='25' style='width:251px' value="<?=$password;?>"/><br>
<input type="Submit">
</form>
Now here is the update.php page where I am having the major problem
<?php
session_start();
mysql_connect('mysql13.000webhost.com', 'a2670376_Users', 'Password') or die(mysql_error());
mysql_select_db("a2670376_Pass") or die(mysql_error());
$id = (int)$_SESSION["id"];
$username = mysql_real_escape_string($_POST["username"]);
$fname = mysql_real_escape_string($_POST["fname"]);
$email = mysql_real_escape_string($_POST["email"]);
$password = mysql_real_escape_string($_POST["password"]);
$query="UPDATE members
SET username = '$username', fname = '$fname', email = '$email', password = '$password'
WHERE id='$id'";
mysql_query($query)or die(mysql_error());
if(mysql_affected_rows()>=1){
echo "<p>($id) Record Updated<p>";
}else{
echo "<p>($id) Not Updated<p>";
}
?>
Now on edit.php I fill out the form to edit the account "test" while I am logged into it now once the form if filled out I click on Submit button
and it takes me to update.php and it returns this
(0) Not Updated
(0) <= id of user logged in
Not Updated <= MySql Error from
mysql_query($query)or die(mysql_error());
if(mysql_affected_rows()>=1){
I want it to update the user logged in and if I am not mistaken in this script it says
$id = (int)$_SESSION["id"];
which updates the user with the id of the person who is logged in
but it isn't updating, its saying that no tables were effected
if it helps here's my MySQL Database picture
just click here http://i50.tinypic.com/21juqfq.png
if this could possibly be any help to find the solution I have 2 more files delete.php and delete_ac.php they have can remove users from my sql database and they show the user id and it works there are no bugs in this script at all PLEASE DO NOT MAKE SUGGESTIONS FOR THE SCRIPTS BELOW
delete.php first
<?php
$host="mysql13.000webhost.com"; // Host name
$username="a2670376_Users"; // Mysql username
$password="PASSWORD"; // Mysql password
$db_name="a2670376_Pass"; // Database name
$tbl_name="members"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// select record from mysql
$sql="SELECT * FROM $tbl_name";
$result=mysql_query($sql);
?>
<table border="0" cellpadding="3" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<td colspan="8" style="bgcolor: #FFFFFF"><strong><img src="http://i47.tinypic.com/u6ihk.png" height="30" widht="30">Delete data in mysql</strong> </td>
</tr>
<tr>
<td align="center" bgcolor="#FFFFFF"><strong>Id</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>UserName</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>FullName</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Password</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Email</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Date</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Ip</strong></td>
<td align="center" bgcolor="#FFFFFF"> </td>
</tr>
<?php
while($rows=mysql_fetch_array($result)){
?>
<tr>
<td bgcolor="#FFFFFF"><? echo $rows['id']; ?></td>
<td bgcolor="#FFFFFF"><? echo $rows['username']; ?></td>
<td bgcolor="#FFFFFF"><? echo $rows['fname']; ?></td>
<td bgcolor="#FFFFFF"><? echo $rows['password']; ?></td>
<td bgcolor="#FFFFFF"><? echo $rows['email']; ?></td>
<td bgcolor="#FFFFFF"><? echo $rows['date']; ?></td>
<td bgcolor="#FFFFFF"><? echo $rows['ip']; ?></td>
<td bgcolor="#FFFFFF">delete</td>
</tr>
<?php
// close while loop
}
?>
</table>
<?php
// close connection;
sql_close();
?>
and now delete_ac.php
<table width="500" border="0" cellpadding="3" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<td colspan="8" bgcolor="#FFFFFF"><strong><img src="http://t2.gstatic.com/images? q=tbn:ANd9GcS_kwpNSSt3UuBHxq5zhkJQAlPnaXyePaw07R652f4StmvIQAAf6g" height="30" widht="30">Removal Of Account</strong> </td>
</tr>
<tr>
<td align="center" bgcolor="#FFFFFF">
<?php
$host="mysql13.000webhost.com"; // Host name
$username="a2670376_Users"; // Mysql username
$password="javascript00"; // Mysql password
$db_name="a2670376_Pass"; // Database name
$tbl_name="members"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// get value of id that sent from address bar
$id=$_GET['id'];
// Delete data in mysql from row that has this id
$sql="DELETE FROM $tbl_name WHERE id='$id'";
$result=mysql_query($sql);
// if successfully deleted
if($result){
echo "Deleted Successfully";
echo "<BR>";
echo "<a href='delete.php'>Back to main page</a>";
}
else {
echo "ERROR";
}
?>
<?php
// close connection
mysql_close();
?>
</td>
</tr>
</table>

Try below query, and post output here. Also execute same echo query in phpmyadmin to see what happend.
echo $query="UPDATE members
SET username = '$username', fname = '$fname', email = '$email', password = '$password'
WHERE id=$id";
From your link it seems anyone can directly go to edit page, that is wrong.
You need to add condition that if user is login then only he can update his profile.

Could you check on edit.php if $id is actually set to some value instead of empty? Might be that the id is never stored in the session

Right now your $id is null. (int)$id is 0.
So when you try to update WHERE id=$id you are basically saying WHERE id=0
If id is an Auto Increment Integer then you are not going to have an id=0 and nothing will be updated. You need to create the $_SESSION['id'] by putting something in it.
$_SESSION['id'] = XXXX;

$sqlshow =# mysqli_query($con,"SELECT `id`, `Registration_No`, `First_Name`, `Middle_Name`, `Sir_Name`, `Sex`, `Birth_Day`, `Email`, `Address`, `Phone` FROM `cdtistudent` WHERE id=40"); while($row = #mysqli_fetch_object($sqlshow)) {
update.php page
if(isset($_POST["update"])){
$Registration = $_POST['Registration'];
$First_Name = $_POST['First'];
$Middle_Name = $_POST['Middle'];
$Sir_Name = $_POST['Sir'];
$Sex = $_POST['Sex'];
$Birth_Day = $_POST['Birth'];
$Email = $_POST['Email'];
$Address = $_POST['Address'];
$Phone=$_POST['Phone'];
$id=$_POST['id'];
$sqlupdate =mysqli_query($con,"UPDATE cdtistudent
SET
Registration_No='$Registration',
First_Name='$First_Name',
Middle_Name='$Middle_Name',
Sir_Name='$Sir_Name',
Sex='$Sex',
Birth_Day='$Birth_Day',
Email='$Email',
Address='$Address',
Phone='$Phone'
WHERE id='$id'");
if($sqlupdate === false){
die("".mysqli_error($con));
}}
it look like
UPDATE cdtistudent SET id=[value-1],Registration_No=[value-2],First_Name=[value-3],Middle_Name=[value-4],Sir_Name=[value-5],Sex=[value-6],Birth_Day=[value-7],Email=[value-8],Address=[value-9],Phone=[value-10] WHERE id=?;
and edit.php page
$sqlshow =# mysqli_query($con,"SELECT `id`, `Registration_No`, `First_Name`, `Middle_Name`, `Sir_Name`, `Sex`, `Birth_Day`, `Email`, `Address`, `Phone` FROM `cdtistudent`
WHERE id=40");
while($row = #mysqli_fetch_object($sqlshow))
{

Related

Post Data from One PHP File to Another Gives Error

I have two php files, one file submits data to a second file for an update action into mysql database.
below is the code for the file that submits data
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="test"; // Database name
$tbl_name="test_mysql"; // Table name
$server_name="localhost";
// Create connection
$con = new mysqli($server_name, $username, $password, $db_name , 3306);
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
// get value of id that sent from address bar
$id=$_GET['id'];
// Retrieve data from database
$sql="SELECT * FROM $tbl_name WHERE id='$id'";
$result = $con->query($sql);
$rows = $result->fetch_assoc();
?>
<table width="400" border="0" cellspacing="1" cellpadding="0">
<tr>
<form name="form1" method="post" action="update_ac.php">
<td>
<table width="100%" border="0" cellspacing="1" cellpadding="0">
<tr>
<td> </td>
<td colspan="3"><strong>Update data in mysql</strong> </td>
</tr>
<tr>
<td align="center"> </td>
<td align="center"> </td>
<td align="center"> </td>
<td align="center"> </td>
</tr>
<tr>
<td align="center"> </td>
<td align="center"><strong>Name</strong></td>
<td align="center"><strong>Lastname</strong></td>
<td align="center"><strong>Email</strong></td>
</tr>
<tr>
<td> </td>
<td align="center">
<input name="name" type="text" id="name" value="<?php echo $rows['name']; ?>">
</td>
<td align="center">
<input name="lastname" type="text" id="lastname" value="<?php echo $rows['lastname']; ?>" size="15">
</td>
<td>
<input name="email" type="text" id="email" value="<?php echo $rows['email']; ?>" size="15">
</td>
</tr>
<tr>
<td> </td>
<td>
<input name="id" type="hidden" id="id" value="<?php echo $rows['id']; ?>">
</td>
<td align="center">
<input type="submit" name="Submit" value="Submit">
</td>
<td> </td>
</tr>
</table>
</td>
</form>
</tr>
</table>
<?php
// close connection
$con->close();
?>
the second file for the update action is presented below
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="test"; // Database name
$tbl_name="test_mysql"; // Table name
$server_name="localhost";
// Create connection
$con = new mysqli($server_name, $username, $password, $db_name , 3306);
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
// update data in mysql database
$sql="UPDATE $tbl_name SET name='$name', lastname='$lastname', email='$email' WHERE id='$id'";
$result=$con->query($sql);
// if successfully updated.
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='list_records.php'>View result</a>";
}
else {
echo "ERROR";
}
?>
the error page is presented below.
An suggestions to fix the problem
Well you haven't set those values yet that's why it's getting an error.
First you must wrap your second file to check if it has submitted the form. Then set those variables inside.
<?php
if(isset($_POST['Submit'])) {
$name = $_POST['name'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$id = $_POST['id'];
// rest of your code goes here
}
Make changes to your second file as
<?php
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$id = $_POST['id'];
// add you rest of code
}
You should define some variables before line
$sql="UPDATE $tbl_name SET name='$name', lastname='$lastname', email='$email' WHERE id='$id'";
For example
$tbl_name = 'mytable';
$name = 'ABC';
$lastname = 'XYZ';
$email = 'abc#example.com';
$sql="UPDATE $tbl_name SET name='$name', lastname='$lastname', email='$email' WHERE id='$id'";
User this at top of your request page.
$name=$_POST['name'];
$lastname=$_POST['lastname'];
$email=$_POST['email'];
$id=$_POST['id'];
In your second file where you write sql query to update data,
You are using :-
undefine variable
name, lastname, email, id
get posted value in these variable like that, before sql query:-
$name= $_POST['name'];
$lastname= $_POST['lastname'];

Update Database fails. can't find error (FOUND ERROR)

I want to update a database using this code but it fails every time and I cannot find why the form fails. if someone could help, i would appreciate that alot!!
These are the codes i use to update the DB (these are three files total)
When you go to my editor you will see this screen.(everything works exept the update) it says cannot update data. it doesn't show any other errors.
did i miss something?
<html>
<body>
<?php
session_start(); // Start the session
$loggedin = $_SESSION['loggedin']; // Are they loggedin?
// They are not logged in, Kill the page and ask them to login.
if ($loggedin != "1") {
die('Sorry your not loggedin, please login to gain acces. Here to login');}
?>
<?php
$host=""; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
$tbl_name=""; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql="SELECT * FROM $tbl_name";
$result=mysql_query($sql);
?>
<head>
<style>
div
{
fload:center;
width:1000px;
margin:0 0 15px 20px;
padding:15px;
border:1px solid black;
}
</style>
<div align="center">
</head>
<img src="http://www.emiclaer.nl/Portals/39/Tuinen.jpg" alt="DTlogo.img" width="880" height="280">
</div>
<body style="margin:15px;">
<div>
Druk op <font color="blue"><u>Update</u></font> om de App te Updaten.<br>
<p></p>
<center>
<table width="400" border="0" cellspacing="1" cellpadding="0">
<tr>
<td>
<table width="400" border="1" cellspacing="0" cellpadding="3">
<tr>
<td colspan="4"><strong>Iphone aanbiedingen.</strong> </td>
</tr>
<tr>
<td align="center"><strong>Naam</strong></td>
<td align="center"><strong>Omschrijving</strong></td>
<td align="center"><strong>Prijs</strong></td>
<td align="center"><strong>Promotext</strong></td>
<td align="center"><strong>URL</strong></td>
<td align="center"><strong>Image URL</strong></td>
<td align="center"><strong>Update</strong></td>
</tr>
<?php
while($rows=mysql_fetch_array($result)){
?>
<tr>
<td><? echo $rows['naam']; ?></td>
<td><? echo $rows['omschrijving']; ?></td>
<td><? echo $rows['promotext']; ?></td>
<td><? echo $rows['prijs']; ?></td>
<td><? echo $rows['url']; ?></td>
<td><? echo $rows['iurl']; ?></td>
<td align="center">Update</td>
</tr>
<?php
}
?>
</table>
</td>
</tr>
</table>
<?php
mysql_close();
?>
</div>
</center>
</form>
</body>
</html>
This is the second screen you will go to
<html>
<?php
session_start(); // Start the session
$loggedin = $_SESSION['loggedin']; // Are they loggedin?
// They are not logged in, Kill the page and ask them to login.
if ($loggedin != "1") {
die('Sorry your not loggedin, please login to gain acces. Here to login');}
?>
<?php
$host=""; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
$tbl_name=""; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// get value of id that sent from address bar
$id=$_GET['id'];
// Retrieve data from database
$sql="SELECT * FROM $tbl_name WHERE id='$id'";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);
?>
<head>
<style>
div
{
fload:center;
width:1000px;
margin:0 0 15px 20px;
padding:15px;
border:1px solid black;
}
</style>
<div align="center">
</head>
<img src="http://www.emiclaer.nl/Portals/39/Tuinen.jpg" alt="DTlogo.img" width="880" height="280">
</div>
<body style="margin:15px;">
<div>
Vul hier de updates in.<br>
<p></p>
<center>
<table width="400" border="0" cellspacing="1" cellpadding="0">
<tr>
<td>
<table width="100%" border="0" cellspacing="1" cellpadding="0">
<tr>
<td> </td>
<td colspan="3"><strong>Update Iphone App</strong> </td>
</tr>
<tr>
<td align="center"> </td>
<td align="center"> </td>
<td align="center"> </td>
<td align="center"> </td>
</tr>
<tr>
<td align="center"> </td>
<td align="center"><strong>Naam</strong></td>
<td align="center"><strong>Omschrijving</strong></td>
<td align="center"><strong>Prijs</strong></td>
<td align="center"><strong>Promotext</strong></td>
<td align="center"><strong>URL</strong></td>
<td align="center"><strong>Image URL</strong></td>
<td align="center"><strong>Update</strong></td>
</tr>
<form name="form1" method="post" action="updateform.php">
<tr>
<td> </td>
<td align="center">
<input name="inp_naam" type="text" id="inp_naam" value="<? echo $rows['naam']; ?>">
</td>
<td align="center">
<input name="inp_omschrijving" type="text" id="inp_omschrijving" value="<? echo $rows['omschrijving']; ?>" size="15">
</td>
<td>
<input name="inp_prijs" type="text" id="inp_prijs" value="<? echo $rows['prijs']; ?>" size="15">
</td>
<td align="center">
<input name="inp_promotext" type="text" id="inp_promotext" value="<? echo $rows['promotext']; ?>">
</td>
<td align="center">
<input name="inp_url" type="text" id="inp_url" value="<? echo $rows['url']; ?>" size="15">
</td>
<td>
<input name="inp_iurl" type="text" id="inp_iurl" value="<? echo $rows['iurl']; ?>" size="15">
</td>
</tr>
<tr>
<td> </td>
<td>
<input name="id" type="hidden" id="id" value="<? echo $rows['id']; ?>">
</td>
<td align="center">
<input type="submit" name="Submit" value="Submit">
</form>
</td>
<td> </td>
</tr>
</table>
</td>
</tr>
</table>
</div>
</center>
<?php
// close connection
mysql_close();
?>
</body>
</html>
This Code is what has to Update the database. (i have updated this one to most comments on the page, mysqli and PDO don't work for me.)
<html>
<body>
<?php
session_start(); // Start the session
$loggedin = $_SESSION['loggedin']; // Are they loggedin?
// They are not logged in, Kill the page and ask them to login.
if ($loggedin != "1") {
die('Sorry your not loggedin, please login to gain acces. Here to login');}
?>
<?php
$inp_naam=$_POST['inp_naam'];
$inp_prijs=$_POST['inp_prijs'];
$inp_promotext=$_POST['inp_promotext'];
$inp_url=$_POST['inp_url'];
$inp_iurl=$_POST['inp_iurl'];
$id=$_POST['id'];
$host=""; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
$tbl_name=""; // Table name
// Connect to server and select database.
$conn = mysql_connect("$host", "$username", "$password")or die("cannot connect Host");
mysql_select_db("$db_name")or die("cannot select DB");
// update data in mysql database
$sql="UPDATE `$db_name`.`$tbl_name`
SET `naam` = '$inp_naam',
`omschrijving` = '$inp_omschrijving',
`prijs` = '$inp_prijs',
`promotext` = '$inp_promotext',
`url` = '$inp_url',
`iurl` = '$inp_iurl'
WHERE `$tbl_name`.`id` = '$id'";
$result = mysql_query($conn, $sql);
if (!$result) {
// if successfully updated.
echo "Successful";
echo "<BR>";
echo "<a href='list_records.php'>View result</a>";
} else {
die('cannot update DataBase'. mysql_error());
}
?>
</body>
</html>
To
<html>
<body>
<?php
session_start(); // Start the session
$loggedin = $_SESSION['loggedin']; // Are they loggedin?
// They are not logged in, Kill the page and ask them to login.
if ($loggedin != "1") {
die('Sorry your not loggedin, please login to gain acces. Here to login');}
?>
<?php
$host=""; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
$tbl_name=""; // Table name
session_start();
// Connect to server and select database.
$conn = mysql_connect("$host", "$username", "$password")or die("cannot connect Host");
mysql_select_db("$db_name")or die("cannot select DB");
// update data in mysql database
$sql="UPDATE tblProducts
SET naam = '".$_POST['inp_naam']."',
omschrijving = '".$_POST['inp_omschrijving']."',
prijs = '".$_POST['inp_prijs']."',
promotext = '".$_POST['inp_promotext']."',
url = '".$_POST['inp_url']."',
iurl = '".$_POST['inp_iurl']."'
WHERE id = '".$_POST['inp_id']."'";
$result = mysql_query($sql,$conn);
if (!result) {
// if successfully updated.
echo "Successful";
echo "<BR>";
echo "<a href='list_records.php'>View result</a>";
} else {
die('cannot update DataBase'. mysql_error());
}
mysql_close();
?>
</body>
</html>
Thank you alot for your time!
Mysqli.
// Connect to database
$con=mysqli_connect("$host","$user","$pass","$db_name");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Get id from URL bar
$id=$_GET['id']
// connect to table
$sql="SELECT * FROM `tblProducts` WHERE `id` = '$id'";
$result=mysqli_query($con,$sql);
// get table information
$rows=mysqli_fetch_array($result,MYSQLI_ASSOC);
mysqli_free_result($result);
?>
First of all, the syntax for your query is incorrect. The SQL query should be passed as the first parameter, with the connection identifier as the second, for example:
$result = mysql_query($sql, $conn);
Secondly, your UPDATE query contains invalid characters. You should use backticks to escape field names in MySQL,not quotes. Update your code as follows:
$sql="UPDATE `$db_name`.`$tbl_name`
SET `naam` = '$inp_naam',
`omschrijving` = '$inp_omschrijving',
`prijs` = '$inp_prijs',
`promotext` = '$inp_promotext',
`url` = '$inp_url',
`iurl` = '$inp_iurl'
WHERE `$tbl_name`.`id` = $id";
You'll see that I also removed the erroneous squared brackets ([]) as well.
Please be advised that mysql_* functions are now deprecated. You should look into MySQLi or PDO. Also be advised that your code is wide open to SQL injection. You should learn about sanitizing your input, and in particular, Prepared Statements.
I am not sure this ' is the correct symbol for using with table and column names.
UPDATE '$db_name'.'$tbl_name'
SET 'naam' = ['$inp_naam'], 'omschrijving' = ['$inp_omschrijving'], 'prijs' = ['$inp_prijs'], 'promotext' = ['$inp_promotext'], 'url' = ['$inp_url'], 'iurl' = ['$inp_iurl']
WHERE '$tbl_name'.'id' = $id
Maybe you wanted to use ` ?
$sql="UPDATE '$db_name'.'$tbl_name'
SET naam = ['$inp_naam'], omschrijving = ['$inp_omschrijving'], prijs = ['$inp_prijs'], promotext = ['$inp_promotext'], url = ['$inp_url'], iurl = ['$inp_iurl']
WHERE '$tbl_name'.id = $id";
Remove single quote from column name
This code of yours has some serious security issues. You are writing POST/GET-variables without quoting to an SQL query, which let's users inject SQL into your query (see http://xkcd.com/327/ :)).
For DB interaction I usually use PDOs (http://www.php.net/manual/de/pdo.prepare.php).
Your code will look like this:
$sth = $dbh->prepare('UPDATE '.$db_name.'.'.$tbl_name.' SET naam = ?, omschrijving = ?, prijs = ?, promotext = ?, url = ?, iurl = ? WHERE '.$tbl_name.'.id = ?');
$sth->execute(array($inp_naam, $inp_omschrijving, $inp_prijs, $inp_promotext, $inp_url, $inp_iurl, $id));
Edit: Without PDO this would look like this:
$sql = "UPDATE ".$db_name.".".$tbl_name." SET"
." naam = '".mysql_real_escape_string($inp_naam)
."', omschrijving = '".mysql_real_escape_string($inp_omschrijving)
."', prijs = '".mysql_real_escape_string($inp_prijs)
."', promotext = '".mysql_real_escape_string($inp_promotext)
."', url = '".mysql_real_escape_string($inp_url)
."', iurl = '".mysql_real_escape_string($inp_iurl)
."' WHERE ".$tbl_name.".id = '".mysql_real_escape_string($id)."'");

Repeating on adding data in Database

I have a problem in my guestbook in php. After I fill up the guestbook, it works fine but when I look to my database, all the data I entered is repeated more than once.
guestbook.php
<table border="0" width="920" bgcolor="#1d1c1b" id="round"><tr><td>
<table width="400" border="0" align="center" cellpadding="3" cellspacing="0">
<tr><br>
<td><strong><h2>SEACO's Guestbook</h2> </strong></td>
</tr>
</table>
<table width="400" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<form id="form1" name="form1" method="post" action="addguestbook.php">
<td>
<table width="400" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td width="117">Name</td>
<td width="14">:</td>
<td width="357"><input name="name" type="text" id="name" size="40" placeholder="Enter your name here" required/></td>
</tr>
<tr>
<td>Email</td>
<td>:</td>
<td><input name="email" type="text" id="email" size="40" placeholder="Enter your email here (Optional)"/></td>
</tr>
<tr>
<td valign="top">Comment</td>
<td valign="top">:</td>
<td><textarea name="comment" cols="40" rows="3" id="comment" placeholder="Your comment here" required></textarea></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td><input type="submit" name="Submit" value="Submit" class="button"/> <input type="reset" name="Submit2" value="Reset" class="button" /></td>
</tr>
</table>
</td>
</form>
</tr>
</table>
<table width="400" border="0" align="center" cellpadding="3" cellspacing="0">
</table><br><center><strong><button class="button">View Guestbook</button> </strong></center>
<br><br></table>
addguestbook.php
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="chess"; // Database name
$tbl_name="guestbook"; // Table name
$name = $_POST['name'];
$email = $_POST['email'];
$comment = $_POST['comment'];
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect server ");
mysql_select_db("$db_name")or die("cannot select DB");
$datetime=date("y-m-d h:i:s"); //date time
$sql="INSERT into $tbl_name(name, email, comment, datetime)values('$name', '$email', '$comment', '$datetime')";
$result=mysql_query($sql);
//check if query successful
if($result){
echo "<br><br><center><font color='white' size='5'>Successful</font> <img src='images/cmark.png' width='40px'></center>";
echo "<BR>";
// link to view guestbook page
echo "<center><a href='viewguestbook.php'><button class='button'>View guestbook</button></a></center>";
echo '<br><br>';
}
else {
echo "ERROR";
}
mysql_close();
?>
viewguestbook.php
<table width="400" border="0" align="center" cellpadding="3" cellspacing="0">
<tr>
<td><strong><font color="white">View Guestbook</font> | <button class="button">Sign Guestbook</button> </strong></td>
</tr>
</table>
<br>
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="chess"; // Database name
$tbl_name="guestbook"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect server ");
mysql_select_db("$db_name")or die("cannot select DB");
$sql="SELECT * FROM $tbl_name";
$result=mysql_query($sql);
while($rows=mysql_fetch_array($result)){
?>
<table width="400" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<td><table width="400" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td width="117">Name</td>
<td width="14">:</td>
<td width="357" id="input"><?php echo $rows['name']; ?></td>
</tr>
<tr>
<td>Email</td>
<td>:</td>
<td id="input"><?php echo $rows['email']; ?></td>
</tr>
<tr>
<td valign="top">Comment</td>
<td valign="top">:</td>
<td id="input"><?php echo $rows['comment']; ?></td>
</tr>
<tr>
<td valign="top">Date/Time </td>
<td valign="top">:</td>
<td id="input"><?php echo $rows['datetime']; ?></td>
</tr>
</table></td>
</tr>
</table>
<?php
}
mysql_close(); //close database
?>
</table>
<?php
if (!isset($_POST['name'])) {
header ("Location: guestbook.php");
exit();
}
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="chess"; // Database name
$tbl_name="guestbook"; // Table name
$name = $_POST['name'];
$email = $_POST['email'];
$comment = $_POST['comment'];
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect server ");
mysql_select_db("$db_name")or die("cannot select DB");
$datetime=date("y-m-d h:i:s"); //date time
$sql="INSERT into $tbl_name(name, email, comment, datetime)values('$name', '$email', '$comment', '$datetime')";
$result=mysql_query($sql);
unset($_POST['name']);
//check if query successful
if($result){
echo "<br><br><center><font color='white' size='5'>Successful</font> <img src='images/cmark.png' width='40px'></center>";
echo "<BR>";
// link to view guestbook page
echo "<center><a href='viewguestbook.php'><button class='button'>View guestbook</button></a></center>";
echo '<br><br>';
}
else {
echo "ERROR";
}
mysql_close();
?>
There is no way to execute your query 6 times until you resubmit the form by reloading or any ajax request. If your query is executed then it should return true in $result. you can use exit() inside condition to check if it works and Try to check if form submitted by submit button like this:
<?php
if(isset($_POST['Submit'])){
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="root"; // Mysql password
$db_name="test"; // Database name
$tbl_name="users"; // Table name
$name = $_POST['name'];
$email = $_POST['email'];
$comment = $_POST['comment'];
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect server ");
mysql_select_db("$db_name")or die("cannot select DB");
$datetime=date("y-m-d h:i:s"); //date time
$sql="INSERT into $tbl_name(name, email, comment, datetime) values ('$name', '$email', '$comment', '$datetime')";
$result=mysql_query($sql);
//check if query successful
if($result){
echo "<br><br><center><font color='white' size='5'>Successful</font> <img src='images/cmark.png' width='40px'></center>";
echo "<BR>";
// link to view guestbook page
echo "<center><a href='viewguestbook.php'><button class='button'>View guestbook</button></a></center>";
echo '<br><br>';
exit();
}
else {
echo "ERROR";
}
mysql_close();
}
else{
echo "not set";
}

php mysql bulk records update?

I'm trying to update multiple mysql records, with this code:
<strong>Update multiple rows in mysql</strong><br>
<?php
$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name="test"; // Database name
$tbl_name="test_mysql"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql="SELECT * FROM $tbl_name";
$result=mysql_query($sql);
// Count table rows
$count=mysql_num_rows($result);
?>
<table width="500" border="0" cellspacing="1" cellpadding="0">
<form name="form1" method="post" action="">
<tr>
<td>
<table width="500" border="0" cellspacing="1" cellpadding="0">
<tr>
<td align="center"><strong>Id</strong></td>
<td align="center"><strong>Name</strong></td>
<td align="center"><strong>Lastname</strong></td>
<td align="center"><strong>Email</strong></td>
</tr>
<?php
while($rows=mysql_fetch_array($result)){
?>
<tr>
<td align="center"><? $id[]=$rows['id']; ?><? echo $rows['id']; ?></td>
<td align="center"><input name="name[]" type="text" id="name" value="<? echo $rows['name']; ?>"></td>
<td align="center"><input name="lastname[]" type="text" id="lastname" value="<? echo $rows['lastname']; ?>"></td>
<td align="center"><input name="email[]" type="text" id="email" value="<? echo $rows['email']; ?>"></td>
</tr>
<?php
}
?>
<tr>
<td colspan="4" align="center"><input type="submit" name="Submit" value="Submit"></td>
</tr>
</table>
</td>
</tr>
</form>
</table>
<?php
// Check if button name "Submit" is active, do this
if($Submit){
for($i=0;$i<$count;$i++){
$sql1="UPDATE $tbl_name
SET name='$name[$i]',
lastname='$lastname[$i]',
email='$email[$i]'
WHERE id='$id[$i]'";
$result1=mysql_query($sql1);
}
}
if($result1){
header("location:update_multiple.php");
?>
It shows records from the DB in input text boxes, but when I change old records with new ones and then submit, nothing happens, page refreshes with old values.
You will need to check if the form is submitted using $_POST['Submit'].
Also you could use a hidden input field to keep track of each row to update:
<input type="hidden" name="id[]" value="<?php echo $row['id']; ?>" />
Then when handling your submission you should do something like this:
if(isset($_POST['Submit'])) {
$ids = $_POST['id'];
$names = $_POST['name'];
$lastnames = $_POST['lastname'];
$emails = $_POST['email'];
//
foreach($ids as $id) {
// update the record based on the id and supplied data
}
}
And of course the update process should be executed before you retrieve you rows from the database. In other words the above code should be placed near the top of your script. At least before the:
$sql="SELECT * FROM $tbl_name";
$result=mysql_query($sql);
Submit should define that form if sent
move update code before select because you first view, and just after that update info, so you'll view previous results all the time
...
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
if($Submit){
for($i=0;$i<$count;$i++){
$sql1="UPDATE $tbl_name SET name='$name[$i]', lastname='$lastname[$i]', email='$email[$i]' WHERE id='$id[$i]'";
$result1=mysql_query($sql1
);
}
$sql="SELECT * FROM $tbl_name";
$result=mysql_query($sql);
// Count table rows
...
Using if($Submit){ is not the correct way to determinate if a form has been submitted ...
you should use :
if($_SERVER['REQUEST_METHOD'] == "POST")
then process your submitted values.
Note : you should update the DB before showing the values ....
And please make sure you read about SQL Injection
First of all mysql_query() doesn't return anything when you execute an update command.
You could use instead mysql_affected_rows to retrieve the number of rows changed by the previous query:
http://php.net/manual/en/function.mysql-affected-rows.php
Then, you should also do some refactoring like moving the update code before displaying the results, otherwise the header location directive won't work if you already sent output to the browser.
did you apply the varaible names in single code?
$sql1="UPDATE $tbl_name SET name='$name[$i]', lastname='$lastname[$i]', email='$email[$i]' WHERE id='$id[$i]'";
change above query to
$sql1="UPDATE $tbl_name SET name='".$name[$i]."', lastname='".$lastname[$i]."', email='".$email[$i]."' WHERE id=$id[$i]";

Deleting Multiple records in php My sql

<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="toybox"; // Database name
$tbl_name="Emp"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql="SELECT * FROM $tbl_name";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
// echo $count;
?>
<table width="400" border="0" cellspacing="1" cellpadding="0">
<tr>
<td><form name="form1" method="post" action="">
<table width="400" border="0" cellpadding="3" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<td bgcolor="#FFFFFF"> </td>
<td colspan="4" bgcolor="#FFFFFF"><strong>Delete multiple rows in mysql</strong> </td>
</tr>
<tr>
<td align="center" bgcolor="#FFFFFF">#</td>
<td align="center" bgcolor="#FFFFFF"><strong>Id</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Name</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Lastname</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Email</strong></td>
</tr>
<?php
while($rows=mysql_fetch_array($result)){
?>
<tr>
<td align="center" bgcolor="#FFFFFF"><input name="checkbox[]" type="checkbox" id="checkbox[]" value="<? echo $rows['EmpId']; ?>"></td>
<td bgcolor="#FFFFFF"><?php echo $rows['EmpId']; ?></td>
<td bgcolor="#FFFFFF"><?php echo $rows['FirstName']; ?></td>
<td bgcolor="#FFFFFF"><?php echo $rows['LastName']; ?></td>
<td bgcolor="#FFFFFF"><?php echo $rows['Email']; ?></td>
</tr>
<?php
}
?>
<tr>
<td colspan="5" align="center" bgcolor="#FFFFFF"><input name="delete" type="submit" id="delete" value="Delete"></td>
</tr>
<?php
// Check if delete button active, start this
if($delete){
for($i=0;$i<$count;$i++){
$del_id = $checkbox[$i];
$sql = "DELETE FROM $tbl_name WHERE id='$del_id'";
$result = mysql_query($sql);
}
// if successful redirect to delete_multiple.php
if($result){
echo " Record have been deleted";
}
}
mysql_close();
?>
</table>
</form>
</td>
</tr>
</table>
Rather than doing a query for each iteration of your delete-loop, I would build all of the indexes up into a string, and use something like the following:
DELETE FROM tableName
WHERE id IN (1,2,12,53)
Also, your submit button won't come through as $delete, but instead $_POST["delete"]. And with your connection:
mysql_connect("$host", "$username", "$password")
You really ought not use variables like strings (generally) - this should be written as:
mysql_connect($host, $username, $password)
Furthermore, you've got a few more problems in and around your delete-logic. For instance, I pointed out already that your <input type='submit' name='delete' /> button will be known as $_POST["delete"] once it is registered on the server. Likewise, your checkboxes, having an id value of checkbox[] will simply be known as $_POST["checkbox"] on the server.
Also, your $count variable, used in your delete-logic, is based on the earlier query that selected all of the records to show them. It does not reflect the number of checkboxes to be deleted, it reflects the number of records that were shown. As such, your for loop should not be based on it:
for ($i = 0; $i < count($_POST["checkbox"]); $i++)
{
// delete $_POST["checkbox"][$i];
}
And again, I would suggest you build a string of values and run a single query instead of multiple.
Working Code .. Consider Point 1 2 and 3
<?php
// Make a MySQL Connection
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("funconnect") or die(mysql_error());
// Get all the data from the "example" table
$result = mysql_query("SELECT * FROM members")
or die(mysql_error());
$count=mysql_num_rows($result);
echo "<form name='sendmail' method='post' action='memberList.php'><table border='1'>";
echo "<tr> <th>Select</th> <th>Name</th> </tr>";
// keeps getting the next row until there are no more to get
$countSn = 0;
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
$chkname = "checkbox".$countSn; #Point 1- Create defferent name for checkboxex like checkbox0, checkbox1
echo "<tr><td><input type='checkbox' name=".$chkname." value=".$row['m_id']." /></td>";
echo "</td><td>";
echo $row['m_name'];
echo "</td></tr>";
$countSn++;
}
echo '<tr><td colspan=2><input name="delete" type="submit" id="delete" value="Delete"></td></tr></table></form>';
$delete=$_POST['delete'];
$checkbox=$_POST['checkbox'];
// Check if delete button active, start this
if($delete){
for($i=0;$i<$count;$i++){
$cname = "checkbox".$i;# Point 2- Create check box name like checkbox0, checkbox1
$checkbox=$_POST[$cname]; #Point 3 - Retrieve data against name
echo $i."===".$checkbox."<br />";
//echo $del_id;
//$sql = "DELETE FROM $tbl_name WHERE id='$del_id'";
//$result = mysql_query($sql);
}
// if successful redirect to delete_multiple.php
if($result){
//echo "<meta http-equiv=\"refresh\" content=\"0;URL=delete_multiple.php\">";
}
}
mysql_close();
?>

Categories