Updating a table with PHP and MYSQL - php

<?php require("inc_connect.php"); ?>
<h1 align="center">Farris Website</h1>
<hr width="1000">
<p align="center">
<table align="center" width="1000" border="3" bordercolor="#0066FF" >
<tr>
<td align="left" valign="top">
<form name="update" method="post" action="ex_update.php?id=<?php echo urlencode($_POST['id']); ?>">
<p><strong>Enter Name:</strong>
<input type="text" name="name">
<br />
ID:
<label for="select"></label>
<select name="id">
<?php
$query = "SELECT * FROM test";
$run = mysql_query($query);
while($output = mysql_fetch_array($run)){
echo "<option value=\"{$output['id']}\">{$output['id']}</option>";}
?>
</select>
</p>
<p>
<input type="submit" name="submit" value="Update!">
</p>
</form></td>
<td width="300" align="left" valign="top"><?php include("inc_output.php"); ?></td>
</tr>
</table>
</p>
The above is the index page ...
<?php
$connect = mysql_connect("localhost","root","");
$sel_database = mysql_select_db("test");
$name = mysql_real_escape_string( $_POST["name"] );
$id = (int) $_GET['id'];
$query = "UPDATE test SET name='{$name}'";
if($run = mysql_query($query)){
header("location: index.php");
exit;
}else{mysql_error();}
?>
And this is the page that processes the form.
The problem is that the record won't update if i set the id={$_GET['id']}
and if I remove that part it updates all the rows.
So updating according to id ...
Thanks in Advance
FarrisFahad

Try changing your form action to
<form name="update" method="post" action="ex_update.php?id=<?php echo urlencode($_GET['id']); ?>">
Also, doing an echo of $query might help debug your problem.

First, just be aware of SQL Injection - your code is wide open to it. See http://bobby-tables.com/
PHP Code
<?php
$connect = mysql_connect("localhost","root","");
$sel_database = mysql_select_db("test");
$name = mysql_real_escape_string( $_POST["name"] );
$id = (int) $_GET['id'];
$query = "UPDATE test SET name='{$name}' WHERE id = {$id}";
if($run = mysql_query($query)){
header("location: index.php");
exit;
}else{
# In production, don't show raw errors to users - log them to a file and
# present the user with a generic "There was a problem with the database"
# error. Or people can start sniffing for vulnerabilities in your site.
echo mysql_error();
}
?>
Page
<?php
require("inc_connect.php");
?>
<h1 align="center">Farris Website</h1>
<hr width="1000">
<p align="center">
<table align="center" width="1000" border="3" bordercolor="#0066FF" >
<tr>
<td><form name="update" method="post" action="ex_update.php?id=<?php echo urlencode($_GET['id']); ?>">
<p><strong>Enter Name:</strong>
<input type="text" name="name"><br />
<label for="select">ID:</label>
<select name="id" id="select">
<?php
$query = "SELECT * FROM test";
$run = mysql_query($query);
while( $r = mysql_fetch_array($run) ){
# I always use short, single character, variables when in loops.
# Saves alot of characters and potential confusion.
echo " <option value='{$r['id']}'>{$r['id']}</option>\n";
}
?>
</select>
</p>
<p>
<input type="submit" name="submit" value="Update!">
</p>
</form></td>
<td><?php include("inc_output.php"); ?></td>
</tr>
</table>
</p>

As you want to update that record which is selected from your dropdown. Moreover u have set your form method to POST. So you should try following:
<form name="update" method="post" action="ex_update.php?id=<?php echo urlencode($_POST['id']); ?>">

Related

How to add a record to a database using id instead of changing them (javascript and php)?

How do I add a few records to a database using the id’s I had listed in phpMyAdmin. The problem is once I entered the id , it display the database but when I entered another id , it took out and change the value of the first id database I entered and replace it with the second id. What I want is to add the database one by one through each click but instead of replacing it, I would like to add them below after the first ID I entered earlier. This is what I’m working on so far.
<html>
<head>
<title>Search data by its ID</title>
</head>
<body>
<center>
<h1>Search a single DATA</h1>
<h2>Retrieve data from database</h2>
<div class="container">
<form action="" method="POST">
<input type="text" name="id" placeholder="Student ID" />
<input type="submit" name="search" value="Search By ID" />
</form>
<table border="2" id="newton">
<tr>
<th>Product Name</th>
<th>Quantity</th>
<th>Returned Date</th>
</tr><br><br>
<?php
$connection = mysqli_connect("localhost","root", "");
$db = mysqli_select_db($connection,"myfirstdb");
if(isset($_POST['search']))
{
$id = $_POST['id'];
$query = "SELECT * FROM `table3` where id = '$id'";
$query_run = mysqli_query($connection, $query);
while($row = mysqli_fetch_array($query_run))
{
?>
<tr>
<td>
<?php echo $row ['product_name']; ?> </td>
<td>
<?php echo $row ['quantity']; ?> </td>
<td>
<?php echo $row ['returned_date']; ?> </td>
</tr>
<?php
}
}
?>
</table>
</form>
</div>
</center>
</body>
</html>
If I understand your problem correctly, the following code can solve your problem. Although the student ID has nothing to do with the name of the product !!
you can use a session for this problem.
<html>
<head>
<title>Search data by its ID</title>
</head>
<body>
<center>
<h1>Search a single DATA</h1>
<h2>Retrieve data from database</h2>
<div class="container">
<form action="" method="POST">
<input type="text" name="id" placeholder="Student ID" />
<input type="submit" name="search" value="Search By ID" />
</form>
<table border="2" id="newton">
<tr>
<th>Product Name</th>
<th>Quantity</th>
<th>Returned Date</th>
</tr><br><br>
<?php
$connection = mysqli_connect("localhost","root", "");
$db = mysqli_select_db($connection,"myfirstdb");
session_start();
if (!isset($_SESSION['id'])) {
$_SESSION['id'] = array();
}
if(isset($_POST['search']))
{
$id = $_POST['id'];
array_push($_SESSION['id'],$id);
$_SESSION['id'] = array_unique($_SESSION['id']);
$id = implode(',',$_SESSION['id']);
$query = "SELECT * FROM `table3` where id in ($id)";
$query_run = mysqli_query($connection, $query);
while($row = mysqli_fetch_array($query_run))
{
?>
<tr>
<td>
<?php echo $row ['product_name']; ?> </td>
<td>
<?php echo $row ['quantity']; ?> </td>
<td>
<?php echo $row ['returned_date']; ?> </td>
</tr>
<?php
}
}
?>
</table>
</form>
</div>
</center>
</body>
</html>

PHP: A HTML hidden input value generates an error upon querying mysql

I'm working on a webpage where I allow users to edit their car information. In the mainlining, there is an edit button (input - type text with a hidden key value) where it takes the user to this "edit car info" page. Initially, once the page is opened for the first time, this hidden value is used to query the database, retrieve original information and and set them as placeholders for the field. The user can write information in the input field then press the "submit edit" button which then updates the row in the database table. However, I get an error that the name of the hidden value is undefined. I don't understand how it can be undefined for the update query when it was working just fine for the select query. Can anyone shed a light on this? What should I do? This is a picture of the errors:
This is the mainlanding code: (hidden value is set here)
<?php
$mysqli= new mysqli("localhost", "root","","Car_registration");
if(empty($_SESSION)) // if the session not yet started
session_start();
if(isset($_SESSION['username'])) { // if user already logged in
header("location: mainlanding_user.php"); //send to homepage
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<title> Car Registration: User's Mainlanding </title>
<link href="css/style3.css" rel="stylesheet">
</head>
<body>
<header>
<h1>Account Information</h1>
<img id="img1" src= "image/car.jpg" alt ="car image">
</header>
<nav id='nav'>
<form action="logout.php">
<input type="submit" value=" Logout " id="button">
</form>
</nav>
<h2>Profile </h2>
<div class='container1'>
<?php
$username="root";
$password="";
$database="Car_registration";
$mysqli= new mysqli("localhost",$username,$password,$database);
$query= "select * from driver where username='".$_SESSION['logged_username']."'";
$result = $mysqli->query($query);
while( $row = $result->fetch_assoc() ){
echo "<div id='container'>" ;
echo "<dl> <dt>First Name</dt> <dd>".$row['Fname'];
echo "</dd> <br> <dt>Last name</dt><dd>".$row['Lname'];
echo "</dd> <br> <dt>License Number</dt><dd>".$row['license_no'];
echo "</dd> <br> <dt>Age</dt><dd>".$row['Age'];
echo "</dd> <br> <dt>Birthday</dt><dd>".$row['bdate'];
echo "</dd> <br> <dt>City</dt><dd>".$row['City'];
echo "</dd></dl>";
echo "</div>";
$license_no = $row['license_no']; //used for finding cars
}
?>
<div class="align-me">
<div class="form-wrapper" action="search_plate_no.php">
<form class="center">
<input class="input-fields" name="search" type="text" placeholder="Search a plate number">
<input class="input-fields submit" name="find" type="submit" value="Search">
</form>
</div>
</div>
<h3> Registered Cars </h3>
<div class='container2'>
<?php
$username="root";
$password="";
$database="Car_registration";
$mysqli= new mysqli("localhost",$username,$password,$database);
$query= "select * from cars where license_no='".$license_no."'";
$result = $mysqli->query($query);
echo "<table border=1>
<tr>
<th>Plate No.</th>
<th>License No.</th>
<th>Car Type</th>
<th>Fines</th>
<th>City</th>
<th>Edit</th>
<th>Delete</th>
</tr>";
while ($temp = $result->fetch_assoc()){
?>
<tr>
<td><?php echo $temp['Plate_no']; ?></td>
<td><?php echo $temp['license_no']; ?></td>
<td><?php echo $temp['Car_type']; ?></td>
<td><?php echo $temp['Fines']; ?></td>
<td><?php echo $temp['city']; ?></td>
<td>
<form action = "edit_car.php" method="post">
<input type="hidden" name="id" value="<?php echo $temp['Plate_no']; ?>">
<input type="submit" name="edit" value="Edit">
</form>
</td>
<td>
<form action = "delete_car.php" method="post">
<input type="hidden" name="id" value="<?php echo $temp['Plate_no']; ?>">
<input type="submit" name="delete" value="Delete">
</form>
</td>
</tr>
<?php
}
?>
</table>
</div>
<form action="register_car.php">
<input type="submit" value=" Register Car " id="button2">
</form>
<footer>
<h4> All rights belong to Car Registration Inc. </h4>
<img id="img3" src= "image/license.png" alt ="license plates image">
</footer>
</body>
</html>
Edit car page: (Error is generated here)
<!DOCTYPE html>
<html>
<head>
<title> Edit Car Information Page </title>
<link href="css/style2.css" rel="stylesheet">
</head>
<body>
<div class="container">
<header>
<h1>Edit Car Information </h1>
<img id="img1" src= "image/register.png" alt ="Registration image">
</header>
<?php
$username="root";
$password="";
$database="Car_registration";
$mysqli= new mysqli("localhost",$username,$password,$database);
$plate_no= $_POST["id"]; //This line causes an error
$_SESSION['plateNo'] = $plate_no;
$query= "select * from cars where Plate_no='".$plate_no."'";
$result = $mysqli->query($query);
while( $row = $result->fetch_assoc()){
$plate_no = $row['Plate_no'];
$car_type = $row['Car_type'];
}
?>
<main>
<h2> You can only edit the following information: </h2>
<form action="" method="post">
<label for="car_type_input">Car Type:</label>
<input type="text" placeholder="<?php echo $car_type?>" id="car_type_input" name="car_type_input"><br><br>
<div class="vertical-center">
<input type="submit" value=" Submit Edit " name="button1" id="button1">
</div>
</form>
<?php
$username="root";
$password="";
$database="Car_registration";
$mysqli= new mysqli("localhost",$username,$password,$database);
if( isset($_POST['button1']) ){ //If user changed field, take value. If not, keep old value.
if( !empty($_POST['car_type_input']) ){ //If there is user input
$car_type_2 = $_POST['car_type_input'];
$query= "update cars set Car_type='".$car_type_2."' WHERE Plate_no='".$_SESSION['plateNo']."'";
}
if ($mysqli->query($query))
echo "Fields updated successfuly!";
else
echo "Update Fields Failed!";
}
?>
</main>
<footer>
<h3> All rights belong to Car Registration Inc. </h3>
<img id="img3" src= "image/license.png" alt ="license plates image">
</footer>
</div>
</body>
</html>
Use $plate_no= $_POST['id']; instead of $plate_no= $_POST["id"];
Here why you close the while loop ??
while ($temp = $result->fetch_assoc()){
?>
and here too
<?php
}
Try this:
print"<h3> Registered Cars </h3>
<div class='container2'>";
$username="root";
$password="";
$database="Car_registration";
$mysqli= new mysqli("localhost",$username,$password,$database);
$query= "select * from cars where license_no='".$license_no."'";
$result = $mysqli->query($query);
echo "<table border=1>
<tr>
<th>Plate No.</th>
<th>License No.</th>
<th>Car Type</th>
<th>Fines</th>
<th>City</th>
<th>Edit</th>
<th>Delete</th>
</tr>";
while ($temp = $result->fetch_assoc())
{
print"
<tr>
<td><?php echo $temp['Plate_no']; ?></td>
<td><?php echo $temp['license_no']; ?></td>
<td><?php echo $temp['Car_type']; ?></td>
<td><?php echo $temp['Fines']; ?></td>
<td><?php echo $temp['city']; ?></td>
<td>
<form action = "edit_car.php" method="post">
<input type="hidden" name="id" value="<?php echo $temp['Plate_no']; ?>">
<input type="submit" name="edit" value="Edit">
</form>
</td>
<td>
<form action = "delete_car.php" method="post">
<input type="hidden" name="id" value="<?php echo $temp['Plate_no']; ?>">
<input type="submit" name="delete" value="Delete">
</form>
</td>
</tr> ";
}
print"</table>
</div>";
you are not sending id that's because error appears use this code to check if id exists first:
$plate_no='';
$car_type = '';
if(isset($_POST["id"])){
$plate_no= $_POST["id"]; //This line causes an error
$_SESSION['plateNo'] = $plate_no;
$query= "select * from cars where Plate_no='".$plate_no."'";
$result = $mysqli->query($query);
while( $row = $result->fetch_assoc()){
$plate_no = $row['Plate_no'];
$car_type = $row['Car_type'];
}
}

i want to try fetch data on other page and than update but always show me an error

here is my index page.inserted all the data to the database and also show on the same page but the main problem is that on update.php page I can not retrieve the data
//that main problem is here and I can't be retrieved the data on this page and always sow that: Warning: mysql_fetch_array() expects parameter 1 to be resource, object given in C:\wamp\www\phonebook\update.php on line 12
index.php
<?php require_once('dbconnect.php'); ?>
<html>
<head>
<title> </title>
</head>
<body>
<h1> phone book </h1>
<form method="post">
<table>
<tr>
<td>fname </td><td> <input type="text" name="firstname" required /> </td>
</tr>
<tr>
<td>lname </td><td> <input type="text" name="lastname" required /> </td>
</tr>
<tr>
<td>mobile </td><td> <input type="text" name="mobile" required /> </td>
</tr>
</table>
<input type="submit" name="submit" value="submit" >
</form>
<!-- $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ show $$$$$$$$$$$$$$$$$$$$$$$$$$ -->
<br> data </br>
<table border="1">
<tr>
<th>id</th> <th>firstname</th> <th>lastname</th> <th>mobile</th><th>update</th><th>delete</th>
</tr>
<?php
$conn = mysqli_connect('localhost','root','','phonebook');
$show = mysqli_query($conn,"SELECT * FROM contacts");
while($row = mysqli_fetch_array($show))
{
?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['firstname']; ?></td>
<td><?php echo $row['lastname']; ?></td>
<td><?php echo $row['mobile']; ?></td>
<td>update</td>
<td><a href="delete.php?id=<?php echo $row['id']; ?>" onclick="return confirm('sure want to delete')" >delete</a></td>
</tr>
<?php } ?>
</table>
</body>
</html>
<?php
//require_once("function.php");
//$obj = new data();
if(isset($_POST{"submit"}))
{
//echo "<pre>";print_r($_POST);die;
$fname = $_POST['firstname'];
$lname = $_POST['lastname'];
$mobile = $_POST['mobile'];
//$obj->insert($fname,$lname,$mobile);
$connect = mysqli_connect('localhost','root','','phonebook');
$insert = mysqli_query($connect,"insert into contacts(firstname,lastname,mobile) values('".$fname."','".$lname."','".$mobile."')");
if ($insert)
{ ?>
<script> alert('record inserted'); </script>
<?php
}
else
{ ?>
<script> alert('record not inserted'); </script>
<?php
}
header('Location:index.php');
}
?>
update.php
//check the code here
<?php require_once('dbconnect.php');
if(isset($_GET['id']) && is_numeric($_GET['id']) )
{
$id=$_GET['id'];
}
?>
<?php
$conn = mysqli_connect('localhost','root','','phonebook');
$result=mysqli_query($conn,"SELECT * FROM contacts WHERE id='$id'");
$fetch=mysql_fetch_array($result);
//$conn = mysqli_connect('localhost','root','','phonebook');
//$show = mysqli_query($conn,"SELECT * FROM contacts");
//while($row = mysqli_fetch_array($show))
?>
<html>
<head>
<title>update page</title>
</head>
<body>
<form method="post" name="update" action="update.php">
<table>
<tr>
<td>fname </td><td> <input type="text" name="firstname" value= "<?php echo $fetch['firstname']; ?>" required /> </td>
</tr>
<tr>
<td>lname </td><td> <input type="text" name="lastname" value="<?php echo $fetch['lastname']; ?>" required /> </td>
</tr>
<tr>
<td>mobile </td><td> <input type="text" name="mobile" value= "<?php echo $fetch['mobile']; ?>" required /> </td>
</tr>
</table>
<input type="submit" name="submit" value="submit" >
</form>
</body>
</html>
Switch to using mysqli_fetch_array() (note the i) instead of mysql_fetch_array
try this:
$conn = mysqli_connect('localhost','root','','phonebook');
$result=mysqli_query($conn,"SELECT * FROM contacts WHERE id='$id'");
$fetch=mysqli_fetch_array($result);
You must not use mysql_*, it's deprecated. Use PDO or MySQLi instead
You shouldn't mix mysql_* and mysqli_*
Just create ONE mysqli instance instead of creating it for every file you have.
Maximize the use of variables too. This way you only have to change something once.
Please sanitize/escape user input before passing it into your SQL query. Otherwise your application is vulnerable to SQL injection attacks.

PHP update SQL form

I wrote this using various helper guides online:
<?php // update
if(isset($_POST['update']))
{
$id = $_POST['id'];
$emp_salary = $_POST['emp_salary'];
$sql = "UPDATE pins ".
"SET is_private = $emp_salary ".
"WHERE id = $pinDetails->id" ;
mysql_select_db('test_db');
$retval = mysql_query( $sql );
if(! $retval )
{
die('Could not change: ' . mysql_error());
}
echo "Post is now private<br><br>";
}
else
{
?>
<form method="post" action="<?php $_PHP_SELF ?>">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<td>Private
<input name="emp_salary" type="text" id="emp_salary" value="1">
<input name="id" type="hidden" id="id">
<input name="update" type="submit" id="update" value="Change">
</td>
</tr>
</table>
</form>
<?php
}
?><!-- update -->
I'm trying to create an online form which I can return to to change posts from public to private simply by entering 1 for private or 0 for public as a moderation tool.
However, when I submit the form, (which works) every time I revisit the page it just says the echo statement 'post is now private'. I want to be able to see the form everytime, so I can re-use again and again when necessary.
What do I need to change in order to achieve this?
Remove else in last condition.
if(isset($_POST['update']))
{
$id = $_POST['id'];
$emp_salary = $_POST['emp_salary'];
$sql = "UPDATE pins ".
"SET is_private = $emp_salary ".
"WHERE id = $pinDetails->id" ;
mysql_select_db('test_db');
$retval = mysql_query( $sql );
if(! $retval )
{
die('Could not change: ' . mysql_error());
}
echo "Post is now private<br><br>";
}
?>
<form method="post" action="<?php $_PHP_SELF ?>">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<td>Private
<input name="emp_salary" type="text" id="emp_salary" value="1">
<input name="id" type="hidden" id="id">
<input name="update" type="submit" id="update" value="Change">
</td>
</tr>
</table>
</form>
after:
echo "Post is now private<br><br>";
add this:
echo 'see form';
Your problem is that the form post variables are still being sent to the server so your if statement
if(isset($_POST['update']))
evaluates to true and the form doesnt' display.

Query does not work

I made this code:
Acum, bifeaza materiile pe care le studiaza clasa aleasa:<br />
<form name="servForm" action="<?php $PHP_SELF; ?>" method="post" >
<table border="0">
<?php
$a = 0;
$rezultat = "SELECT id, materie
FROM materii
ORDER BY id";
$rezultat1 = mysql_query($rezultat);
while($plm = mysql_fetch_array($rezultat1))
{
if($a++ %5 == 0) echo "<tr>";
?>
<td align="center"><input type="checkbox" name="checkbox2[]" value="<?php echo $plm['id']; ?>" /></td>
<td style="text-align:left"><?php echo $plm["materie"]; ?> </td>
<?php
if($a %5 == 0) echo "</tr>";
}
?>
</table>
</div>
<br/>
<input type="reset" value="Sterge" /> <input type="submit" value="Salveaza" name="savebtn" />
</form>
<?php
if(isset($_POST['savebtn']))
{
foreach($_POST["checkbox2"] as $loc_id)
{
$query = "INSERT INTO materii_pe_clase(id_scoala,id_clasa,id_materie) VALUES('$scoalalui','$clasalui','$loc_id')"; //aici cauta ! :))
$result5 = mysql_query($query)
or die('eroare');
}//sfarsit foreact
}//sfarsit if isset
Why does the last query not work? p.s. its a school project, so mysql is ok, no need for mysqli. p.p.s I defindet the $scoalalui and $clasalui somwhere a little up the page. but they are not the problem, i tried replacing them with values. the query simply does not work. thanks!
thank you all!
EDIT
VARDUMP for $clasalui and $scoalalui
:
string '1' (length=1)
string '1' (length=1)
Your problem here is that, you have error tool turned off, because PHP should have said, something like this.
Notice: Undefined variable $PHP_SELF"
Since you don't see it, I'd assume that, its a root of your "problem".
PHP_SELF is not a variable, that's a constant. Its not even required here, as by default PHP sends data to its target URL.
I improved readability of your code, so that should work for you now,
<?php
// You want to see all errors? Fine:
error_reporting(E_ALL);
$a = 0;
$rezultat = "SELECT id, materie FROM materii ORDER BY id";
$rezultat1 = mysql_query($rezultat);
// If the form is submitted, this will be executed
if (isset($_POST['savebtn'])) {
foreach($_POST["checkbox2"] as $loc_id) {
$query = "INSERT INTO `materii_pe_clase` (`id_scoala`, `id_clasa`, `id_materie`) VALUES('$scoalalui', '$clasalui', '$loc_id')";
$result = mysql_unbuffered_query($query);
if (!$result){
die(mysql_error());
}
}
// And finally
die('Saved. Thanks');
}
?>
Acum, bifeaza materiile pe care le studiaza clasa aleasa: <br />
<form name="servForm" method="POST">
<table border="0">
<?php while($plm = mysql_fetch_array($rezultat1)) : ?>
<?php if ($a++ %5 == 0) :?>
<tr>
<?php endif; ?>
<td align="center">
<input type="checkbox" name="checkbox2[]" value="<?php echo $plm['id']; ?>" />
</td>
<td style="text-align:left"><?php echo $plm["materie"]; ?> </td>
<?php if($a %5 == 0) : ?>
</tr>
<?php endif; ?>
<?php endwhile; ?>
</table>
<br/>
<input type="reset" value="Sterge" />
<input type="submit" value="Salveaza" name="savebtn" />
</form>

Categories