Values not inserting in database (Issue might be with foreign key) - php

I have added a foreign key in a table. Now, when I try to insert data from my form into the database, it doesn't work. I think the issue might be with the foreign key called 'register_id'. How can this issue be solved?
My code:
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password) or die("cannot connect to database");
$selected = mysql_select_db("audit", $dbhandle);
$strQuery = 'SELECT * FROM schedule';
$retval = mysql_query($strQuery, $dbhandle);
if (!$retval) {
die('Could not get data: ' . mysql_error());
}
//insert code
if (isset($_POST['schedule'])) {
//$id = ($_POST['id']);
$_SESSION['company_session'] = $_POST['company_name'];
$_SESSION['auditor_session'] = $_POST['auditor_name'];
$_SESSION['date_session'] = $_POST['audit_date'];
$_SESSION['time_session'] = $_POST['audit_time'];
$_SESSION['status_session'] = $_POST['audit_status'];
$company_session = $_SESSION['company_session'];
$auditor_session = $_SESSION['auditor_session'];
$date_session = $_POST['audit_date'];
$time_session = $_POST['audit_time'];
$status_session = $_SESSION['status_session'];
mysql_query("INSERT INTO schedule (company_name,auditor_name,audit_date,audit_time,audit_status) VALUES ('$company_session','$auditor_session','$date_session','$time_session','$status_session')");
//echo ("New Process Created successfully");
header('Location: ?');
}
?>
//html code
<div class="form-group"><br>
<table class="table">
<tr><input class="form-control" type="hidden" name="id"></tr>
<tr><input class="form-control" type="hidden" name="register_id"></tr>
<?php
$connect = mysql_connect("localhost", "root", "") or die("Could not connect to the database");
mysql_select_db("audit") or die("could not find db");
$query = mysql_query("SELECT fullname FROM register WHERE register_id ='" . $_SESSION['register_id'] . "'");
$numrows = mysql_num_rows($query);
if ($numrows != 0) {
$row = mysql_fetch_assoc($query);
$name = $row['fullname'];
}
?>
<tr>
<td><label>Company Name:</label></td>
<td><input class="form-control" type="text" name="company_name" required="true"></td>
<td><label>Assigned Auditor:</label></td>
<?php echo "<td><input class='form-control' name='auditor_name' value='$name' required='true'/></td>" ?>
</tr>
<tr>
<td><label>Scheduled Date:</label></td>
<td><input class="form-control" type="date" name="audit_date" min="2000-01-02" required="true"></td>
<td><label>Scheduled Time:</label></td>
<td><input class="form-control" type="time" name="audit_time" required="true"></td>
</tr>
<tr>
<td><label>Status:</label></td>
<td><input class="form-control" type="text" name="audit_status" value="Not started" required="true"></td>
<td></td>
<td><button class="btn btn-primary" type="submit" name="schedule" value="submit">Schedule</button> <input class="btn btn-primary" type='submit' value='Update' name='update' /> <input class="btn btn-primary" type='submit' value='Delete' name='delete' /> <input class="btn btn-primary" type='submit' value='Reset' name='reset' /></td>
</tr>
</div>
</table>
</div>
</form>

Related

Why are values from a url are not being passed to sticky form

I have created a php sticky form so data will not disappear when the submit button is clicked. A url link is being used to pass values to a form so they can be edited. However, the values from the url are not being passed into the form fields. Why are the values from the url not being passed into the form fields? Thank you so much for your time.
This is the code:
index.php
<?php
require_once('authorize.php');
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
require_once('appvars.php');
require_once('connectvars.php');
$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$data = mysqli_query($conn, $query);
echo '<table>';
echo '<tr><th>Name</th><th>Caption</th><th>Action</th></tr>';
while ($row = mysqli_fetch_array($data)) {
//link
echo '<td><a href="link.php?id=' . $row['id'] . '&image=' . $row['image1'] . '&name=' . $row['name'] .
'&caption=' . $row['caption'] .
'&video=' . $row['video'] . '">Edit </a>';
echo '</td></tr>';
}
echo '</table>';
echo "<br><br>";
mysqli_close($conn);
?>
</body>
</html>
sticky_form.php
<!DOCTYPE html>
<html>
<head>
<title>Edit Conent</title>
</head>
<body>
<h3>Edit Conent</h3>
<?php
require_once('appvars.php');
require_once('connectvars.php');
$vid="";
$vname="";
$vcaption="";
$vvideo="";
$id ="";
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if(isset($_POST["button_edit"])){
$id = $_POST["id"];
$name = $_POST['name'];
$caption = $_POST['caption'];
$video = $_POST['video'];
$qry = mysqli_query($dbc,"Update table1 Set name='$name', caption='$caption', video='$video' Where id='$id'");
else if(isset($_GET["id"])){
$qry = mysqli_query($dbc,"Select * From table1 Where id='".$_GET["id"]."'");
while($row=mysqli_fetch_array($qry,MYSQLI_ASSOC)){
$vid=$row["id"];
$vname=$row["name"];
$vcaption=$row["caption"];
$vvideo=$row["video"];
}
}
?>
<body>
<form action='' method="post" enctype="multipart/form-data" >
<table>
<tr>
<td>ID</td>
<td><input type="text" name="id" value="<?php echo $vid;?>"></td></tr>
<tr>
<td>Name</td>
<td><input type="text" class="bigger_textbox" name="name" value="<?php if (isset($_POST['name'])) {echo htmlentities($_POST['name']);}?>"></td></tr>
<tr><td>Caption</td>
<td><input type="text" class="bigger_textbox" name="caption" value="<?php if (isset($_POST['caption'])) {echo htmlentities($_POST['caption']);}?>"></td></tr>
<tr><td>Video</td>
<td><input type="text" class="bigger_textbox" name="video" value="<?php if (isset($_POST['video'])) {echo htmlentities($_POST['video']);}?>"></td></tr>
<tr><td colspan="2">
<input type="submit" name="button_edit" value="Edit Content"></td></tr> </table>
</form>
<table border=1>
<tr><th>Name</th><th>Caption</th>
<th>Video</th> <th>Action</th></tr>
<?php
if (isset($_GET["id"])) {
$qry =mysqli_query($dbc, "Select * From table1 Where id='".$_GET["id"]."'");
while($row=mysqli_fetch_array($qry,MYSQLI_ASSOC)) {
echo '<tr><td>'.$row["name"].'</td>';
echo '<td>'.$row["caption"].'</td>';
echo '<td>'.$row["video"].'</td>';
echo '<td>Edit </td></tr>';
}
}
?>
</table>
</body>
</html>
Apparently you already have the values you need in stick_form.php:
else if(isset($_GET["id"])){
$qry = mysqli_query($dbc,"Select * From table1 Where id='".$_GET["id"]."'");
while($row=mysqli_fetch_array($qry,MYSQLI_ASSOC)){
$vid=$row["id"];
$vname=$row["name"];
$vcaption=$row["caption"];
$vvideo=$row["video"];
}
Try replacing this part of the code of stick_form.php:
<td><input type="text" class="bigger_textbox" name="name" value="<?php if (isset($_POST['name'])) {echo htmlentities($_POST['name']);}?>"></td></tr>
<tr><td>Caption</td>
<td><input type="text" class="bigger_textbox" name="caption" value="<?php if (isset($_POST['caption'])) {echo htmlentities($_POST['caption']);}?>"></td></tr>
<tr><td>Video</td>
<td><input type="text" class="bigger_textbox" name="video" value="<?php if (isset($_POST['video'])) {echo htmlentities($_POST['video']);}?>" </td></tr>
With:
<td><input type="text" class="bigger_textbox" name="name" value="<?php echo $vname; ?>"></td></tr>
<tr><td>Caption</td>
<td><input type="text" class="bigger_textbox" name="caption" value="<?php echo $vcaption; ?>"></td></tr>
<tr><td>Video</td>
<td><input type="text" class="bigger_textbox" name="video" value="<?php echo $vvideo; ?>"></td></tr>
Update
As you commented, after clicking the edit button, your form fields get empty. That's because you're not setting the correct variables in this part of your code:
if(isset($_POST["button_edit"])){
$id = $_POST["id"];
$name = $_POST['name'];
$caption = $_POST['caption'];
$video = $_POST['video'];
$qry = mysqli_query($dbc,"Update table1 Set name='$name', caption='$caption', video='$video' Where id='$id'");
Change it to:
if(isset($_POST["button_edit"])){
$vid = $_POST["id"];
$vname = $_POST['name'];
$vcaption = $_POST['caption'];
$vvideo = $_POST['video'];
$qry = mysqli_query($dbc,"Update table1 Set name='$vname', caption='$vcaption', video='$vvideo' Where id='$vid'");
Hope it helps.

Load data from MySQL database to HTML textboxes

I am still learning, can anyone help me, What wrong in my code?
I need to load when you click on the Load button program will search the database ID selected in the dropdown, and them bring the name .. etc and show it on textbox.
Sorry, for my English.
<?php
$servername = "localhost";
$username = "estgv15592";
$password = "estgv155922016";
$dbname = "estgv15592";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST["loadbtn"]))
{
$id = (integer) $_POST["id"];
$query = "SELECT NOME, MORADA, PRECO FROM FICHA_DE_OBRA WHERE ID_FICHAOBRA = '$id' ";
$result = mysqli_query($conn, $query);
$details = mysql_fetch_array($result);
$nome = $details["NOME"];
$morada = $details["MORADA"];
$preco = $details["PRECO"];
}
$sql = "SELECT * FROM FICHA_DE_OBRA";
$result = mysqli_query($conn, $sql);
echo '<form id="form" method="post">';
echo "<select name ='id'>";
echo "<option value=''>Selecione Número ficha Obra</option>";
while($row = mysqli_fetch_array($result))
{
echo "<option value='" . $row['ID_FICHAOBRA'] . "'>" . $row['ID_FICHAOBRA'] . "</option>";
}
echo "</select>";
$conn->close();
?>
<input type="submit" value="Load" name="loadbtn">
<table width="300" border="0">
<tr>
<td>Name</td>
<td><input type="text" name="upName" style="text-align:right" value="<?php echo $nome;?>"/></td>
</tr>
<tr>
<td>Cost</td>
<td><input type="text" name="upCost" style="text-align:right" value="<?php echo $morada;?>" /></td>
</tr>
<tr>
<td>Active</td>
<td><input type="text" name="upActive" style="text-align:right" value="<?php echo $preco;?>" /></td>
</tr>
</table>
</div>
<br/>
</form>
You are not using proper php tag: (e.g. <?php echo $preco;?>):
<tr>
<td>Name</td>
<td><input type="text" name="upName" style="text-align:right" value="<?php echo $nome; ?>"/></td>
</tr>
<tr>
<td>Cost</td>
<td><input type="text" name="upCost" style="text-align:right" value="<?php echo $morada; ?>" /></td>
</tr>
<tr>
<td>Active</td>
<td><input type="text" name="upActive" style="text-align:right" value="<?php echo $preco; ?>" /></td>
</tr>
Use mysqli_query and mysqli_fetch_array function and note that first argument in mysqli_query should be the connection object where you made the mistake:
$result = mysqli_query($conn, $query); // first PHP block
$result = mysqli_query($conn, $sql); // second PHP block
$details = mysqli_fetch_array($result); // first PHP block
$row = mysqli_fetch_array($result) // second PHP block
And move below lines to the top of your first PHP block, or $conn would be undefined in your first PHP block:
$servername = "localhost";
$username = "estgv15592";
$password = "your_password";
$dbname = "estgv15592";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
The problem is came from your connection to database you use mysqli in connection but you when call queries you use mysql.
This is the code
<?php
$servername = "localhost";
$username = "estgv15592";
$password = "********";
$dbname = "estgv15592";
$conn = mysql_connect($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST["loadbtn"]))
{
$id = intval($_POST["id"]);
$query = "SELECT NOME, MORADA, PRECO FROM FICHA_DE_OBRA WHERE ID_FICHAOBRA = '$id' ";
$result = mysql_query($query, $conn);
$details = mysql_fetch_array($result);
$nome = $details["NOME"];
$morada = $details["MORADA"];
$preco = $details["PRECO"];
}
?>
<?php
$sql = "SELECT * FROM FICHA_DE_OBRA";
$result = $conn->query($sql);
echo '<form id="form" method="post">';
echo "<select name ='id'>";
echo "<option value=''>Selecione Número ficha Obra</option>";
while($row = mysqli_fetch_array($result))
{
echo "<option value='" . $row['ID_FICHAOBRA'] . "'>" . $row['ID_FICHAOBRA'] . "</option>";
}
echo "</select>";
$conn->close();
?>
<input type="submit" value="Load" name="loadbtn">
<table width="300" border="0">
<tr>
<td>Name</td>
<td><input type="text" name="upName" style="text-align:right" value="<? echo $nome; ?>" /></td>
</tr>
<tr>
<td>Cost</td>
<td><input type="text" name="upCost" style="text-align:right" value="<? echo $morada; ?>" /></td>
</tr>
<tr>
<td>Active</td>
<td><input type="text" name="upActive" style="text-align:right" value="<? echo $preco; ?>" /></td>
</tr>
</table>
</div>
<br/>
</form>
</body>
</html>
</div>
this method you use to get data not secure. I advise you to learn pdo or prepared statement with mysqli

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

my php function cant run when i call it in submit form

I have a proble: I have a function in the html head, and then in the body I have a form type submit and run the function onsubmit. It seeems I cant reach the function or go to function to insert details to database. I cant complete this idea. Please help me this.
<?php
function sida() {
$host = "localhost";
$username = "root";
$password = "";
$databasename = "vinhcv_truonghoc";
$connect = mysql_connect($host, $username, $password);
$db = mysql_select_db($databasename);
if (isset($_POST['comment']) && isset($_POST['name'])) {
$comment = $_POST['comment'];
$name = $_POST['name'];
$q = "insert into comments values('', '$name', '$comment', CURRENT_TIMESTAMP)";
echo $q;
$insert = mysql_query($q);
if (!$insert) { echo mysql_error(); }
$id = mysql_insert_id($insert);
$select = mysql_query("select name, comment, post_time from comments where name = '$name' and comment='$comment' and id='$id'");
if ($row = mysql_fetch_array($select)) {
$name = $row['name'];
$comment = $row['comment'];
$time = $row['post_time'];
?>
<div class="comment_div">
<p class="name">Posted By:<?php echo $name;?></p>
<p class="comment"><?php echo $comment;?></p>
<p class="time"><?php echo $time;?></p>
</div>
<?php
}
exit;
}
}
?>
and the form in the body:
<form method="POST" onsubmit="sida()">
<textarea id="comment" placeholder="Write Your Comment Here....."></tetarea>
<br>
<input type="text" id="username" placeholder="Your Name">
<br>
<input type="submit" value="Post Comment">
</form>
<div id="all_comments">
<?php
$host = "localhost";
$username = "root";
$password = "";
$databasename = "vinhcv_truonghoc";
$connect = mysql_connect($host,$username,$password);
$db = mysql_select_db($databasename);
$comm = mysql_query("select name,comment,post_time from comments order by post_time desc");
while($row = mysql_fetch_array($comm))
{
$name = $row['name'];
$comment = $row['comment'];
$time = $row['post_time'];
?>
<div class="comment_div">
<p class="name">Posted By:<?php echo $name;?></p>
<p class="comment"><?php echo $comment;?></p>
<p class="time"><?php echo $time;?></p>
</div>
<?php
}
?>
</div>
In the body it can connect to database to get information, that mean not thing wrong when connect with database, so why it cant insert to database?
What you need to do is commented:-
<form method="POST" ><!-- remove onsubmit="sida()"-->
<textarea id="comment" placeholder="Write Your Comment Here....." name = "comment"></textarea><!-- add name attribute -->
<br>
<input type="text" id="username" placeholder="Your Name" name = "username"><!-- add name attribute -->
<br>
<input type="submit" value="Post Comment">
</form>
<div id="all_comments">
<?php
$data = array(); // define empty array
if(isset($_POST["comment"]) && isset($_POST["username"])){ // check with posted value not button value
$host="localhost";
$username="root";
$password="";
$databasename="vinhcv_truonghoc";
$i = 0; // DEFINE COUNTER
$connect=mysqli_connect($host,$username,$password,$databasename); // mysql_* is deprecated so use mysqli_* or PDO
if($connect){ // IF CONNECTION ESTABLISHED
$comment = mysqli_real_escape_string($connect,$_POST['comment']); // Prevent from SQL Injection
$username = mysqli_real_escape_string($connect,$_POST['username']); // Prevent from SQL Injection
$query = mysqli_query ($connect,"INSERT INTO comments (username,comment) VALUES ('".$username."','".$comment."')"); // check and change table name as well as column name
if($query){
echo "Inserted Successfully";
}else{
echo "Problem occur in insertion because of".mysqli_error($connect);
}
$comm = mysqli_query($connect,"select name,comment,post_time from comments order by post_time desc");
if($comm){ // IF QUERY EXECUTED
while($row=mysqli_fetch_array($comm)){
$data[$i]["name"] = $row['name']; // ASSIGN VALUES TO THE ARRAY
$data[$i]["comment"] = $row['comment'];
$data[$i]["time"] = $row['post_time'];
$i++;
}
}else{
echo "Query execution failed because of".mysqli_error($connect);
}
}else{
echo'connection problem because of'.mysqli_connect_error();
}
}else{
echo "All fields are need to fill properly";
}
?>
<?php foreach ($data as $dat){?> <!-- ITERATE THROUGH ARRAY -->
<div class="comment_div">
<p class="name">Posted By:<?php echo $data['name'];?></p>
<p class="comment"><?php echo $data['comment'];?></p>
<p class="time"><?php echo $data['time'];?></p>
</div>
<?php } ?>
</div>
Seems like you are not passing any parameters to the $_POST array. You need to pass the name attribute to your input fields. Since you are going to run a PHP server-side function you need to use the action attribute.
Like this:
<form method="POST" action="sida()">
<textarea name="comment" id="comment" placeholder="Write Your Comment Here....."></textarea>
<br>
<input name="name" type="text" id="username" placeholder="Your Name">
<br>
<input type="submit" value="Post Comment" name="submit">
</form>
$host="localhost";
$username="root";
$password="";
$databasename="vinhcv_truonghoc";
function connect() {
global $host,$username,$password,$databasename;
$con=mysql_connect($host,$username,$password) or die ("ConnectionFailed");
mysql_select_db($databasename,$con) or exit ("Failed to connect");
return $con; }
function iud($query) //Insert,Update,Delete {
$con=connect();
$result=mysql_query($query,$con);
$n=mysql_affected_rows($con);
mysql_close($con);
return $n; }
function select ($query) //Select {
$con=connect();
$result=mysql_query($query,$con);
mysql_close($con); return $result; }
if(isset($_REQUEST['submit'])) {
$name=$_REQUEST['name'];
$comment=$_REQUEST['comment'];
$query="INSERT INTO `comments`(`name`, `comment`, `post_time`)
VALUES('$name','$comment',CURRENT_TIMESTAMP)";
$n=iud($query);
echo $n; }
?>
<html> <head></head> <body> <form method="GET"> <table>
<tr> <td>Name</td> <td><Input type="text" name="name" id=""
class="" placeholder="Name.."></td> </tr>
<tr> <td>Comment</td> <td><textarea name="comment" rows="5" cols="40" placeholder="Comment
Here.."> </textarea></td> </tr>
<tr> <td></td> <td><Input type="submit" name="submit" id="" class="" value="submit">
</td> </tr>
</table> </form>
<!-- Showing Result --> <table> <?php $query="Select * from comments ORDER BY coid DESC"; //Coid Is A Primary Key
$result=select($query); $n=mysql_num_rows($result); if($n>0) {
while($data=mysql_fetch_array($result)) extract($data); } ?>
<tr> <td><?php echo #$name; ?></td> </tr> <tr> <td><?php
echo #$comment; ?></td> </tr> </table>
</body> </html>
I hope It will Work For you :)

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