Load data from MySQL database to HTML textboxes - php

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

Related

The checkbox's do not hold all value when I select more then one checked

I want insert employee attendance. when I checked more then one checkbox it take two checkbox value 1 and other checkbox value 0 .so how can i solve this please help me. this is my form code
<form action="coll.php" method="post" name="create_grading" id="create_grading">
<table width="30%" border="0" cellpadding="2" cellspacing="3" class="mainTable">
<tr>
<th><input type="checkbox" id="selectall" /></th>
<th>name</th>
</tr>
<?php
$sql = "select * from employee";
$query = mysqli_query($con, $sql);
while ($row = mysqli_fetch_array($query)) {
?>
<tr>
<td><input type="hidden" name="eid[]" value="<?php echo $row['eid']; ?>"/>
<input name="status[]" class="case" type="checkbox" value="1" /><input name="status[]" class="case" type="hidden" value="0" /></td>
<td align="center"><?php echo $row['employee_name'] ?></td>
</tr>
<?php }; ?>
<tr>
<td></td>
<td><input type="submit" name="Submit" id="Submit" value="Submit" /></td>
</tr>
</table>
</form>
this is my insert code
$host = "localhost";
$user = "root";
$pass = "";
$db = "multiple_row_insert";
$con = mysqli_connect($host, $user, $pass, $db);
if (isset($_POST['Submit'])) {
$eid = $_POST['eid'];
$count = count($eid);
for ($i = 0; $i < $count; $i++) {
$status = $_POST['status'][$i];
$eid2 = $_POST['eid'][$i];
$query = "INSERT INTO time(eid,status) VALUES ('$eid2','$status')";
$query = mysqli_query($con, $query);
}
}
if(isset($_POST['checkbox']))
//then is checked...
else
//is not checked
So basically you only need 1 checkbox, you can change the name of your inputs. And then in your backend use something like:
$_POST['status_'.$i]
On each case and detect if its checked with the "isset" for this $_POST.
Edited:
Your code should look something like this (not tested, sorry if there is any syntax error, you can fix them anyways):
$host = "localhost";
$user = "root";
$pass = "";
$db = "multiple_row_insert";
$con = mysqli_connect($host, $user, $pass, $db);
if (isset($_POST['Submit'])) {
$eid = $_POST['eid'];
$count = count($eid);
for ($i = 0; $i < $count; $i++) {
$status = 0;
if(isset($_POST['status_'.$i])) //check if checkbox is setted (value 1 / checked)
$status = 1;
$eid2 = $_POST['eid'][$i];
$query = "INSERT INTO time(eid,status) VALUES ('$eid2','$status')";
$query = mysqli_query($con, $query);
}
}
And your frontend code:
<form action="coll.php" method="post" name="create_grading" id="create_grading">
<table width="30%" border="0" cellpadding="2" cellspacing="3" class="mainTable">
<tr>
<th><input type="checkbox" id="selectall" /></th>
<th>name</th>
</tr>
<?php
$sql = "select * from employee";
$query = mysqli_query($con, $sql);
$i = 0;
while ($row = mysqli_fetch_array($query)) {
?>
<tr>
<td><input type="hidden" name="eid[]" value="<?php echo $row['eid']; ?>"/>
<input name="status_<?php echo $i; ?>" class="case" type="checkbox" value="0" /></td>
<td align="center"><?php echo $row['employee_name']; ?></td>
</tr>
<?php $i++; } ?>
<tr>
<td></td>
<td><input type="submit" name="Submit" id="Submit" value="Submit" /></td>
</tr>
</table>
</form>

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.

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

PHP form : not updating mysql database

I have virtually no programming experience and trying this first project, I am a bit stuck on how to update the database, so I click on edit and the correct record gets loaded into the edit screen update.php
When I click update, I get the message from updated.php saying that the database has been updated, but the database does not get updated, when I display the records they are the same as before the update, thanks in advance for all your help.
the following code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Form Edit Data</title>
</head>
<body>
<table border=1>
<tr>
<td align=center>Form Edit Employees Data</td>
</tr>
<tr>
<td>
<table>
<?
$user_name = "";
$password = "";
$database = "";
$server = "localhost";
mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database);
$id = $_GET['id'];
$order = "SELECT * FROM MY_ID where ID = ' " .$id . " ' ";
$result = mysql_query($order);
$row = mysql_fetch_array($result);
?>
<form method="post" action="edit_data.php"?id=<?= $id ?>>
<input type="text" name="id" value="<? echo "$row[ID]"?>">
<tr>
<td>First Name</td>
<td>
<input type="text" name="FirsName" size="20" value="<? echo "$row[FirstName]"?>">
</td>
</tr>
<tr>
<td>Sur Name</td>
<td>
<input type="text" name="SurName" size="40" value="<? echo "$row[SurName]"?>">
</td>
</tr>
<tr>
<td>Address</td>
<td>
<input type="text" name="Address" size="40" value="<? echo "$row[Address]"?>">
</td>
</tr>
<tr>
<td align="right">
<input type="submit" name="submit" value="submit">
</td>
</tr>
</form>
</table>
</td>
</tr>
</table>
</body>
</html>
and here is the other file
<?php
$user_name = "";
$password = "";
$database = "";
$server = "";
mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database);
$id = $_REQUEST['ID'];
$FirstName = trim(mysql_real_escape_string($_POST["FirstName"]));
$SurName = trim(mysql_real_escape_string($_POST["SurName"]));
$Address = trim(mysql_real_escape_string($_POST["Address"]));
$sql = "UPDATE MY_ID SET FirstName='$FirstName',SurName='$SurName',Address='$Address' WHERE ID='$id'";
$result=mysql_query($sql);
if ($result){
echo "Successful";
echo "<BR>";
echo "<a href='edit.php'>View result</a>";
}
else {
echo "ERROR";
}
?>
Looks like you forget the double quotation mark and the full stop. You should write it as: '".$example."'
$sql = "UPDATE MY_ID SET FirstName='".$FirstName."',SurName='".$SurName."',Address='".$Address.:' WHERE ID='".$id."'";
It is because your form method is POST, and you are trying to GET ID.
Probably ID returns null.
My suggestion is to put a hidden input in your form as with name="ID", then read it in your posted page as $_POST["ID"];
Yes, the answer is as Mansours said. You should not use single quota to your variable.
So, it's bad practice writing code something like this:
<input type="text" value="<?php echo "$row[name]"; ?>">
it should be
<input type="text" value="<?php echo $row['name']; ?>">
it would be clear, and also, when inserting or updating the record you should write as follow:
$sql = "UPDATE MY_ID SET FirstName='" . $FirstName . "',
SurName='" . $SurName . "',
Address='" . $Address . "'
WHERE ID='" . $id . "'";
mysql_query($sql);

Categories