My script is updating all fields when I just edit one - php

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.

Related

How can i insert html table data into sql database using 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.

fetching data into dropdownlist and get the selected data in php

I am trying to fetch some data from databse and display it into dropdownlist and get the selected data using php.
Code
<?php
if(isset($_POST['action']) && $_POST['action'] == 'Save'){
savecategory();
}
function savecategory() {
$category=$_POST["category"];
$servername = "localhost";
$username = "root";
$password = "******";
$dbname = "db";
$conn = new mysqli($servername, $username, $password, $dbname);
if (!conn) {
die("Connection Failed: " . mysqli_connect_error());
}
echo"Connected Successfully";
$sql = "INSERT INTO category_tbl(cat_name) VALUES ('$category')";
if(mysqli_query($conn,$sql))
{
echo"Successfully Saved";
}
else{
echo"save failed..!!";
}
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>gallery category</title>
</head>
<body>
<form action="<?php $_SERVER["PHP_SELF"]?>" method="post">
<!--division for category insertion-->
<div class="categoryEntry">
<table align="center">
<th colspan="2">Gallery Category</th>
<tr>
<td>Category</td>
<td> <input type="text" name="category"> </td>
</tr>
<tr>
<td> <input type="submit" name="action" value="Save"> </td> <td> <input type="submit" name="action" value="Cancel"> </td>
</tr>
</table>
</div>
<!-- end of category insertion div-->
<!-- start retreive category data into table -->
<hr>
<br><br><br>
<div>
<table align="center">
<th align="center" colspan="2"> Category List</th><br>
<tr><td>Select Your Category:</td>
<td><label>
<select name="Select" class="textfields" id="ddlcategory">
<option id="0">---Select your category---</option>
<?php
$servername = "localhost";
$username = "root";
$password = "******";
$dbname = "mydb";
$conn = new mysqli($servername, $username, $password, $dbname);
if (!conn) {
die("Connection Failed: " . mysqli_connect_error());
}
echo"Connected Successfully";
$sql=mysqli_query("SELECT * FROM category_tbl");
while($category=mysqli_fetch_array($sql)){
?>
<option id="<?php echo $category['cat_id']; ?>">
<?php echo $category['cat_name']; ?></option>
<?php
}
?>
</select>
</label>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
I have write code for retrieving data but it can't able to show data in drop downlist.
help needed..!! thanks..
I hope the following code solves your problem:
<?php
{
mysqli_select_db($conn, "db");
$sql = "SELECT * FROM category_tbl";
$query = mysqli_query($link1, $sql);
echo"<select name='category_tbl'>";
while($row = mysqli_fetch_array($query))
{
echo "<option value'" . $row['cat_id'] . "'>" . $row['cat_id'] . "</option>";
}
echo "</select>";
}
?>
Try the below code
<select>
<?php
$query= "Select * from DB_Table_Name>"; //Your Sql Query in a variable
$execute = mysqli_query($db,$query); // Execute your query..$db is your connection variable
while($row = mysqli_fetch_array($execute,MYSQLI_BOTH))
{?>
<option><?php echo $row['something']; ?></option> //Use Your Table Name Instead of Something
<?php
}
?>
</select>

PHP page to run MySQL query

I need a PHP+HTML page which would ask for two values from user i.e. password & id_category.
So far I have coded the PHP as:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "db1";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "select user_id,mobile from test_user_table where id_category like '912' or id_category like '912%' or id_category like '%912%' or id_category like '%912'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["user_id"]. " - Mobile: " . $row["mobile"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
I need a HTML page which would ask for those two variables and pass on to this code i.e. value of password to $password & id_category to the select statement (instead of 912)
Pls help
You html will be something look like below
<!DOCTYPE html>
<html>
<title>Login Form</title>
<body>
<form action="form_submit" method="post">
<table>
<tr>
<td>Username</td>
<td>:</td>
<td><input type="text" name="username" /></td>
</tr>
<tr>
<td>Password</td>
<td>:</td>
<td><input type="password" name="username" /></td>
</tr>
<tr>
<td>Category</td>
<td>:</td>
<td><select name="category">
<option value="192">Category 1</option>
<option value="193">Category 2</option>
<option value="194">Category 3</option>
<option value="195">Category 4</option>
</select></td>
</tr>
</table>
</form>
</body>
</html>
Since I user method as POST you should get the value on form_submit.php as
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$category = $_POST['category'];
?>
This should be help:
HTML:
<form name="login" method="post">
Username<input type="text" name="username"/>
Password<input type="password" name="password"/>
Category<input type="text" name="category"/>
<input type="submit" name="submit"/>
</form>
PHP:
<?
if (isset ($_POST["submit"]){
$username = mysqli_real_escape_string( $_POST["username"]);
$password = mysqli_real_escape_string( $_POST["password"]);
$category = mysqli_real_escape_string( $_POST["category"]);
// YOUR QUERY
$sql = "
SELECT columns FROM table WHERE
username = '$username' AND
password = '$password' AND (
categoryid LIKE '$category' OR
categoryid LIKE '%$category' ....
)
";
}//if end
?>

Edit page error how to fix?

I seem to have problem fixing this:
<?php
$username = "root";
$password = "";
$database = "learningnews";
$db = mysql_connect('localhost', $username, $password, $database);
$id = $_GET["title"];
$show = "SELECT * FROM learningnews.news where title = '$id'";
$ending = mysql_query($show);
$now = mysql_fetch_array($ending);
?>
<html>
<head>
<title>Edit Page</title>
</head>
<body>
<tr>
<td>
<table border="1">
<form method="post" action="newsedit.php">
<tr>
<td>
<input type="text" name="name" size="40" value="<?php echo "$now[title]" ?>">
</tr>
</td>
<tr>
<td>
<input type="text" name="name1" size="500" value="<?php echo "$now[content]" ?>">
</tr>
</td>
</form>
</tr>
</td>
</table>
</body>
</html>
I seem can't get to show of the title and the content that I have in my database so that I can edit it I get this error:
Notice: Undefined index: title in C:\xampp\htdocs\newsedit.php on line 6
Could someone help please ?
EDIT : Heres the code where I submit the news and ouput them.
EDIT2 : Re-posted the second php file. Here how it looks. This time, no error but it doesnt show the content and title i want .. in the input fields.
<?php
$id ="";
$username = "root";
$password = "";
$database = "learningnews";
$db = mysql_connect('localhost', $username, $password, $database);
$show = "SELECT * FROM learningnews.news where title = '$id'";
$ending = mysql_query($show);
$now = mysql_fetch_array($ending);
?>
<html>
<head>
</head>
<body>
<tr>
<td>
<table border="1">
<form method="post" action="newsedit.php">
<tr>
<td>
<input type="text" name="title" size="40" value="<?php echo "$now[title]" ?>">
</tr>
</td>
<tr>
<td>
<input type="text" name="content" size="500" value="<?php echo "$now[content]" ?>">
</tr>
</td>
</form>
</tr>
</td>
</table>
</body>
</html>
Basically, I need the ouput from first code to show in second and so I can edit it then update it.
<?php
if ( isset( $_GET['name'] ) )
{
$username = "root";
$password = "";
$database = "learningnews";
$db = mysql_connect('localhost', $username, $password, $database);
$id = $_GET["name"];
$show = "SELECT * FROM learningnews.news where title = '$id'";
$ending = mysql_query($show);
$now = mysql_fetch_array($ending);
}
?>
Because $_GET["title"]; was never defined. Not sure what are you trying to do with title.
You need to check if the variable is set with isset before you use it.
<?php
if(isset($_GET['title']))
$id = $_GET["title"];
?>
In your previous page's code you need to change the form method to GET so you can check your title with $_GET on the next page.
<form method="GET" action="admin.php">
<input type="text" name="title">
<textarea name="content"></textarea>
<input type="submit" value="posthorses"/>
</form>

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