PHP database UPDATE function only modified the first row? - php

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<?php
if (!mysqli_connect_errno($con)) {
$queryStr = "SELECT * " .
"FROM crewlist";
}
$result = mysqli_query($con, $queryStr);
while ($row = mysqli_fetch_array($result)) {
echo "<tr>.<th>" . $row["crew_name"] . "<br></br>" . "</th>";
echo "<th>" . $row["crew_rank"] . "</th>";
echo "<th>" . $row["start_date"] . "</th>";
echo "<th>" . $row["end_date"] . "</th>";
echo "<th>" . $row["watchkeeping"] . "</th>";
echo "<th>" . $row["active"] . "</th>";
echo "<td>Edit";
echo "<td>Delete";
}
?>
editcrew.php
<table>
<form action="handlecrewedit.php" method="post">
<tr>
<td>Crew Name:</td>
<td><input type="text" name="CrewName" id ="CrewName"required></td>
</tr>
<tr>
<td>Crew Rank:</td>
<td><input type="text" name="CrewRank" id="CrewRank" required></td>
</tr>
<tr>
<td>Start Date:</td>
<td><input type="text" name="StartDate" id="StartDate" required></td>
</tr>
<tr>
<td>End Date:</td>
<td><input type="text" name="EndDate" id="EndDate" required></td>
</tr>
<tr>
<td>Payroll No:</td>
<td><input type="text" name="PayrollNo" id="PayrollNo" required></td>
</tr>
<tr>
<td>Employee No:</td>
<td><input type="text" name="EmployeeNo" id="EmployeeNo" required></td>
</tr>
<tr>
<td>Watching Keeping:</td>
<td><input type="text" name="WatchKeeping" id="WatchKeeping" required></td>
</tr>
<tr>
<td>Active:</td>
<td><input type="text" name="Active" id="Active" required></td>
</tr>
<tr>
<td><input type="submit" value="Submit" ></td>
</tr>
</form>
</table>
handlecrewedit.php
<?php
require 'dbfunction.php';
$con = getDbConnect();
$crew_id = $_POST["crew_id"];
$CrewName = $_POST["CrewName"];
$CrewRank = $_POST["CrewRank"];
$StartDate = $_POST["StartDate"];
$EndDate = $_POST["EndDate"];
$PayrollNo = $_POST["PayrollNo"];
$EmployeeNo = $_POST["EmployeeNo"];
$WatchKeeping = $_POST["WatchKeeping"];
$Active = $_POST["Active"];
if (!mysqli_connect_errno($con)) {
$queryStr = "SELECT crew_id " .
"FROM crewlist";
}
$result = mysqli_query($con, $queryStr);
while ($row = mysqli_fetch_array($result)) {
if (!mysqli_connect_errno($con)) {
$sqlQueryStr = "UPDATE crewlist SET crew_name = '$CrewName', crew_rank = '$CrewRank', start_date = '$StartDate' "
. ", end_date = '$EndDate', payroll_no = '$PayrollNo'"
. ", employee_no = '$EmployeeNo', watchkeeping = '$WatchKeeping', active = '$Active' WHERE crew_id = " . $row['crew_id'] . "";
}
mysqli_query($con, $sqlQueryStr);
header('Location: crewlisting.php');
mysqli_close($con);
}
mysqli_close($con);
?>
This is another issue on my modifying entries. I'm not quite sure if I can simply copy and paste my delete code for my edit code, but here is some rough gauge of my table. Unlike the delete function, by selecting the edit function, it directs the user to the form page and it requires them to fill in the updated data.

Errors
Missing closing tag (?>) on here <form action="<?php echo $_SERVER['PHP_SELF']; ?" method="post">
$queryStr = "SELECT * " ."FROM crewlist"; should be $queryStr = "SELECT * FROM crewlist"
No closing tag comes for <br> on here echo "<tr>.<th>" . $row["crew_name"] . "<br></br>" . "</th>";
You don't know how many data passing for this $result = mysqli_query($con, $queryStr);, because there is no row count validation
There is no use of check this inside while loop. if (!mysqli_connect_errno($con))
If you are just updating the fields then you've placed the update query in the wrong place

Replace editcrew.php and handlecrewedit.php file code with below code.
editcrew.php
<table>
<form action="handlecrewedit.php" method="post">
<input type="hidden" name="crew_id" value="<?php echo $_GET['id']; ?>" />
<tr>
<td>Crew Name:</td>
<td><input type="text" name="CrewName" id ="CrewName"required></td>
</tr>
<tr>
<td>Crew Rank:</td>
<td><input type="text" name="CrewRank" id="CrewRank" required></td>
</tr>
<tr>
<td>Start Date:</td>
<td><input type="text" name="StartDate" id="StartDate" required></td>
</tr>
<tr>
<td>End Date:</td>
<td><input type="text" name="EndDate" id="EndDate" required></td>
</tr>
<tr>
<td>Payroll No:</td>
<td><input type="text" name="PayrollNo" id="PayrollNo" required></td>
</tr>
<tr>
<td>Employee No:</td>
<td><input type="text" name="EmployeeNo" id="EmployeeNo" required></td>
</tr>
<tr>
<td>Watching Keeping:</td>
<td><input type="text" name="WatchKeeping" id="WatchKeeping" required></td>
</tr>
<tr>
<td>Active:</td>
<td><input type="text" name="Active" id="Active" required></td>
</tr>
<tr>
<td><input type="submit" value="Submit" ></td>
</tr>
</form>
</table>
handlecrewedit.php
<?php
require 'dbfunction.php';
$con = getDbConnect();
$crew_id = $_POST["crew_id"];
$CrewName = $_POST["CrewName"];
$CrewRank = $_POST["CrewRank"];
$StartDate = $_POST["StartDate"];
$EndDate = $_POST["EndDate"];
$PayrollNo = $_POST["PayrollNo"];
$EmployeeNo = $_POST["EmployeeNo"];
$WatchKeeping = $_POST["WatchKeeping"];
$Active = $_POST["Active"];
if (!mysqli_connect_errno($con)) {
$sqlQueryStr = "UPDATE crewlist SET crew_name = '$CrewName', crew_rank = '$CrewRank', start_date = '$StartDate' "
. ", end_date = '$EndDate', payroll_no = '$PayrollNo'"
. ", employee_no = '$EmployeeNo', watchkeeping = '$WatchKeeping', active = '$Active' WHERE crew_id = " . $crew_id . "";
mysqli_query($con, $sqlQueryStr);
}
header('Location: crewlisting.php');
mysqli_close($con);
?>

I think the suggested answers miss a small point.
It only updates the first row because you exit the while loop with the redirection header.
header('Location: crewlisting.php');
mysqli_close($con);
Place those two lines outside your while loop, and it should update each row.
Your while loop will than be:
while ($row = mysqli_fetch_array($result)) {
// not needed. if (!mysqli_connect_errno($con)) {
$sqlQueryStr = "UPDATE crewlist SET crew_name = '$CrewName', crew_rank = '$CrewRank', start_date = '$StartDate' "
. ", end_date = '$EndDate', payroll_no = '$PayrollNo'"
. ", employee_no = '$EmployeeNo', watchkeeping = '$WatchKeeping', active = '$Active' WHERE crew_id = " . $row['crew_id'] . "";
//} closing bracket of if, but the if is not needed.
mysqli_query($con, $sqlQueryStr);
}
//after updating all rows, redirect
header('Location: crewlisting.php');
mysqli_close($con);

Related

INSERT query in PHP not working

I am really new to PHP and am messing around with adding and editing database values. I have accomplished adding information to the database, but I cannot seem to figure out how to edit it properly!
I created a file called edit.php and here is the code I have thus far:
<?php
include '../database/connection.php';
$id = $_GET['id'];
$first_name = $_GET['first_name'];
$last_name = $_GET['last_name'];
$university_id = $_GET['university_id'];
$sql = "UPDATE master_roster (first_name, last_name, university_id) VALUES ('$first_name', '$last_name', '$university_id') WHERE id = $id";
?>
No error messages of any help are posting. Whenever the form is submitted and is handed off to this file, I just get a blank screen with no results. I cannot seem to figure out what it is I am missing to have it update the content from input fields!
EDIT: I gave all of suggestions a shot but it still does not work! Here is the form that the data is coming from:
<?php
$id = $_GET['id'];
$first_name = $_GET['first_name'];
$last_name = $_GET['last_name'];
$university_id = $_GET['university_id'];
?>
<form action="edit_member.php?id=<?php echo $id; echo "&first_name="; echo $first_name; echo "&last_name="; echo $last_name; echo "&university_id="; echo $university_id; ?>" method="post">
<table>
<tr>
<td>First Name</td>
<td><input type="text" name="first_name" value="<?php echo $first_name; ?>"></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" name="last_name" value="<?php echo $last_name; ?>"></td>
</tr>
<tr>
<td>University ID</td>
<td><input type="text" name="university_id" value="<?php echo $university_id; ?>"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
I am not too concerned about SQL Injections at this point because I am just trying to learn the basics.
EDIT #2:
LIST.PHP - where the DB pulls all the members
<table>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>University ID</th>
</tr>
<?php
include '../database/connection.php';
$sql = "SELECT * FROM master_roster";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['first_name'] . "</td>";
echo "<td>" . $row['last_name'] . "</td>";
echo "<td>" . $row['university_id'] . "</td>";
echo "<td><a href='form.php?id=" . $row['id'] . "&first_name=" . $row['first_name'] . "&last_name=" . $row['last_name'] . "&university_id=" . $row['university_id'] . "'>Edit</a></td>";
echo "</tr>";
}
echo "</table>";
mysqli_free_result($result);
} else {
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
mysqli_close($link);
?>
EDIT.PHP
<?php
include '../database/connection.php';
$id = mysqli_real_escape_string($_POST['id']);
$first_name = mysqli_real_escape_string($_POST['first_name']);
$last_name = mysqli_real_escape_string($_POST['last_name']);
$university_id = mysqli_real_escape_string($_POST['university_id']);
$sql = "UPDATE master_roster
SET
first_name = '$first_name',
last_name = '$last_name',
university_id = '$university_id'
WHERE
id = $id";
?>
FORM.PHP
<form action="edit.php" method="post">
<table>
<tr>
<td>First Name</td>
<td><input type="text" name="first_name"></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" name="last_name"></td>
</tr>
<tr>
<td>University ID</td>
<td><input type="text" name="university_id"></td>
</tr>
<tr>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
This is the wrong syntax for update. update takes a series of column=value clauses:
UPDATE master_roster
SET first_name = '$first_name',
last_name = '$last_name',
university_id = '$university_id'
WHERE id = $id
Mandatory comment:
Using variable substitutions in strings like that leaves your code vulnerable to SQL injection attacks. You should consider using a prepared statement instead.
You're writing wrong UPDATE statement.
Try this
$sql = "UPDATE master_roster
SET
first_name = '$first_name',
last_name = '$last_name',
university_id = '$university_id'
WHERE
id = $id";
Now execute the query using statement below.
$result = $conn->query($sql);
$result will return true if the insertion is successful and false if not.
Use this to check if it is done or not.
if($result == false){
die( "Connection Failed: ".$conn->error );
}
You should also be prevented from SQL injection.
You can use mysqli_real_escape_string() method.
$first_name = $_GET['first_name'];
$safe_first_name = mysqli_real_escape_string($conn, $first_name);
You can also use parameterized query.
Read this.
Now read the codes below modify your both pages like this.
Form
<form action="edit.php" method="post">
<table>
<tr>
<td>First Name</td>
<td><input type="text" name="first_name"></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" name="last_name"></td>
</tr>
<tr>
<td>University ID</td>
<td><input type="text" name="university_id"></td>
</tr>
<tr>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
This will update the data.
<?php
include '../database/connection.php';
$id = mysqli_real_escape_string($conn, $_POST['id']);
$first_name = mysqli_real_escape_string($conn, $_POST['first_name']);
$last_name = mysqli_real_escape_string($conn, $_POST['last_name']);
$university_id = mysqli_real_escape_string($conn, $_POST['university_id']);
$sql = "UPDATE master_roster
SET
first_name = '$first_name',
last_name = '$last_name',
university_id = '$university_id'
WHERE
id = $id";
$result = $conn->query($sql);
if($result == false){
die( "Connection Failed: ".$conn->error );
}
?>

Get data from HTML table using PHP post

<form action="book.php" method="post">
<table>
<thead>
<tr>
<td>FlightID</td>
<td>From</td>
<td>Destination</td>
</tr>
</thead>
<tbody>
<tr>
<td name="flightID" value="1">1</td>
<td name="From" value="Sydney">Sydney</td>
<td name="Destination" value="Bali">Bali</td>
<td class="tdBook"><button class="btnBook" type=submit name="booking"> Book </button>
</tr>
<tr>
<td name="flightID" value="2">2</td>
<td name="From" value="London">London</td>
<td name="Destination" value="HongKong">Hong Kong</td>
<td class="tdBook"><button class="btnBook" type=submit name="booking"> Book </button>
</tr>
</tbody>
</table>
</form>
I created a table like this. At the end of each row, it has a book button.
What I am trying to do is when the user clicked the button, the selected row data(ID,From,Des) will pass to the 'book.php', then the PHP file will do the rest of the job.
But I tried to catch the value using $_POST['name'] in 'book.php', like this
<?php
if(isset($_POST['booking'])){
$ID = $_POST['flightID'];
$From = $_POST['From'];
$To = $_POST['Destination'];
}
?>
It shows all of those values are undefined. Any help would be appreciated.
The problem is that the values in <td> cannot be passed from the form to your PHP file by themselves. You could use hidden inputs for this. Additionally, each row in the table should be its own form to assure that all data is not submitted at the same time.
Try this:
<table>
<thead>
<tr>
<td>FlightID</td>
<td>From</td>
<td>Destination</td>
</tr>
</thead>
<tbody>
<tr>
<form action="book.php" method="post">
<td><input type="hidden" name="flightID" value="1">1</td>
<td><input type="hidden" name="From" value="Sydney">Sydney</td>
<td><input type="hidden" name="Destination" value="Bali">Bali</td>
<td class="tdBook"><button class="btnBook" type=submit name="booking"> Book </button>
</form>
</tr>
<tr>
<form action="book.php" method="post">
<td><input type="hidden" name="flightID" value="2">2</td>
<td><input type="hidden" name="From" value="London">London</td>
<td><input type="hidden" name="Destination" value="HongKong">Hong Kong</td>
<td class="tdBook"><button class="btnBook" type=submit name="booking"> Book </button>
</form>
</tr>
</tbody>
i have the same problem as yours and tried to create an answer so i came up with this code to indicate each row in an HTML table with a special name using loops, i can now take the specified row and do as much PHP operations as i can with it without disturbing the table as a whole and it was well synchronized with my database, hope it helps!
and btw the whole "marking each row with a special name" code is in usersTable.php
users.sql
create table users(
id int,
username varchar(50),
password varchar(50)
);
users.php
<?php
$host = "localhost";
$username = "root";
$password = "";
$database = "wdl2hw4db";
$conn = mysqli_connect($host, $username, $password, $database);
if (mysqli_connect_errno()){
die("can't connect to the Database" . mysqli_connect_errno());
}else{
echo "Database is connected" . "<br>";
}
if (isset($_POST['insert'])){
$idN1= $_POST['id'];
$usernameN1 = $_POST['username'];
$passwordN1 = $_POST['password'];
$query = "insert into users(id, username, pass) values ('".$idN1."' , '".$usernameN1."' , '".$passwordN1."' )";
$result = mysqli_query($conn, $query);
}else if (isset($_POST['update'])){
$idN2 = $_POST['id'];
$usernameN2 = $_POST['username'];
$passwordN2 = $_POST['password'];
$query = "update users set pass = '". $passwordN2 ."'where id = " . $idN2;
$result = mysqli_query($conn, $query);
}else if (isset($_POST['Display'])){
header('Location: usersTable.php');
}
echo "<br>";
?>
<form method="post">
ID: <input type="text" name="id" ><br><br>
username: <input type="text" name="username" ><br><br>
password: <input type="password" name="password" ><br><br>
<input type="submit" name="insert" value="insert">
<input type="submit" name="Display" value="Display">
</form>
userTable.php
<?php
$host = "localhost";
$username = "root";
$password = "";
$database = "wdl2hw4db";
$conn = mysqli_connect($host, $username, $password, $database);
$query = "select * from users";
$result = mysqli_query($conn, $query);
echo "<table border=\"6px\"><thead><tr><th>ID</th><th>username</th><th>password</th><th>Delete</th><th>Update</th></tr></thead>";
$i = 1;
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr><form method='post'><td>" . $row['id'] . "</td><td>" . $row['username'] . "</td><td>" . $row['pass'] . "</td><td><input type='submit' name='Delete" . $i . "' value='Delete'></td><td><input type='submit' name='Update" . $i . "' value='Update'><input type='text' name='UpdateText" . $i . "' placeholder='insert new password here'></td></form></tr>";
$i++;
}
echo "</table>";
$i = 1;
$result2 = mysqli_query($conn, $query);
while ($row2 = mysqli_fetch_assoc($result2)) {
if (isset($_POST['Delete' . $i])) {
$usernameN4 = $row2['username'];
$query2 = "delete from users where username ='" . $usernameN4 . "'";
$result2 = mysqli_query($conn, $query2);
header("Refresh:0");
break;
}
$i++;
};
$i = 1;
$result3 = mysqli_query($conn, $query);
while ($row3 = mysqli_fetch_assoc($result3)) {
if (isset($_POST['Update' . $i]) && $_POST['UpdateText' . $i] != null ) {
$id4 = $row3['id'];
$Utext = $_POST['UpdateText' . $i];
$query3 = "update users set pass ='" . $Utext . "' where id = " . $id4;
$result3 = mysqli_query($conn, $query3);
header("Refresh:0");
break;
}
$i++;
};
mysqli_free_result($result);

Display all rows and update all rows by a submit

I want to display all rows by a php query and update all by a submit button in sql. I this way below a can display all row and update particular row by its own submit button. But I want to update all by a single submit button.
So for do it, I thank, I want to loop for update. But I cannot understand how to do it in this case.
Here is my code:
<?php
include_once('../db.php');
global $db;
$result = mysqli_query($dbh,"SELECT * FROM ppad");
if(!$result) {
die("Database query failed: " . mysqli_error());
}
while($row = mysqli_fetch_assoc($result)) {
$id=$row['id'];
$name=$row['name'];
$date=$row['date'];
$title=$row['title'];
$Detail=$row['Detail'];
echo '<form action="padSproccess.php" method="POST">
<table width="100%" border="1">
<tr>
<td width="10%">Date</td>
<td width="14%">Time</td>
<td width="20%">Name(url)</td>
<td width="30%">Detail</td>
</tr>
<tr>
<td width="10%"><input type="text" name="date" maxlength="2" value="'.$date.'"></td>
<td width="14%"><input type="text" name="title" maxlength="50" value="'.$title.'"></td>
<td width="20%"><input type="text" name="name" maxlength="50" value="'.$name.'"></td>
<td width="30%"><input type="text" name="Detail" maxlength="100" value="'.$Detail.'"></td>
<input type="hidden" name="id" value="'.$id.'">
</tr>
</table>
<input type="submit" name="submit" id="submit" value="Submit">
</form>';}
?>
padSproccess.php
include("../db.php");
global $db;
if(isset($_POST['submit'])){
$date = mysqli_real_escape_string($dbh,$_POST['date']);
$title = mysqli_real_escape_string($dbh,$_POST['title']);
$name = mysqli_real_escape_string($dbh,$_POST['name']);
$Detail = mysqli_real_escape_string($dbh,$_POST['Detail']);
$id = mysqli_real_escape_string($dbh,$_POST['id']);
// update data in mysql database
$update = mysqli_query($dbh,"UPDATE ppad SET date='$date', month='$month', name='$name', Detail='$Detail' WHERE id = '$id'");
// if successfully updated.
}
For this you need to update your code into
<?php
include_once('../db.php');
global $db;
$result = mysqli_query($dbh,"SELECT * FROM ppad");
if(!$result) {
die("Database query failed: " . mysqli_error());
}?>
<form action="padSproccess.php" method="POST">
<table width="100%" border="1">
<tr>
<td width="10%">Date</td>
<td width="14%">Time</td>
<td width="20%">Name(url)</td>
<td width="30%">Detail</td>
</tr>
<?php
while($row = mysqli_fetch_assoc($result)) {
$id=$row['id'];
$name=$row['name'];
$date=$row['date'];
$title=$row['title'];
$Detail=$row['Detail'];
echo '<tr>
<td width="10%"><input type="text" name="date[]" maxlength="2" value="'.$date.'"></td>
<td width="14%"><input type="text" name="title[]" maxlength="50" value="'.$title.'"></td>
<td width="20%"><input type="text" name="name[]" maxlength="50" value="'.$name.'"></td>
<td width="30%"><input type="text" name="Detail[]" maxlength="100" value="'.$Detail.'"></td>
<input type="hidden" name="id[]" value="'.$id.'">
</tr>';
}?>
</table>
<input type="submit" name="submit" id="submit" value="Submit">
</form>
Now within your padSproccess.php you'll receive an array of results within your variables which'll be updated using foreach loop
What you need to do first is have an overall form, not a form for each (unless you want to throw in javascript to fire off ajax calls). So what you'll need to do is make sure each row can be associated with a specific id:
<?php
include_once '../db.php';
$result = mysqli_query($dbh, "SELECT * FROM ppad");
if(!$result) {
die("Database query failed: " . mysqli_error());
}
?>
<form action="padSproccess.php" method="POST">
<table width="100%" border="1">
<thead>
<tr>
<td width="10%">Date</td>
<td width="14%">Time</td>
<td width="20%">Name(url)</td>
<td width="30%">Detail</td>
</tr>
</thead>
<tbody>
<?php
while($row = mysqli_fetch_assoc($result)) {
$id = $row['id'];
$name = $row['name'];
$date = $row['date'];
$title = $row['title'];
$Detail = $row['Detail'];
echo '
<tr>
<td width="10%"><input type="text" name="date[' . $id . ']" maxlength="2" value="'.$date.'"></td>
<td width="14%"><input type="text" name="title[' . $id . ']" maxlength="50" value="'.$title.'"></td>
<td width="20%"><input type="text" name="name[' . $id . ']" maxlength="50" value="'.$name.'"></td>
<td width="30%"><input type="text" name="Detail[' . $id . ']" maxlength="100" value="'.$Detail.'"></td>
</tr>
';
}
?>
</tbody>
</table>
<input type="submit" name="submit" id="submit" value="Submit">
</form>
Then in padSproccess.php you'll receive an array of names, dates, titles and Details, each one keyed by the ID of the row. So that'll change to something like this:
<?php
include "../db.php";
if(isset($_POST['submit'])){
$ids = array_keys($_POST['name']);
foreach ($ids as $id) {
$date = mysqli_real_escape_string($dbh,$_POST['date'][$id]);
$title = mysqli_real_escape_string($dbh,$_POST['title'][$id]);
$name = mysqli_real_escape_string($dbh,$_POST['name'][$id]);
$Detail = mysqli_real_escape_string($dbh,$_POST['Detail'][$id]);
$id = mysqli_real_escape_string($id);
// update data in mysql database
$update = mysqli_query($dbh,"UPDATE ppad SET date='$date', month='$month', name='$name', Detail='$Detail' WHERE id = '$id'");
}
// if successfully updated.
}
Try this. Of course for the database I've not started and it is possible errors.
<?php
include_once('../db.php');
global $db;
$result = mysqli_query($dbh,"SELECT * FROM ppad");
if(!$result) {
die("Database query failed: " . mysqli_error());
}
?>
<form action="padSproccess.php" method="POST">
<?php
while($row = mysqli_fetch_assoc($result)) {
$id=$row['id'];
$name=$row['name'];
$date=$row['date'];
$title=$row['title'];
$Detail=$row['Detail'];
echo '
<table width="100%" border="1">
<tr>
<td width="10%">Date</td>
<td width="14%">Time</td>
<td width="20%">Name(url)</td>
<td width="30%">Detail</td>
</tr>
<tr>
<td width="10%"><input type="text" name="ar['.$id.'][date]" maxlength="2" value="'.$date.'"></td>
<td width="14%"><input type="text" name="ar['.$id.'][title]" maxlength="50" value="'.$title.'"></td>
<td width="20%"><input type="text" name="ar['.$id.'][name]" maxlength="50" value="'.$name.'"></td>
<td width="30%"><input type="text" name="ar['.$id.'][Detail]" maxlength="100" value="'.$Detail.'"></td>
</tr>
</table>
';}
?>
<input type="submit" name="submit" id="submit" value="Submit">
</form>
<?php
include("../db.php");
global $db;
if(isset($_POST['submit'])){
foreach($_POST['ar'] as $id=>$dat){
$date = mysqli_real_escape_string($dbh,$dat['date']);
$title = mysqli_real_escape_string($dbh,$dat['title']);
$name = mysqli_real_escape_string($dbh,$dat['name']);
$Detail = mysqli_real_escape_string($dbh,$dat['Detail']);
$id = mysqli_real_escape_string($dbh,$id]);
// update data in mysql database
$update = mysqli_query($dbh,"UPDATE ppad SET date='$date', month='$month', name='$name', Detail='$Detail' WHERE id = '$id'");
}
// if successfully updated.
}
?>

Why the mysql update query in php not working?

Please help me regarding the problem specified in the title.
Input form page code:
<?
db_connect();
$query1 = "SELECT *, DATE_FORMAT(eventdate,'%m/%d/%y') AS
eventdate,DATE_FORMAT(throughdate,'%m/%d/%y') AS throughdate FROM events WHERE id = " . mysql_real_escape_string($_REQUEST['id']);
$result1 = mysql_query($query1) or die("Error - query failed " . mysql_error());
if ( mysql_num_rows($result1) == 0 ) {
print "<p>Error - no such event.</p>\n";
return;
}
else {
$qry_event1 = mysql_fetch_array($result1);
}
// default the formaction to the query
if (! isset($_REQUEST['formaction']) ) { $_REQUEST['formaction'] = 'query'; }
?>
<form name="eventform" method="post" action="act_updevent.php">
<input type="hidden" name="submit_check" value="1">
<input type="hidden" name="formaction" value="form">
<!-- if we are editing, $id will exist. Pass it along. -->
<input type="hidden" name="id" value="<?php $qry_event1['id'];?>">
<table>
<tr>
<td align="right" valign="center"><b><? displayformlabel('eventdate','Event Date:')?>
</b></td>
<td><input name="eventdate" value="<? echo $qry_event1['eventdate']; ?>">
<a name="calendar1here" id="calendar1here" href="JavaScript:;"
onClick="cal1.select(document.forms[0].eventdate,'calendar1here','MM/dd/yy'); return
false;">
<img src="resources/calendar.gif" alt="Calendar Icon" width="20" height="20"
border="0"></a>
</td>
</tr>
<tr>
<td align="right" valign="center"><b><? displayformlabel('throughdate','Through:')?>
</b></td>
<td><input name="throughdate" value="<? echo $qry_event1['throughdate']; ?>">
<a name="calendar2here" id="calendar2here" href="JavaScript:;"
onClick="cal2.select(document.forms[0].throughdate,'calendar2here','MM/dd/yy'); return
false;">
<img src="resources/calendar.gif" alt="Calendar Icon" width="20" height="20"
border="0"></a>
<span class="formnotes">Leave blank if only one day event</span>
</td>
</tr>
<tr>
<td align="right"><b><? displayformlabel('title','Event Title:')?></b></td>
<td><input name="title" size="50" maxlength="50" value="<? echo $qry_event1['title'];?
>"></td>
</tr>
<tr>
<td align="right"><? displayformlabel('website','Event Website:')?></td>
<td><input name="website" size="50" maxlength="100" value="<? echo
$qry_event1['website']; ?>"></td>
</tr>
<tr>
<td align="right"><? displayformlabel('email','Event Email:')?></td>
<td><input name="email" size="50" maxlength="100" value="<? echo
$qry_event1['email'];?>"></td>
</tr>
<tr>
<td align="right" valign="top"><? displayformlabel('notes','Notes:')?></td>
<td><textarea name="notes" style="width: 320px; height: 60px;"><? echo
$qry_event1['notes']; ?></textarea></td>
</tr>
<tr>
<td align="right"><? displayformlabel('venue','Venue:')?></td>
<td><input name="venue" size="50" maxlength="50" value="<? echo $qry_event1['venue'];?
>"></td>
</tr>
<tr>
<td align="right"><? displayformlabel('address','Address:')?></td>
<td><input name="address" size="50" maxlength="50" value="<?echo
$qry_event1['address'];?>"></td>
</tr>
<tr>
<td align="right"><? displayformlabel('city','City:')?></td>
<td><input name="city" size="50" maxlength="50" value="<?echo $qry_event1['city'];?
>"></td>
</tr>
<tr>
<td align="right"><? displayformlabel('state','State:')?></td>
<td><input name="state" size="3" maxlength="2" value="<?echo $qry_event1['state'];?
>"></td>
</tr>
<tr>
<td align="right"><? displayformlabel('lat','Latitude:')?></td>
<td><input name="lat" size="15" maxlength="15" value="<? echo $qry_event1['lat'];?>">
</td>
</tr>
<tr>
<td align="right"><? displayformlabel('lon','Longitude:')?></td>
<td><input name="lon" size="15" maxlength="15" value="<? echo $qry_event1['lon'];?>">
<span class="formnotes">Look up
coordinates using above address information.</span>
</td>
</tr>
<tr>
<td align="right"><? displayformlabel('accurate','Accurate:')?></td>
<td><input name="accurate" type="checkbox" value="1" <?php if
(isset($qry_event1['accurate'])) { echo 'checked="checked"'; }?>>
<a href="JavaScript:;" class="formnotes" onClick="window.open('<?php
print $vsf->self;?>?action=accuratehelp','helpwin','width=435,height=220');">Whats
this?</a>
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
Update page:
<?php
// updates a record in the database
// do validation (shared with update logic)
$id = $_REQUEST['id'];
$eventdate = $_REQUEST['eventdate'];
$throughdate = $_REQUEST['throughdate'];
$title = $_REQUEST['title'];
$website = $_REQUEST['website'];
$email = $_REQUEST['email'];
$notes = $_REQUEST['notes'];
$venue = $_REQUEST['venue'];
$address = $_REQUEST['address'];
$city = $_REQUEST['city'];
$state = $_REQUEST['state'];
$lat = $_REQUEST['lat'];
$lon = $_REQUEST['lon'];
$accurate = $_REQUEST['accurate'];
$errorwasthrown="";
$database = 'mapcal';
// database server
$dbsvr = 'localhost';
// username
$dbuser = 'root';
// password
$dbpass = 'usbw';
function db_connect() {
global $dbsvr,$dbuser,$dbpass,$database;
static $dbcon;
if ( ! $dbcon ) {
$dbcon = mysql_connect($dbsvr,$dbuser,$dbpass);
if (! mysql_select_db($database) ) {
die("Failure connecting to database - " . mysql_error());
}
}
}
if (! $eventdate ) {
adderrmsg('eventdate','Event date cannot be blank.');
$errorwasthrown=1;
}
else {
// else date wasn't blank, so validate it
if (! preg_match("/^\d\d\/\d\d\/\d\d$/",$eventdate) ) {
adderrmsg('eventdate',"Event date must be in format mm/dd/yy.");
$errorwasthrown=1;
}
}
if ($throughdate && ! preg_match("/^\d\d\/\d\d\/\d\d$/",$throughdate) ) {
adderrmsg('throughdate',"Through date must be in format mm/dd/yy.");
$errorwasthrown=1;
}
if (! $title ) {
adderrmsg('title','Title cannot be blank.');
$errorwasthrown=1;
}
if ($errorwasthrown) {
include('dsp_editevent.php');
}
else {
db_connect();
// format the date correctly for mysql
$dateparts = split("/",$eventdate);
$eventdate = "$dateparts[2]/$dateparts[0]/$dateparts[1]";
if ($throughdate) {
$dateparts = split("/",$throughdate);
$throughdate = "$dateparts[2]/$dateparts[0]/$dateparts[1]";
$throughdate = "'" . mysql_real_escape_string($throughdate) . "'";
}
else {
$throughdate = 'NULL';
}
// format event website if necessary
if ($website && ! preg_match("/:\/\//",$website) ) {
$website = "http://" . $website;
}
// update record in the database
$query = "UPDATE events SET ";
$query .= "eventdate = '" . mysql_real_escape_string($eventdate) . "', " .
"throughdate = " . $throughdate . ", " .
"title = '" . mysql_real_escape_string($title) . "', " .
"website = '" . mysql_real_escape_string($website) . "', " .
"email = '" . mysql_real_escape_string($email) . "', " .
"notes = '" . mysql_real_escape_string($notes) . "', " .
"venue = '" . mysql_real_escape_string($venue) . "', " .
"address = '" . mysql_real_escape_string($address) . "', " .
"city = '" . mysql_real_escape_string($city) . "', " .
"state = '" . mysql_real_escape_string($state) . "', " .
"lat = '" . mysql_real_escape_string($lat) . "', " .
"lon = '" . mysql_real_escape_string($lon) . "', " .
"accurate = '" . mysql_real_escape_string($accurate) . "' " .
"WHERE id = " . mysql_real_escape_string($id);
if ( ! mysql_query($query) ) {
exit("Query failed! - $query");
}
print "<p style='color: green'>Event <b>$title</b> was updated.</p>\n";
include('dsp_listevents.php');
} // close else ! errorwasthrown
?>
What i can see after printing the query is that it is not getting the value of id but all the fields from the form but why?
Keep the Id value in quotes.
"WHERE id = '" . mysql_real_escape_string($id)."'";

Need help... how to add md5 to password field in php?

i looking some help and nice attention here..
i bought some php script many years ago and now no suport anymore... i just want to add md5 to password field..
here my form:
<?php
$SQL = "SELECT * from USERS WHERE USERNAME = '$_SESSION[username]'"; $result = #mysql_query( $SQL ); $row = #mysql_fetch_array( $result );
include 'menu.php';
?>
<FORM METHOD="post" ACTION="?page=query_client">
<INPUT TYPE="hidden" NAME="controller" VALUE="USERS~update~account_details&up=1~<?php echo $row[ID]; ?>">
<TABLE CLASS="basictable">
<TR>
<TD CLASS="tdmenu" WIDTH="40%">Username</TD>
<TD CLASS="tdmenu" WIDTH="60%">
<b><?php echo $row[USERNAME]; ?></b>
</TD>
</TR>
<TR>
<TD CLASS="tdmenu" WIDTH="40%">Password *</TD>
<TD CLASS="tdmenu" WIDTH="60%">
<INPUT TYPE="PASSWORD" NAME="PASSWORD" SIZE="40" VALUE="<?php echo $row[PASSWORD]; ?>">
</TD>
</TR>
<TR>
<TD CLASS="tdmenu" WIDTH="40%">Email Address *</TD>
<TD CLASS="tdmenu" WIDTH="60%">
<INPUT TYPE="text" NAME="EMAIL" SIZE="40" VALUE="<?php echo $row[EMAIL]; ?>">
</TD>
</TR>
<TR>
<TD CLASS="tdmenu" WIDTH="40%">Full Name *</TD>
<TD CLASS="tdmenu" WIDTH="60%">
<INPUT TYPE="text" NAME="FULLNAME" SIZE="40" VALUE="<?php echo $row[FULLNAME]; ?>">
</TD>
<TR>
<TD CLASS="tdmenu" WIDTH="40%">Address *</TD>
<TD CLASS="tdmenu" WIDTH="60%">
<INPUT TYPE="text" NAME="ADDRESS1" SIZE="40" VALUE="<?php echo $row[ADDRESS1]; ?>">
</TD>
</TR>
<BR>
<TABLE CLASS="basictable">
<TR>
<TD CLASS="tdhead2" >
<DIV ALIGN="CENTER"><B>
<INPUT TYPE="submit" NAME="Submit" VALUE="Submit">
</B></DIV>
</TD>
</TR>
</TABLE>
</FORM>
and the
it self as query_client.php inside look like:
<?PHP
#session_start();
$controller = $_POST['controller'];
$pieces = explode("~", $controller);
$table = $pieces[0];
$qt = $pieces[1];
$return = $pieces[2];
$id = $pieces[3];
$hack = $pieces[4];
if ($qt == insert) $qt = 'INSERT INTO';
if ($qt == update) { $qt = 'UPDATE'; $end = "WHERE ID = '$id'"; }
$pre = array_keys( $_POST );
mysql_query ("CREATE TABLE IF NOT EXISTS `$table` (`ID` INT NOT NULL AUTO_INCREMENT , PRIMARY KEY ( `id` ) )");
$count = count($pre); $count = $count - 2;
$sql = "$qt $table SET";
for ($i=0; $i < $count; $i++)
{
$x=$i+1;
$y = $_POST[$pre[$x]];
$d = $y;
mysql_query ("ALTER TABLE `$table` ADD `$pre[$x]` TEXT NOT NULL");
$sql .= " `$pre[$x]` = '$d',";
}
$sql .= " ID = '$id' $end";
$query = mysql_query($sql) or die("$sql_error" . mysql_error());
if (empty($hack)) { } else {
$pieces = explode("/", $hack);
$h0 = $pieces[0];
$h1 = $pieces[1];
$h2 = $pieces[2];
$h3 = $pieces[3];
$h4 = $pieces[4];
$h5 = $pieces[5];
mysql_query ("ALTER TABLE `$table` $h0 $h1 $h2 $h3 $h4 $h5");
$query = mysql_query($sql) or die("$sql_error" . mysql_error());
}
if (isset($_GET[inc])) include "$_GET[inc].php";
?>
so please help me how to add md5 in PASSWORD field?
thanks in advance..
Best to use a salt also - hashing and verification should be done at server - see secure hash and salt for PHP
Some links on writing secure code:
OWASP Top 10 for 2010
PHP Security: Fortifying Your Website
Writing Secure PHP

Categories