How can i insert html table data into sql database using php? - php

This is my table html code. I tried sending the data using the normal insert but it only sends the last row data. I don't know how to send the full data . Can someone please help me with this.
<form action="admin_schedule_employee.php" id="schedule_employee" method="post" >
<input type="date" class="input-sm" name="scheduledate" style="margin:10px;">
<table class="table-responsive table table striped table-bordered">
<thead>
<tr>
<th style="width:20%">Employee First Name</th>
<th style="width:20%">Employee ID</th>
<th style="width:20%">Start Time</th>
<th style="width:20%">End Time</th>
</tr>
<?php while($row = mysqli_fetch_array($search_result)): ?>
<tr>
<td><input disabled name="employeename" type="text" value="<?php echo $row['fname']; ?>"></input></td>
<td><input disabled name="employeeid" type="number" value="<?php echo $row['employee_id']; ?>"></input></td>
<td><input name="starttime" type="time"></td>
<td><input name="endtime" type="time"></td>
</tr>
<?php endwhile; ?>
</thead>
<tbody>
</tbody>
</table>
<input type="submit" name="Schedule" value="Schedule">
</form>[This is how my table look like i want to send the whole data to sql database using php][1]

To start with, you will need to create multiple pages:
form.php
process.php
done.php
Creating your user form is simple, place the table in form tags like you have done above, here is an example. Save this page as form.php
<form id="new record" action="process.php" method="POST">
<table width="500px">
<tr>
<td width="50%">
<input type="text" name="fname" id="fname">
</td>
<td width="50%">
<input type="text" name="lname" id="lname">
</td>
</tr>
<tr>
<td width="50%">
</td>
<td width="50%">
<input type="submit" value="Add Record">
</td>
</tr>
</table>
</form>
Next, you will need to create a page which can process this data, and add it to your mysql database. For the following example, I have omitted my database details and substituted them, but you should add your own.
For this example, imagine my database has a table with only an fname and an lname column.
<meta http-equiv="refresh" content="0; url=/done.php" />
<?php
$servername = "your_server_name";
$username = "mysql_username";
$password = 'mysql_password';
$dbname = "database_name";
$fname = $_GET['fname'];
$lname = $_GET['lname'];
try {
$conn = new PDO("mysql:host=$servername; dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO online (fname, lname)
VALUES ('$fname', '$lname')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record inserted";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
Hopefully, that will work to insert the record. Now we need a table on the done.php page which can display all the records in the database. Use the following code:
<html lang="en">
<head>
<meta http-equiv="refresh" content="5; url=/done.php" />
<meta charset="utf-8" />
<title></title>
</head>
<body>
<?php
$servername = "your_server_name";
$username = "mysql_username";
$password = 'mysql_password';
$dbname = "database_name";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * from table_name";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo $row["fname"]. ": ";
echo $row["lname"]. "<br /><br />";
}
} else {
echo "No messages";
}
mysqli_close($conn);
?>
</body>
</html>
Hopefully this will work for you.

Related

PHP form submission for multiple entry

How can I keep the current form with clear fields after successful insertion. I have used to php files, one for connecting the database and another for collecting data from user. Both of the files code are given below:
For connecting database:
<?php
$servername = "localhost";
$username = "local";
$password = "host";
$dbname = "form";
$conn = mysqli_connect($servername,$username,$password,$dbname);
if(!$conn){
die("Connection failed: ".mysqli_connect_error());
}
$roll=$_POST['roll'];
$name=$_POST['name'];
$city=$_POST['city'];
$sql = "insert into people_info (roll,name,city) values ('$roll','$name','$city')";
if(mysqli_query($conn,$sql)){
echo "New record created successflly";
}
else{
echo "Error: ".$sql."<br>".mysqli_error($conn);
}
mysqli_close($conn);
?>
And the form page is:
<html>
<body>
<form action="connection.php" method="post">
<table border="1">
<tr>
<th>
Field
</th>
<th>
Value
</th>
</tr>
<tr>
<td>
Roll:
</td>
<td>
<input type="text" name="roll"/><br>
</td>
</tr>
<tr>
<td>
Name:
</td>
<td>
<input type="text" name="name"/><br>
</td>
</tr>
<tr>
<td>
City:
</td>
<td>
<input type="text" name="city"/><br>
</td>
</tr>
<tr>
<td>
<input type="submit"/>
</td>
</tr>
</table>
</form>
</body>
</html>
Instead of this:
if(mysqli_query($conn,$sql)){
echo "New record created successfully";
}
else{
echo "Error: ".$sql."<br>".mysqli_error($conn);
}
try
if(mysqli_query($conn,$sql)){
header('location: page1.php?message=New record created successfully');
}
else{
header('location: page1.php?message=' . mysqli_error($conn));
}
here header() function will redirect you to form page with $message variable having response message. Use it to show the response on page.

search page not displaying any results

please assist
I have created a search page to query the database, when the submit button is selected, no data is populated into the grid and there is no error message or notice that gives me an indication of where the issue is. Please assist.
Here is the code:
<?php
if(isset($_POST['submit']))
{
$txtLastName = $_POST['txtLastName'];
$txtidnumber = $_POST['txtidnumber'];
$txtMedicalAidNumber = $_POST['txtMedicalAidNumber'];
//connect to the database
$db = mysql_connect
("server", "username", "password") or die ('I cannot connect to the database because: ' . mysql_error());
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$mydb = mysql_select_db("mediouqp_login");
if($txtLastName != '' && $txtidnumber != '' && $txtMedicalAidNumber != '')
{
$sql = "SELECT last_name, id_number, medical_id_number FROM patient WHERE last_name LIKE '%" . $txtLastName . "%' OR id_number LIKE '%" . $txtidnumber ."%'";
}
else
{
$sql = "SELECT last_name FROM patient ORDER BY last_name DESC";
}
$result = mysql_query($sql);
}
if($result)
{
if(mysql_num_rows($result) > 0)
{
echo 'Total records found are- '.mysql_num_rows($result);
}
else
{
echo "No records found.";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style2.css">
</head>
<body>
<ul>
<li>PATIENT DETAILS
<li>REPORTS</li>
<li>ADMINISTRATOR</li>
<li>DOWNLOADS</li>
</ul>
<div class="headerTitle">
<h1 id="mainHeader">search patient details</h1>
</div>
<form action="search_patient.php" method="post" name="frm_search" id="frm_search">
<table>
<tr>
<td class="Label" id="lname">Last Name
</td>
<td class="Field">
<input type ="lastname" name ="txtLastName" ></input>
<span id="spnLastName"></span>
</td>
</tr>
<tr>
<td class="Label" id="lname">ID Number
</td>
<td class="Field">
<input type ="lastname" name ="txtidnumber" ></input>
<span id="spnIdNumber"></span>
</td>
</tr>
<tr>
<td class="Label" id="lname">Medical Aid Number
</td>
<td class="Field">
<input type ="medicalaidnumber" name ="txtMedicalAidNumber" ></input>
<span id="spnMedicalaidNumber"></span>
</td>
</tr>
<tr>
<td class="Label">
</td>
<td>
<input type="submit" id="btnSearchPatient" value="Submit"></input>
<input type = "button" onClick="window.location='create_patient.php';" value="Create Patient" /></input>
</td>
</tr>
</table>
</form>
<br/>
<br/>
<table id="tblpatient" class="Grid">
<tr class="Header">
<td> </td>
<td> </td>
<td> </td>
<td>Last Name</td>
<td>ID Number</td>
<td>Medical Aid</td>
</tr>
<?php
if($result)
{
while($row = mysql_fetch_array($result))
{
$last_name = $row['last_name'];
$id_number = $row['id_number'];
$medical_id_number = 0;//$row['medical_id_number'];
?>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td><?php echo $last_name;?></td>
<td><?php echo $id_number;?></td>
<td><?php echo $medical_id_number;?></td>
</tr>
<?php
}
}
?>
</table>
</body>
</html>
Note: This extension(mysql) was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used along with prepared statements.
As per the code you have written it will be submitting the data but what you have written under this statement will never Work.
if(isset($_POST['submit'])){// Codes Inside this}
Reason this code will not work
Your Submit button is not having the name which you have given in the isset($_POST['submit']).
You mist add the name to the submit button which you have in your code.
Replace your Submit button as i have provided by adding the name to it and changing the button code style.
Replace:
<input type="submit" id="btnSearchPatient" value="Submit"></input>
With:
<input type="submit" id="btnSearchPatient" name="submit" value="Submit" />
After all the above steps that has been provided ensure the note below in order the data comes as not expected.
Note: If you need to execute the statement perfect you first put echo to the select statement that you have coded and break the execution over there. You will find the SQL statement over to the browser and you copy that echoed statement into the SQL section of the DB created in the Phpmyadmin and check whether your code executed well. If so you got the required output that you can remove the echo and exit statement and you can proceed.

Failing to update the new data entered by administrator

Look like everything is working fine with this code but in fact fails to update the database, Data are displayed correctly while fetching data but when i press update Button the data disappear but no update has been executed. It look fine to me but seems i am wrong.
This is a project for my professor so i don't care for the SQL injection and others.
<html>
<head>
<link rel="stylesheet" type="text/css" href="btnstyle.css">
<title>Managament System</title>
</head>
<body>
<h1>TU Chemnitz Student managament system</h1>
<br>
ADD Person
Edit Person
Manage Boards
Manage Departments
Search N&S
Triple Search
Membership
<br>
<br>
<?php
// set database server access variables:
$host = "localhost";
$user = "";
$pass = "";
$db = "";
// open connection
$connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!");
// select database
mysql_select_db($db) or die ("Unable to select database!");
// create query
$querys = "SELECT * FROM tblperson";
// execute query
$result = mysql_query($querys) or die ("Error in query: $query. ".mysql_error());
echo "<table border=1 align=center>
<tr>
<th>Personal ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Deparment</th>
<th>Board</th>
<th>Marticulation Number</th>
<th>Reg Date</th>
<th>Action</th>
</tr>";
while($row = mysql_fetch_array($result)) {
?>
<?php
echo '<tr>';
echo '<td>'. $row['personid'].'</td>';
echo '<td>'. $row['personname'].'</td>';
echo '<td>'. $row['personsurname'].'</td>';
echo '<td>'. $row['persondepartment'].'</td>';
echo '<td>'. $row['personboard'].'</td>';
echo '<td>'. $row['martinumber'].'</td>';
echo '<td>'. $row['personregdate'].'</td>';
echo '<td>'.' EDIT '.'</td>';
}
?>
</body>
</html>
and this is the edit file which seems to problematic.
<?php
include_once('coneksioni.php');
if(isset($_GET['edit']))
{
$personid = $_GET['edit'];
$res = mysql_query("SELECT * FROM tblperson WHERE personid='$personid'");
$row = mysql_fetch_array($res);
}
if(isset($_POST['newpersonname']))
{
$newpersonname = $_POST['newpersonname'];
$personid = $_POST['personid'];
$sql = "UPDATE tblperson SET personname = '$newpersonname' WHERE personid = '$personid'";
$res = mysql_query($sql) or die ("Cant be updated");
echo "< meta http-equiv='refresh' content='0;url=home.php'>";
}
?>
<form action="edit20.php" method="POST">
<table border="0">
<tr>
<td>First Name</td>
<td><input type="text" name="newpersonname" value="<?php echo $row[1];?>" maxlength="30" size="13"></td>
</tr>
<tr>
<td>Last Name</td>
<td> <input type="text" name="personsurname" value="<?php echo $row[2];?>" maxlength="30" size="30"></td>
</tr>
<tr>
<td>Department</td>
<td>
<select name='persondepartment'>
<option>Production</option>
<option>Sales</option>
</select>
</td>
</tr>
<tr>
<td>Board</td>
<td>
<select name='personboard'>
<option>Evaluation</option>
<option>Executive</option>
<option>Research</option>
</select>
</td>
</tr>
<tr>
<td>Marticulation Number</td>
<td> <input type="text" name="martinumber" maxlength="60" size="30"></td>
</tr>
<tr>
<td>Date of Registration</td>
<td><input type="date" name="personregdate" maxlength="7" size="7"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value=" Update"></td>
</tr>
</table>
</form>
You are looking for personid when the Update button is pressed on the form in edit20.php but that value has never been set so it will be empty and the update will fail.
After
<form action="edit20.php" method="POST">
add:
<input type="hidden" name="personid" value="<?php echo $personid; ?>">
On edit page seem your confusing the same variable with different values. If you state $personid variable to contain the edit value from get, then just re-use the variable don't assign new value. On this line you assign new value :
$personid = $_POST['personid'];
Don't assign new value since it has the initial value already to use just set the variable global for usage
$personid = $_GET['edit'];
Or else create a hidden element and pass edit value into it.
Please add name attribute for your update button
<td colspan="2"><input type="submit" name="update" value=" Update"></td>
and chk whether the update button set or reset as in the place of
if(isset($_POST['newpersonname'])) // change text 'newpersonname' as 'update'
You use a variable that doesn't excist:
<?php
include_once('coneksioni.php');
if(isset($_GET['edit']))
{
$personid = $_GET['edit'];
$res = mysql_query("SELECT * FROM tblperson WHERE personid='$personid'");
$row = mysql_fetch_array($res);
}
if(isset($_POST['newpersonname']))
{
$newpersonname = $_POST['newpersonname'];
$personid = $_POST['personid']; // this doesn't excist
$sql = "UPDATE tblperson SET personname = '$newpersonname' WHERE personid = '$personid'";
$res = mysql_query($sql) or die ("Cant be updated");
echo "< meta http-equiv='refresh' content='0;url=home.php'>";
}
?>
$personid = $_POST['personid']; doesn't excist in your code. Its simply a piece of code you put in there to probably proces, but forgot to define the variable in the code. Place the following in your form.
<input type="hidden" name="personid" value="<?php echo $_GET['edit']; ?>">
You only use this just once because you send the form back after proces to your home, hence it wont be used anymore. You can also use the avariable you defined as $personid; on that position.
If that fails, something maybe wrong in your query. Try to echo out the query (remove qucikly the meta command) by simply just do echo $sql after you do the sql query. 9 out of 10 times, it's a typo.

My script is updating all fields when I just edit one

my problem it's I'm trying to develop a back-end where I need to update but my problem is, when I update one field my script update all fields and all data of my mysqli database.
My code for now is:
<html>
<body>
<?php
ini_set('display_errors', 1);
error_reporting(~0);
$serverName = "localhost";
$userName = "root";
$userPassword = "";
$dbName = "hotel_vaniet";
$strCustomerID = null;
if(isset($_GET["cod"]))
{
$cod = $_GET["cod"];
}
$serverName = "localhost";
$userName = "root";
$userPassword = "";
$dbName = "hotel_vaniet";
$conn = mysqli_connect($serverName,$userName,$userPassword,$dbName);
$sql = "SELECT * FROM quartos WHERE cod=$cod";
$query = mysqli_query($conn,$sql);
$result=mysqli_fetch_array($query,MYSQLI_ASSOC);
?>
<div id="main">
<form action="editar_quartos_final.php" name="frmAdd" method="post">
<br><h1>Página de Edição</h1>
<br><hr/>
<div id="login2">
<table width="284" border="1">
<tr>
<th width="120">Tipo</th>
<td width="238"><input type="text" name="tipo" size="50" value="<?php echo $result["tipo"];?>"></td>
</tr>
<tr>
<th width="120">Capacidade</th>
<td><input type="text" name="capacidade" size="50" value="<?php echo $result["capacidade"];?>"></td>
</tr>
<tr>
<th width="120">Preço p/ Noite</th>
<td><input type="text" name="preco" size="50" value="<?php echo $result["preco"];?>"></td>
</tr>
<tr>
<th width="120">Reservado</th>
<td><input type="text" name="reservado" size="50" value="<?php echo $result["reservado"];?>"></td>
</tr>
</table>
<br><input id="submitbuttoneditar" type="submit" value=" Editar " name="submit"/><br />
</div>
</form>
<?php
mysqli_close($conn);
?>
</body>
</html>
This the first page ,this page send me to another where makes all changes. The second page :
<html>
<head>
<title>Página de Edição do Cliente</title>
</head>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "hotel_vaniet";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE quartos SET
tipo = '".$_POST["tipo"]."' ,
capacidade = '".$_POST["capacidade"]."' ,
preco = '".$_POST["preco"]."' ,
reservado = '".$_POST["reservado"]."'
WHERE cod=cod";
if ($conn->query($sql) === TRUE) {
echo "Dados actualizados com sucesso!";
header("Location: quartos.php");
} else {
echo "Erro na edição dos dados! " . $conn->error;
header("Location: quartos.php");
}
$conn->close();
?>
</body>
</html>
On your first page you have $cod variable which equals $_GET["cod"].
On your second page $cod variable is not defined. So your try to update
WHERE cod=cod
means - update where value of field cod is the same as value of field cod. And as it is true for all records - all your records are updated.
So, the solution is to pass your $cod value to your second script.
For example, you can do it with a hidden field from your first form:
<form action="editar_quartos_final.php" name="frmAdd" method="post">
<br><h1>Página de Edição</h1>
<br><hr/>
<input type="hidden" name="cod" value="<?php echo $cod?>" />
<div id="login2">
<table width="284" border="1">
<tr>
<th width="120">Tipo</th>
<td width="238"><input type="text" name="tipo" size="50" value="<?php echo $result["tipo"];?>"></td>
</tr>
<tr>
See this field with hidden type?
And in your second script use $_POST['cod']:
$sql = "UPDATE quartos SET
tipo = '".$_POST["tipo"]."' ,
capacidade = '".$_POST["capacidade"]."' ,
preco = '".$_POST["preco"]."' ,
reservado = '".$_POST["reservado"]."'
WHERE cod=" . $POST['cod'];
And of course, your code is vulnerable to sql injections.
So you should start using prepared statements asap.

SQL form run from include not working in firefox/safari

**
This is the code for one of several forms saved as php includes for use on the same admin page. They work individually in all browsers but do not work in safari or firefox from the admin page. Any Thoughts?
Thanks for your help!
(I know I need to switch over to prepared statements) **
<?php
$servername = "1.1.1.1:111";
$username = "root";
$password = "root";
$dbname = "sit";
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$result = mysqli_query($conn, "SELECT * FROM `calltoaction` ");
$values = mysqli_fetch_array($result);
$calltoaction_title = $_POST['calltoaction_title'];
$calltoaction_content = $_POST['calltoaction_content'];
if(isset($_POST['calltoaction_title'])){
$calltoaction= "UPDATE calltoaction SET calltoaction_title='$calltoaction_title' ,calltoaction_content='$calltoaction_content' WHERE calltoaction_id='1'";
if (mysqli_query($conn, $calltoaction)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
}
?>
<form id="comment_form" method="post" action="<?php $calltoaction?>" onsubmit="setTimeout(function () { window.location.reload(); }, 10), location.reload(true);">
<table width="100%" border="0" cellspacing="1" cellpadding="2">
<tr>
<td width="85%">About Us Title</td>
</tr>
<tr>
<td><input class="commentarea" name="calltoaction_title" type="text" id="calltoaction_title"value="<?php echo $values['calltoaction_title']?>"></td>
</tr>
<tr>
<td width="85%" >Testimonial</td>
</tr>
<tr>
<td width="85%" >About Us Content</td>
</tr>
<tr>
<td><pre><textarea class="commentarea" name="calltoaction_content" type="text" id="calltoaction_content" rows= "10" ><?php echo $values['calltoaction_content']?></textarea></pre></td>
</tr>
<tr>
<td>
<input type="submit" value="Update">
</td>
</tr>
</table>
</form>
<?php mysqli_close($conn); ?>

Categories