form wont send data to mysql - php

I'm trying to code a form that gets some data from a mysql db, and the rest i have to fill inn myself. The problem is that in add.php witch insert to mysql dont get data from the form.
My codes are:
<form action="add.php" method="post">
<table border="0px" align="center" width="300px">
<tr align="center">
<td><h2>Flight</h2></td>
<td><h2>Org</h2></td>
<td><h2>Dest</h2></td>
<td><h2>STD</h2></td>
<td><h2>ATD</h2></td>
<td><h2>Delay</h2></td>
<td><h2>NET</h2></td>
<td><h2>Gros</h2></td>
<td><h2>Core Material</h2></td>
<td><h2>ACS</h2></td>
<td><h2>Total sorted</h2></td>
</tr>
<?php
$con = mysql_connect("localhost","db","pass") or die('Could not connect: ' .mysql_error());
mysql_select_db("db", $con) or die(mysql_error());
$q="SELECT flightnr, org, dest, std FROM flight";
$sql = mysql_query($q) or die("MySQL ERROR: ".mysql_error());
while($row = mysql_fetch_array($sql))
{
$flightnr2 = $row['flightnr'];
$org2 = $row['org'];
$dest2 = $row['dest'];
$std2 = $row['std'];
}
?>
<tr>
<td><input type="text" name="flightnr" value="<?php echo $flightnr2;?>" /></td>
<td><input type="text" name="org" id="org" value="<?php echo $org2;?>" /></td>
<td><input type="text" name="dest" id="dest" value="<?php echo $dest2;?>" /></td>
<td><input type="text" name="std" id="std" value="<?php echo $std2;?>" /></td>
<td><input type="time" name="adt" id="adt" placeholder="ATD"></td>
<td><input type="time" name="delay" id="delay" placeholder="Delay"></td>
<td><input type="int" name="net" id="net" placeholder="NET"></td>
<td><input type="int" name="gros" id="gros" placeholder="Gros"></td>
<td><input type="int" name="core" id="core" placeholder="Core Material"></td>
<td><input type="int" name="acs" id="acs" placeholder="ACS"></td>
<td><input type="int" name="tot" id="tot" placeholder="Total sorted"></td>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
add.php:
<?php
$con = mysql_connect("localhost","db","pass") or die('Could not connect: ' .mysql_error());
mysql_select_db("db", $con) or die(mysql_error());
$date = date("D-m-Y");
$flightnr = $_POST['flightnr'];
$org = $_POST['org'];
$dest = $_POST['dest'];
$std = $_POST['dest'];
$adt = mysql_real_escape_string($_POST['adt']);
$delay = mysql_real_escape_string($_POST['delay']);
$net = mysql_real_escape_string($_POST['net']);
$gros = mysql_real_escape_string($_POST['gros']);
$core = mysql_real_escape_string($_POST['core']);
$acs = mysql_real_escape_string($_POST['acs']);
$tot = mysql_real_escape_string($_POST['tot']);
$sql="INSERT INTO fly (date, flightnr, org, dest, std, adt, delay, net, gros, core, acs, tot)VALUES('$date', '$flightnr', '$org', '$std', '$adt', '$delay', '$net', '$gros', '$core', '$acs', '$tot')";
$result=mysql_query($sql);
if($result){
echo "Successful";
echo "<BR>";
}
else {
echo "ERROR";
}
?>
Any idea how I can get it to work...

In add.php you're checking $row instead of $_POST.
It should be:
if (isset($_POST['atd']) && isset($_POST['..']) && ... )
{
$values = Array($_POST['atd'], $_POST['..'], ...);
$values = array_map("mysql_real_escape_string", $values);
$sql = "INSERT INTO fly (date, flightnr, org, dest, std, adt, delay, net, gros, core, asc, tot) VALUES ('" . implode(',', $values) . "');";
}
Anyway you should use PDO or MySQLi because MySQL is deprecated.

There is a lot of miss spelling and mistakes here.. take a look at this:
echo '<td><input type="int" name="acs" id="acs" placeholder="ACS"></td>'
and
$asc = mysql_real_escape_string($_POST['asc']);
So you realy have to read your codes, and check your spelling.
Here is one more:
$dest = $row['dest'];
$std = $row['dest'];
This should be like this:
$dest = $row['dest'];
$std = $row['std'];

in your form add hidden field like
">
in your add.php file get your data like
$flightner=$_POST['flightnr'];
then fire sql query insert into..
<input type="hidden" name="test" id="test" value="<?php echo $row['flightnr'];?>"/>
Hi.. xzibiz
First,you have to store a value $row['flightnr'] in specific hidden field then use $_POST['test'] to fetch actual value
$flightnr=$_POST['test'];
Reason for error...
php only reads those data which sent by html input field so you can fetch those value from inputed field html using php server variable $_REQUEST['html_input_field']

I've got it working now.. my new code is:
$q="SELECT flightnr, org, dest, std FROM flight";
$sql = mysql_query($q) or die("MySQL ERROR: ".mysql_error());
while($row = mysql_fetch_array($sql))
{
$flightnr2 = $row['flightnr'];
$org2 = $row['org'];
$dest2 = $row['dest'];
$std2 = $row['std'];
}
?>
<tr>
<td><input type="text" name="flightnr" value="<?php echo $flightnr2;?>" /></td>
<td><input type="text" name="org" id="org" value="<?php echo $org2;?>" /></td>
<td><input type="text" name="dest" id="dest" value="<?php echo $dest2;?>" /></td>
<td><input type="text" name="std" id="std" value="<?php echo $std2;?>" /></td>
add.php:
$date = date("D-m-Y");
$flightnr = $_POST['flightnr'];
$org = $_POST['org'];
$dest = $_POST['dest'];
$std = $_POST['dest'];
$adt = mysql_real_escape_string($_POST['adt']);
$delay = mysql_real_escape_string($_POST['delay']);
$net = mysql_real_escape_string($_POST['net']);
$gros = mysql_real_escape_string($_POST['gros']);
$core = mysql_real_escape_string($_POST['core']);
$acs = mysql_real_escape_string($_POST['acs']);
$tot = mysql_real_escape_string($_POST['tot']);
$sql = "INSERT INTO fly ".
"(date, flightnr, org, dest, std, adt, delay, net, gros, core, acs, tot) ".
"VALUES ('$date', '$flightnr', '$org', '$dest', '$std', '$adt', '$delay', '$net', '$gros', '$core', '$acs', '$tot')";
$retval = mysql_query( $sql, $con );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($con);
?>

Related

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);

Having trouble getting my mysql table to update

This is the form I use to edit my table:
<?php
// get value of id that sent from address bar
$id=$_GET['id'];
// Retrieve data from database...
$sql = "SELECT * FROM chart WHERE id='$id'";
$result = $conn->query($sql);
// Output the loop...
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) { ?>
<form action="./include/update.php" method="post">
<tbody>
<tr>
<td><input type="date" id="date" name="date" value="<?php echo $row['date']; ?>" /></td>
<td><input type="text" id="nuvolog_am" name="nuvolog_am" value="<?php echo $row['nuvolog_am']; ?>" /></td>
<td><input type="text" id="nuvolog_noon" name="nuvolog_noon" value="<?php echo $row['nuvolog_noon']; ?>" /></td>
<td><input type="text" id="nuvolog_pm" name="nuvolog_pm" value="<?php echo $row['nuvolog_pm']; ?>" /></td>
<td><input type="text" id="predisone" name="predisone" value="<?php echo $row['predisone']; ?>" /></td>
<td><input type="text" id="norvase" name="norvase" value="<?php echo $row['norvase']; ?>" /></td>
<tr>
<td colspan="17"><input type="text" id="symptoms" name="symptoms" value="<?php echo $row['symptoms']; ?>" /></td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="17"><input type="submit" value="Add Records"></td>
</tr>
</tfoot>
</form>
<? }
} else {
echo "0 results";
}
// Close the connection...
mysqli_close($link);
?>
And this is the update.php
<?php
// Database credentials...
$servername = "localhost";
$username = "...";
$password = "...";
$dbname = "...";
// Database connection...
$conn = new mysqli($servername, $username, $password, $dbname);
// Check the connection...
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// update data in mysql database
$sql="UPDATE chart SET
id = '$id',
date = '$date',
nuvolog_am = '$nuvolog_am',
nuvolog_noon = '$nuvolog_noon',
nuvolog_pm = '$nuvolog_pm',
predisone = '$predisone',
norvase = '$norvase'
WHERE id='$id'";
$result=mysql_query($sql);
// When chart is submitted...
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
// Close the connection...
mysqli_close($link);
?>
It's probably something very simple, but I cannot figure out why this won't update the records database. I'm hoping somebody can help me figure this out.
Please replace $result=mysql_query($sql); to mysqli code.
like
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";
$conn->query($sql);
to run query use this
$conn->query($sql);
You are updating the table using $result=mysql_query($sql); while to connect you used $conn = new mysqli($servername, $username, $password, $dbname);
By the way you should delete this question (if it's possible) or change all your passwords if the password that appears in the old version is used for other accounts too (you can see the edit history).

Image is not storing in mysql database via php

I am trying to upload image and store it in mysql database through php. but no image is storing in database.
<form action="" method="get" name="frmPostImage" class="box" enctype="multipart/form-data">
<table>
<tr>
<td><b>City:</b></td>
<td>
<select name="cityid">
<?php
$sql = "SELECT cityid, cityname, countryname
FROM $t_cities ct
INNER JOIN $t_countries c ON ct.countryid = c.countryid
ORDER BY c.pos, ct.pos";
$res = mysql_query($sql) or die(mysql_error());
while($row=mysql_fetch_array($res))
{
echo "<option value=\"$row[cityid]\"";
if ($row['cityid'] == $_REQUEST['cityid']) echo " selected";
echo ">$row[countryname] > $row[cityname]</option>";
}
?>
</select>
</td>
</td>
</tr>
<tr>
<tr>
<td><b><?php echo $lang['POSTIMG_IMAGE_TITLE']; ?>:</b><span class="marker">*</span></td>
<td><input name="imgtitle" type="text" id="imgtitle" size="55" maxlength="100" value="<?php echo isset($data
['imgtitle']); ?>"><br><img
src="images/spacer.gif"></td>
</tr>
<tr>
<td><b><?php echo $lang['POSTIMG_IMAGE_FILE']; ?>:</b><span class="marker">*</span></td>
<td><input name="img" type="file" size="45"><br><img src="images/spacer.gif"></td>
</tr>
<tr>
<td><b><?php echo $lang['POSTIMG_IMAGE_DESCRIPTION']; ?>:</b></td>
<td><textarea name="imgdesc" type="text" rows="5" cols="54"><?php echo $data['imgdesc']; ?></textarea><br><img
src="images/spacer.gif"></td>
<td> <input type="hidden" name="do" value="save"><button type="submit">Go</button></td>
</tr>
</table>
</form>
and following code to store it into database.
$expiry = time()+($expire_images_after*24*60*60);
$expiry_dt = date("Y-m-d H:i:s", $expiry);
$city = $_REQUEST['cityid'];
// Temporary file name stored on the server
$tmpName = $_FILES['img']['tmp_name'];
$sql = "INSERT INTO $t_imgs
SET imgtitle = '$_GET[imgtitle]',
imgfilename = '$tmpName',
imgdesc = '$_GET[imgdesc]',
postername = '$data[postername]',
cityid = '$city',
ip = '$ip',
verified = '1',
enabled = '1',
createdon = NOW(),
expireson = '$expiry_dt',
timestamp = NOW()";
mysql_query($sql) or die($sql.mysql_error());
if (mysql_affected_rows())
{
// Get ID
$sql = "SELECT LAST_INSERT_ID() FROM $t_imgs";
list($imgid) = mysql_fetch_array(mysql_query($sql));
}
}
?>
<h2><?php echo $lang['POST_IMAGE_SUCCESS']; ?></h2>
i am able to store every other value except the image. tried different combination but nothing worked. Guide me...:)
I think there can be issues with mysql statement:
instead $sql = "INSERT INTO $t_imgs SET imgtitle
you should probably use $sql = "INSERT INTO $t_imgs values (imgtitle, ...);
check here:
http://dev.mysql.com/doc/refman/5.5/en/insert.html

Inserting multiple checkbox values to MySQL

I know there are multiple questions here on SO regarding this same issue already and I've looked into them but didn't quite get a satisfying answer. So here goes my question,
I have a form which consists of a few textboxes and checkboxes. It looks like this,
The user can select multiple checkboxes. I'm trying to insert the values(not the displaying text string) of those checkboxes into a MySQL table. It should look like this,
One Service ID(SID) can have multiple Locations(Loc_Code). Those location codes (CO, GQ) are the values of the checkboxes.
I've written this following code so far.
<html>
<head>
</head>
<body>
<?php
require_once("db_handler.php");
$conn = iniCon();
$db = selectDB($conn);
/* Generating the new ServiceID */
$query = "SELECT SID FROM taxi_services ORDER BY SID DESC LIMIT 1";
$result = mysql_query($query, $conn);
$row = mysql_fetch_array($result);
$last_id = $row["SID"];
$id_letter = substr($last_id, 0, 1);
$id_num = substr($last_id, 1) + 1;
$id_num = str_pad($id_num, 3, "0", STR_PAD_LEFT);
$new_id = $id_letter . $id_num;
//Selecting locations
$query = "SELECT Loc_Code, Name FROM districts";
$result = mysql_query($query, $conn);
$count = mysql_num_rows($result);
?>
<?php
if(isset($_POST["savebtn"]))
{
//inserting the new service information
$id = $_POST["sid"];
$name = $_POST["name"];
$cost = $_POST["cost"];
if($_POST["active"] == "on") $active = 1; else $active = 0;
$query = "INSERT INTO taxi_services(SID, Name, Cost, Active) VALUES('$id', '$name', '$cost', '$active')";
$result = mysql_query($query, $conn);
//inserting the location details
for($j = 0; $j < $count; $j++)
{
$loc_id = $_POST["checkbox2"][$j];
$query = "INSERT INTO service_locations(SID, Loc_Code) VALUES('$id', '$loc_id')";
$result5 = mysql_query($query, $conn);
}
if (!$result || !$result5)
{
die("Error " . mysql_error());
}
else
{
?>
<script type="text/javascript">
alert("Record added successfully!");
</script>
<?php
}
mysql_close($conn);
}
?>
<div id="serv">
<b>Enter a new taxi service</b>
<br/><br/>
<form name="servForm" action="<?php $PHP_SELF; ?>" method="post" >
<table width="300" border="0">
<tr>
<td>Service ID</td>
<td><input type="text" name="sid" readonly="readonly" value="<?php echo $new_id; ?>" style="text-align:right" /></td>
</tr>
<tr>
<td>Name</td>
<td><input type="text" name="name" style="text-align:right" /></td>
</tr>
<tr>
<td>Cost</td>
<td><input type="text" name="cost" style="text-align:right" onkeypress="return isNumberKey(event)" /></td>
</tr>
<tr>
<td>Active</td>
<td><input type="checkbox" name="active" /></td>
</tr>
</table>
</div>
<div id="choseLoc">
Locations <br/><br/>
<table border="0">
<?php
$a = 0;
while($row = mysql_fetch_array($result))
{
if($a++ %5 == 0) echo "<tr>";
?>
<td align="center"><input type="checkbox" name="checkbox2[]" value="<?php echo $row['Loc_Code']; ?>" /></td>
<td style="text-align:left"><?php echo $row["Name"]; ?></td>
<?php
if($a %5 == 0) echo "</tr>";
}
?>
</table>
</div>
<br/>
<div id="buttons">
<input type="reset" value="Clear" /> <input type="submit" value="Save" name="savebtn" />
</form>
</div>
</body>
</html>
It inserts the Service details correctly. But when it inserts location data, a problem like this occurs,
I selected 4 checkboxes and saved. The 4 location codes gets saved along with the service ID. But as you can see from the screenshot above, a bunch of empty rows gets inserted too.
My question is how can I stop this from happening? How can I insert the data from the checkboxes only I select?
Thank you.
One way would be to only loop over the checkboxes that were submitted:
//inserting the location details
foreach($_POST["checkbox2"] as $loc_id)
{
$query = "INSERT INTO service_locations(SID, Loc_Code) VALUES('$id', '$loc_id')";
$result5 = mysql_query($query, $conn);
}
I reiterate here the SQL injection warning given above: you would be much better off preparing an INSERT statement and then executing it with parameters. Using PDO, it would look something like:
//inserting the location details
$stmt = $dbh->prepare('
INSERT INTO service_locations(SID, Loc_Code) VALUES(:id, :loc)
');
$stmt->bindValue(':id', $id);
$stmt->bindParam(':loc', $loc_id);
foreach($_POST["checkbox2"] as $loc_id) $stmt->execute();
from these sentence:
for($j = 0; $j < $count; $j++)
{
$loc_id = $_POST["checkbox2"][$j];
$query = "INSERT INTO service_locations(SID, Loc_Code) VALUES('$id', '$loc_id')";
$result5 = mysql_query($query, $conn);
}
i find the problem is that the value of loc_code must be the last loction you selected. because in this loop, the value of loc_code will replaced everytime. if you want to insert all the location, you should put it on the one sentence, like INSERT INTO service_locations(SID, Loc_Code) VALUES('$id', '$loc_id'), the value of $loc_id should be CO,GQ,GL.
This is happening because the checkboxes that weren't ticked still get posted, they just have empty values. Before you do your insert to service_locations just check if $loc_id is empty or not, only do the insert if it isn't.

Editing data from MySQL via PHP

I am running into a frustrating problem with a PHP script that's supposed to allow me to edit individual rows within my MySQL database.
This is the file where all of the rows from the database are displayed; it works just like it's supposed to.
<table cellpadding="10">
<tr>
<td>ID</td>
<td>First Name</td>
<td>Last Name</td>
<td>E-mail</td>
<td>Phone</td>
</tr>
<?php
$username="username here";
$password="password here";
$database="database name here";
mysql_connect(localhost,$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
$query="SELECT * FROM students";
$result=mysql_query($query);
mysql_close();
while ($row=mysql_fetch_array($result)){
echo ("<tr><td>$row[id]</td>");
echo ("<td>$row[first]</td>");
echo ("<td>$row[last]</td>");
echo ("<td>$row[email]</td>");
echo ("<td>$row[phone]</td>");
echo ("<td>Edit</td></tr>");
}
echo "</table>";
?>
As you can see, each row has an "Edit" link that is supposed to allow the user to edit that individual student's data. Here, then, is StudentEdit.php:
<?php
$username="username";
$password="password";
$database="database";
mysql_connect(localhost,$username,$password);
$student_id = $_GET[id];
$query = "SELECT * FROM students WHERE id = '$student_id'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
mysql_close();
?>
<form method="post" action="EditStudentData.php" />
<table>
<tr>
<td><input type="hidden" name="id" value="<? echo "$row[id]" ?>"></td>
</tr>
<tr>
<td>First Name:</td>
<td><input type="text" name="first" value="<? echo "$row[first]" ?>"></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input type="text" name="last" value="<? echo "$row[last]" ?>"></td>
</tr>
<tr>
<td>Phone Number:</td>
<td><input type="text" name="phone" value="<? echo "$row[phone]" ?>"></td>
</tr>
<tr>
<td>E-mail:</td>
<td><input type="text" name="email" value="<?echo "$row[email]" ?>"></td>
</tr>
</table>
</form>
When I execute this, however, I get the following error message:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home4/lukaspl1/public_html/StudentEdit.php on line 12
Any ideas what's wrong, and how to fix it?
Thank you in advance!
Remove the mysql_close from here
mysql_connect(localhost,$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
$query="SELECT * FROM students";
$result=mysql_query($query);
mysql_close();
The code should mysql_connect(localhost,$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
$query="SELECT * FROM students";
$result=mysql_query($query);
And moreover,you are going to use only key based resultset.. simply have mysql_fetch_assoc.
And another suggestion would be instead of $row[id]..replace it with $row['id'].
StudentEdit.php: you forgot to call #mysql_select_db($database) or die( "Unable to select database"); before you executed the query
This part of the code is wrong:
$student_id = $_GET[id];
the correct code is
$student_id = $_GET['id'];
code from expertsnote.com
Try...
echo ("<td>Edit</td></tr>");
instead of
echo ("<td>Edit</td></tr>");
this code was missing
$select_db = mysql_select_db("$db_name");
if (!$select_db) {echo "Error Selecting Database";}
this is the cod for edit the details dynamically
<?php
include('db.php');
$id=$_REQUEST['id'];
$query="SELECT * FROM `camera details` WHERE id='".$id."'";
$result=mysqli_query($db,$query) or die(mysqli_error());
$row1=mysqli_fetch_assoc($result);
if(isset($_POST['submit'])&&(isset($_POST['new'])&&($_POST['new'])==1))
{
$id=$_REQUEST['id'];
foreach($_POST as $key=>$values)
{
if($key!="submit"){
$names[]=$key;
$val[]= "'".$values."'";
if($key!="new"){
$k[] = "`".$key."` = '".$values."'";
}
}
}
$output=implode(",",(array)($k));
//$v=implode(",",(array)($val));
// `name` = 'san'
$query="UPDATE `camera details` SET $output WHERE id='".$id."'";
$output=mysqli_query($db,$query) or die(mysqli_error($db));
if($output)
{
header('location:cameralist.php');
}
}
else{
?>
I recommend doing this in studentEdit.php
$student_id = mysql_real_escape_string($_GET[id]);
$query = "SELECT * FROM students WHERE id = '$student_id'";
$result = mysql_query($query) or die(mysql_error() . ' ' . $query);
$row = mysql_fetch_array($result);
mysql_close();
Two things I've changed here is firstly to escape the data being passed in the url and secondly I've added or die(mysql_error() . ' ' . $query); If something is going wrong in the sql statement you should now see the error and hopefully you'll be able to fix it from there.
What looks incorrect to me is the way you are displaying the value retrieved from the database:
<input type="hidden" name="id" value="<? echo "$row[id]" ?>">
It should be
<input type="hidden" name="id" value="<?php echo $row['id']; ?>">
This code gives the option to add, search, edit and delete options. Thought it might to see all the options in one code.
$searchedUsername = "";
$searchedEmail = "";
//registration (Add) function
if ( isset($_POST['stdregister'])){
$username = $_POST['stdusername'];
$password = $_POST['stdpassword'];
$email = $_POST['stdemail'];
$hashedPassword = md5($password);
$connection = mysqli_connect("localhost","root","","std");
$query = "INSERT INTO student VALUES ('$username','$hashedPassword','$email')";
if ( mysqli_query($connection,$query) == 1 ){
echo "Successfully saved";
}
else{
echo "<p style='color: #f00;'>There is an error</p>";
}
mysqli_close($connection);
}
//delete function
if ( isset($_POST['stddelete'])){
$username = $_POST['stddelusername'];
$connection = mysqli_connect("localhost","root","","std");
$query = "DELETE FROM student WHERE username LIKE '$username'";
mysqli_query($connection,$query);
echo mysqli_error($connection);
mysqli_close($connection);
}
//update function
if ( isset($_POST['stdupdate'])){
$username = $_POST['stdusername'];
$stdpass = md5($_POST['stdpassword']);
$stdemail = $_POST['stdemail'];
$connection = mysqli_connect("localhost","root","","std");
$query = "UPDATE student SET password='$stdpass', email='$stdemail' WHERE username LIKE '$username'";
mysqli_query($connection,$query);
echo mysqli_error($connection);
mysqli_close($connection);
}
if ( isset($_POST['stdsearch']) ){
$searchUsername = $_POST['stdeditusername'];
$connection = mysqli_connect("localhost","root","","std");
$query = "SELECT * FROM student WHERE username LIKE '$searchUsername' ";
$result = mysqli_query($connection, $query);
while( $row = mysqli_fetch_array($result) ){
$searchedUsername = $row['username'];
$searchedEmail = $row['email'];
}
}
?>
<html>
<head>
</head>
<body>
<h1>Student Registration</h1>
<form name="stdregistration" action="forms.php" method="post">
<label>Username :</label>
<input name="stdusername" required="required" type="text" /><br /><br />
<label>Password :</label>
<input name="stdpassword" type="password" /><br /><br />
<label>E-mail :</label>
<input name="stdemail" type="email" /><br /><br />
<input name="stdregister" type="submit" value="Save" />
</form>
<h2>Delete Students</h2>
<form name="stddeletion" action="forms.php" method="post">
<label>Select the Username :</label>
<select name="stddelusername" required>
<option value="">Select One</option>
<?php
$connection2 = mysqli_connect("localhost","root","","std");
$query2 = "SELECT username FROM student";
$result = mysqli_query($connection2,$query2);
while( $row = mysqli_fetch_array($result) ){
echo "<option value='".$row['username']."'>".$row['username']."</option>";
}
mysqli_close($connection2);
?>
</select>
<input name="stddelete" type="submit" value="Delete" />
</form>
<h2>Edit Students</h2>
<form name="stdedition" action="forms.php" method="post">
<label>Select the Username :</label>
<select name="stdeditusername" required>
<option value="">Select One</option>
<?php
$connection2 = mysqli_connect("localhost","root","","std");
$query2 = "SELECT username FROM student";
$result = mysqli_query($connection2,$query2);
while( $row = mysqli_fetch_array($result) ){
echo "<option value='".$row['username']."'>".$row['username']."</option>";
}
mysqli_close($connection2);
?>
</select>
<input name="stdsearch" type="submit" value="Search" />
</form>
<form name="stdedit" action="forms.php" method="post">
<label>Username :</label>
<input name="stdusername" required="required" type="text" readonly value="<?php echo $searchedUsername; ?>" /><br /><br />
<label>Password :</label>
<input name="stdpassword" type="password" /><br /><br />
<label>E-mail :</label>
<input name="stdemail" type="email" value="<?php echo $searchedEmail; ?>" /><br /><br />
<input name="stdupdate" type="submit" value="Update" />
</form>
</body>
</html>

Categories