I'm trying to setup a form that can update my product.
the code reads data ok, but $update is getting errors that prevents the update from doing anything.
The errors are :
Undefined variable: update
mysqli::query(): Empty query (after submit the form)
Please Help! Thanks.
//include database configuration file
include("config.php");
$mysqli->set_charset("utf8");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Edit Page</title>
</head>
<body>
<?php
if(isset($_POST['Submit'])){//if the submit button is clicked
$updateproductname = $_POST['updateproductname'];
$updatesku = $_POST['productsku'];
$updateproductoriginal = $_POST['updateoriginalname'];
$updatedescshort = $_POST['updatedescshort'];
$update = $mysqli->query("UPDATE testproducts".
"SET product_sku=$updatesku, product_name=$updateproductname, 'product_originalname'='$updateproductoriginal', 'product_description_short='$updatedescshort' ".
"WHERE product_id = '$id' ");
$mysqli->query($update) or die("Cannot update");//update or error
}
?>
<?php
//Create a query
$sql = "SELECT * FROM testproducts WHERE product_id = $id";
//submit the query and capture the result
$result = $mysqli->query($sql) or die(mysql_error());
?>
<h2>Update Record <?php echo $id;?></h2>
<form action="" method="post">
<?php
while ($row = $result->fetch_assoc()) {?>
<table border="0" cellspacing="10">
<tr>
<td>Product Name:</td> <td><input type="text" name="updateproductname" value="<?php echo $row['product_name']; ?>"></td>
</tr>
<tr>
<td>Product Original Name:</td> <td><input type="text" name="updateoriginalname" value="<?php echo $row['product_originalname']; ?>"></td>
</tr>
<tr>
<td>Product SKU:</td> <td><input type="text" name="productsku" value="<?php echo $row['product_sku']; ?>"></td>
</tr>
<tr>
<td>ShortDescription:</td> <td><input type="text" name="updatedescshort" size="100" value="<?php echo $row['product_description_short']; ?>"></td>
</tr>
<tr>
<td><INPUT TYPE="Submit" VALUE="Update the Record" NAME="Submit"></td>
</tr>
</table>
<?php
}
?>
</form>
<?php
if($update){//if the update worked
echo "<b>Update successful!</b>";
}
?>
</body>
</html>
a) You are vulnerable to SQL injection attacks
b) Read the docs for mysqli_query(). The function takes a query STRING, and returns a RESULT HANDLE. You're then taking that result handle and trying to re-query it. If you'd bothered having proper error handling on ALL of your mysqli calls, you'd have seen this.
was able to update the record after moving the update and select code to top of html
<?php
if(isset($_POST['Submit'])){//if the submit button is clicked
// Check connection
$productname = $_POST['updateproductname'];
$productoriginal = $_POST['updateoriginalname'];
$sku = $_POST['productsku'];
$descshort = $_POST['updatedescshort'];
$mysqli->query("UPDATE testproducts ".
"SET product_name='$productname',product_originalname='$productoriginal', product_sku='$sku', product_description_short='$descshort'".
" WHERE product_id='$id'");
}
?>
<?php
//Create a query
$sql = "SELECT * FROM testproducts WHERE product_id = $id";
//submit the query and capture the result
$result = $mysqli->query($sql) or die(mysql_error());
//$query=getenv(QUERY_STRING);
//parse_str($query);
//$ud_title = $_POST['Title'];
//$ud_pub = $_POST['Publisher'];
//$ud_pubdate = $_POST['PublishDate'];
//$ud_img = $_POST['Image'];
$mysqli->close();
?>
Related
I have this Add Edit Delete form, the problem is:
when I put everything and I click on ADD it says "Data added successfully." but the data isn't in my table of phpAdmin and it not shows in the page...
Or is simply because my hoster doens't work with MySQLi but with MySQL?
Without talking about SQL Injections because Im not so expert and dont know how protect from that, this pages will be protected with login area so only restricted members will access to it.
index.php
<?php
//including the database connection file
include_once("config.php");
//fetching data in descending order (lastest entry first)
//$result = mysql_query("SELECT * FROM users ORDER BY id DESC"); // mysql_query is deprecated
$result = mysqli_query($mysqli, "SELECT * FROM `user` ORDER BY id DESC"); // using mysqli_query instead
?>
<html>
<head>
<title>Homepage</title>
</head>
<body>
Add New Data<br/><br/>
<table width='80%' border=0>
<tr bgcolor='#CCCCCC'>
<td>Steam Username</td>
<td>Steam Password</td>
<td>Steam Guard Code</td>
<td>Update</td>
</tr>
<?php
//while($res = mysql_fetch_array($result)) { // mysql_fetch_array is deprecated, we need to use mysqli_fetch_array
while($res = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>".$res['steamUE']."</td>";
echo "<td>".$res['steamPW']."</td>";
echo "<td>".$res['steamGC']."</td>";
echo "<td>Edit | Delete</td>";
}
?>
</table>
</body>
</html>
add.html
<html>
<head>
<title>Add Data</title>
</head>
<body>
Home
<br/><br/>
<form action="add.php" method="post" name="form1">
<table width="25%" border="0">
<tr>
<td>Steam Username</td>
<td><input type="text" name="steamUE"></td>
</tr>
<tr>
<td>Steam Password</td>
<td><input type="text" name="steamPW"></td>
</tr>
<tr>
<td>Steam Guard Code</td>
<td><input type="text" name="steamGC"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="Submit" value="Add"></td>
</tr>
</table>
</form>
</body>
</html>
edit.php
<?php
// including the database connection file
include_once("config.php");
if(isset($_POST['update']))
{
$id = mysqli_real_escape_string($mysqli, $_POST['id']);
$steamUE = mysqli_real_escape_string($mysqli, $_POST['steamUE']);
$steamPW = mysqli_real_escape_string($mysqli, $_POST['steamPW']);
$steamGC = mysqli_real_escape_string($mysqli, $_POST['steamGC']);
// checking empty fields
if(empty($steamUE) || empty($steamPW) || empty($steamGC)) {
if(empty($steamUE)) {
echo "<font color='red'>Steam Username field is empty.</font><br/>";
}
if(empty($steamPW)) {
echo "<font color='red'>Steam Password field is empty.</font><br/>";
}
if(empty($steamGC)) {
echo "<font color='red'>Steam Guard Code field is empty.</font><br/>";
}
} else {
//updating the table
$result = mysqli_query($mysqli, "UPDATE `user` SET steamUE='$steamUE',steamPW='$steamPW',steamGC='$steamGC' WHERE id='$id'");
//redirectig to the display page. In our case, it is index.php
header("Location: index.php");
}
}
?>
<?php
//getting id from url
$id = $_GET['id'];
//selecting data associated with this particular id
$result = mysqli_query($mysqli, "SELECT * FROM `user` WHERE id='$id'");
while($res = mysqli_fetch_array($result))
{
$steamUE = $res['steamUE'];
$steamPW = $res['steamPW'];
$steamGC = $res['steamGC'];
}
?>
<html>
<head>
<title>Edit Data</title>
</head>
<body>
Home
<br/><br/>
<form name="form1" method="post" action="edit.php">
<table border="0">
<tr>
<td>Steam Username</td>
<td><input type="text" name="steamUE" value="<?php echo $steamUE;?>"></td>
</tr>
<tr>
<td>Steam Username</td>
<td><input type="text" name="steamPW" value="<?php echo $steamPW;?>"></td>
</tr>
<tr>
<td>Steam Guard Code</td>
<td><input type="text" name="steamGC" value="<?php echo $steamGC;?>"></td>
</tr>
<tr>
<td><input type="hidden" name="id" value=<?php echo $_GET['id'];?>></td>
<td><input type="submit" name="update" value="Update"></td>
</tr>
</table>
</form>
</body>
</html>
delete.php
<?php
//including the database connection file
include("config.php");
//getting id of the data from url
$id = $_GET['id'];
//deleting the row from table
$result = mysqli_query($mysqli, "DELETE * FROM `user` WHERE id='$id'");
//redirecting to the display page (index.php in our case)
header("Location: index.php");
?>
add.php
<html>
<head>
<title>Add Data</title>
</head>
<body>
<?php
//including the database connection file
include_once("config.php");
if(isset($_POST['Submit'])) {
$steamUE = mysqli_real_escape_string($mysqli, $_POST['steamUE']);
$steamPW = mysqli_real_escape_string($mysqli, $_POST['steamPW']);
$steamGC = mysqli_real_escape_string($mysqli, $_POST['steamGC']);
// checking empty fields
if(empty($steamUE) || empty($steamPW) || empty($steamGC)) {
if(empty($steamUE)) {
echo "<font color='red'>Steam Username field is empty.</font><br/>";
}
if(empty($steamPW)) {
echo "<font color='red'>Steam Password field is empty.</font><br/>";
}
if(empty($steamGC)) {
echo "<font color='red'>Steam Guard Code field is empty.</font><br/>";
}
//link to the previous page
echo "<br/><a href='javascript:self.history.back();'>Go Back</a>";
} else {
// if all the fields are filled (not empty)
//insert data to database
$result = mysqli_query($mysqli, "INSERT INTO `user` (steamUE,steamPW,steamGC) VALUES ('$steamUE','$steamPW','$steamGC')");
//display success message
echo "<font color='green'>Data added successfully.";
echo "<br/><a href='index.php'>View Result</a>";
}
}
?>
</body>
</html>
config.php
<?php
/*
// mysql_connect("database-host", "username", "password")
$conn = mysql_connect("localhost","root","root")
or die("cannot connected");
// mysql_select_db("database-name", "connection-link-identifier")
#mysql_select_db("test",$conn);
*/
/**
* mysql_connect is deprecated
* using mysqli_connect instead
*/
$databaseHost = 'sql.website.com';
$databaseName = '';
$databaseUsername = '';
$databasePassword = '';
$mysqli = mysqli_connect($databaseHost, $databaseUsername, $databasePassword, $databaseName);
?>
It not doesn't says or shows any errors or any other problems, it says only data added successfully and nothing else. I don't understand why it doesn't add any data in my tables, i checked everything again and again, maybe because i'm tired but i tried to rename tables names but nothing change, is the same...
Spotted three errors,
add.php: Column names should be without ''. Check the following
$result = mysqli_query($mysqli, "INSERT INTO user (steamUE,steamPW,steam_GC) VALUES ('$steamUE','$steamPW','$steamGC')");
edit.php: '' missing from $id. Check the following
$result = mysqli_query($mysqli, "UPDATE user SET steamUE='$steamUE',steamPW='$steamPW',steamGC='$steamGC' WHERE id='$id'");
delete.php: '' missing from $id. Check the following
$result = mysqli_query($mysqli, "DELETE * FROM user WHERE id='$id'");
If the connection with DB is successful, it must work (and this answer deserves a green tick from you :D).
Or is simply because my hoster doens't work with MySQLi but with
MySQL?
Wherever I faced issues, I got some error or a blank page.
Check your dB connection. Turn to mysqli, declair it with $sql with (errno), but call your param before $sql. Use if condition to check your connection. On your add please use prepared with $stmnt and execute it.
I am trying to edit a mysql table, however when i submit the form, the table does not get updated, and the previous value remains the same. I am not getting any errors at all either...
i have tried running the update query directly in the database, and it works...can someone have a look at my code and see if they can help?
below is my code:
edit.php
<?php include('server.php') ?>
<?php
if(isset($_POST['update']))
{
$responseid = $_POST['responseid'];
$response=$_POST['response'];
{
//updating the table
$result = $conn->prepare ("UPDATE response SET response= '$response' WHERE responseid=$responseid");
header("Location: results.php");
}
}
?>
<?php
//getting id from url
$responseid = $_GET['id'];
//selecting data associated with this particular id
$result = $conn->prepare("SELECT * FROM response WHERE responseid=$responseid");
while ($response = $result->fetch())
{
$response = $res['response'];
$student_id = $res['student_id'];
}
?>
<html>
<head>
<title>Edit Data</title>
</head>
<body>
<form name="form1" method="post" action="edit.php">
<table border="0">
<tr>
<td>response</td>
<td><input type='text' name='date' value="<?php echo $response;?>"</td>
</tr>
<tr>
<td><input type="hidden" name="id" value=<?php echo $_GET['id'];?>></td>
<td><input type="submit" name="update" value="Update"></td>
</tr>
</table>
</form>
</body>
</html>
results.php
<div id="table1" class="table1">
<?php
if(isset($_POST["submit"]))
{
$searchTerm=$_POST['search'];
$stmt = $conn->prepare(" SELECT question.description AS question, answer.description AS answer, discipline.name AS name, response.responseid AS responseid, response.response AS response, response.student_id AS student_id, response.Date_Time AS Date
FROM response
INNER JOIN answer ON response.question_id = answer.answerid
INNER JOIN question ON response.question_id = question.qid
INNER JOIN discipline ON response.discipline_id = discipline.disciplineid WHERE Date_Time LIKE :searchTerm");
$stmt->bindValue(':searchTerm','%'.$searchTerm.'%');
$stmt->execute();
$result=0;
/*
The above code is a query which selects attributes according to the search term
*/
echo "<table> <tr><th>Discipline</th><th>Question</th><th>Student ID</th><th>Response</th><th>Date & Time</th><th>Answer</th><th>Final Marks</th></tr>";
while ($response = $stmt->fetch()) /* This is a While loop which iterates each row */
{
echo " <tr><td>".$response["name"]."</td><td>".$response["question"]."</td><td>".$response["student_id"]."</td><td>".$response["response"]."</td><td>".$response["Date"]."</td><td><input type='text' name='date' value=". $response["answer"]."></td><td>Edit</td></tr> ";
$result++;
}
} /* This bit of code closes the connection with the database */
?>
</div>
please click this link to see my database
Updating using prepared statements (similar to the way your doing it in the select in the second listing)...
//updating the table
$result = $conn->prepare ("UPDATE response
SET response= :response
WHERE responseid=:responseid");
$result->bindValue(':response',$response);
$result->bindValue(':responseid', $responseid);
$result->execute();
Also check the contents of $_POST as I think you have the field names wrong (think they were 'date' and 'id')...
<form name="form1" method="post" action="edit.php">
<table border="0">
<tr>
<td>response</td>
<td><input type='text' name='response' value="<?php echo $response;?>"</td>
</tr>
<tr>
<td><input type="hidden" name="responseid" value=<?php echo $_GET['id'];?>></td>
<td><input type="submit" name="update" value="Update"></td>
</tr>
</table>
</form>
I like to have a standard value filled in the input field.
I have this code:
$stma = $conn->prepare("SELECT * FROM `users` WHERE ID = '".$_GET['gebruiker']."' ");
$stma->execute();
$row_count = $stma->rowCount(); // returns 1
foreach ($conn->query($stma) as $rows) {
$Username = $rows['Username'];
}
/// my form
echo '<form method="POST" >
<table>
<th colspan="3"><h1>Gebruiker bewerken</h1></th>
<tr>
<th>
<h3>Gebruikersnaam: </h3>
</th>
<td>
<input style="width: 70%;" type="text" READONLY value="'.$Username.'" >
// the value must be filled in this input field
</td>
</tr>
<tr>
<th>
<h3>Wachtwoord: </h3>
</th>
<td>
<input style="width: 70%;" type="password" name="wachtwoord" REQUIRED>
</td>
</tr>
<tr>
<th>
</th>
<td colspan="2">
<input type="submit" name="bewerken" class="button" style="vertical-align:middle" value="Opslaan">
</td>
</tr>
'.$error.'
</table>
</form>';
The code doesn't fill in the value i got from the database.
I still get an empty form field.
My query returns 1 result row (i checked)
Does someone see my mistake?
I don't see the mistake i've made (it must me my mistake, it worked for me on other forms too)
To make sure it outputs all errors and warnings (for debugging), this might help:
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
Place above mentioned code at the top of your file.
And you might want to prevent any SQL injection as well:
$stma = $conn->prepare("SELECT * FROM `users` WHERE ID = ? ");
$stma->bindParam(1, $_GET['gebruiker'], PDO::PARAM_INT);
$stma->execute();
$stma->debugDumpParams(); // you could use this to check whether or not all parameters are set correctly
$row_count = $stma->rowCount(); // returns 1
foreach ($conn->query($stma) as $rows) {
$Username = $rows['Username'];
}
Below is a working example.
PHP
try {
$conn = new PDO('mysql:host=localhost;dbname=YourDBname', 'root', '');
} catch (PDOException $e) {
echo $e->getMessage();
}
$id = $_GET['gebruiker'];
$sql = "SELECT * FROM `users` WHERE id = :id";
$stm = $conn->prepare($sql);
$stm->execute(['id'=>$id]);
$user = $stm->fetchObject();
$username = $user->username;
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test</title>
</head>
<body>
<form action="POST">
<input type="text" value="<?php echo (isset($username)) ? $username : 'No value' ; ?>">
</form>
</body>
</html>
If your set gebruiker from your url, then you just have do it like: script.php?gebruiker = 1 You can replace 1 with any ID value that exists in your table.
please try this code
$stma = $conn->prepare("SELECT * FROM `users` WHERE ID = '".$_GET['gebruiker']."' ");
$stma->execute();
$row_count = $stma->rowCount(); // returns 1
foreach ($conn->query($stma) as $rows) {
$Username = $rows['Username'];
}
**please replace this code**
$res = $conn->query("SELECT * FROM users WHERE ID = '".$_GET['gebruiker']."' ");
$allRows = $res->fetch_assoc();
$Username = $allRows['UserName'];
When trying to make an edit page for a table in PHP, I'm running into a problem on the edit.php page where when I click edit table row button, it brings me to the correct page obviously (edit.php), and then when I enter in the edited details and submit it, it makes a whole new table row entry instead of update the one I had selected for it to update.
I have checked to make sure the id is set correctly to the correct table row in the database and it is. I have no idea why it is doing this. Any help would greatly be appreciated.
<?php require("manage_post.php"); ?>
<?php
session_start();
if(!isset($_SESSION['userName'])){ //if login in session is not set
header("Location: login.php");
exit();
}
?>
<?php
$con = mysql_connect("localhost","root","");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("cad", $con)
or die('Could not select database');
$query="SELECT `town`, `location`, `incident_type`, `time_date`, `admin`, `id`
FROM `cad`
WHERE `id` =
$_GET[id]";
$result=mysql_query($query)
or die(mysql_error());
while( false!=($row=mysql_fetch_array($result)) )
{
echo '<h1>Town name: ', htmlspecialchars($row['town']), '</td>';
}
$town=$row['town'] ;
$location= $row['location'] ;
$incident_type=$row['incident_type'] ;
if(isset($_POST['save']))
{
$town = $_POST['town'];
$location = $_POST['location'];
$incident_type = $_POST['incident_type'];
mysql_query("UPDATE cad SET town ='{$town}', location ='{$location}',
incident_type ='{$incident_type}' WHERE `id` = $_GET[id]") or die(mysql_error());
echo "Saved! Redirecting back to the home page.";
}
mysql_close($con);
$id=$_GET['id'];
?>
<!DOCTYPE html>
<html>
<head>
<title>Edit Incident</title>
</head>
<body>
<?php
echo "<h1>You are editing incident number # $id</h1>";
?>
<form method="post">
<table>
<tr>
<td>Town</td>
<td><input type="text" name="town" value="<?php echo $town; ?>"/></td>
</tr>
<tr>
<td>Location</td>
<td><input type="text" name="location" value="<?php echo $location; ?>"/></td>
</tr>
<tr>
<td>Incident Type</td>
<td><input type="text" name="incident_type" value="<?php echo $incident_type; ?>"/></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="save" value="Save" /></td>
</tr>
</table>
</body>
</html>
You have to use query like below
mysql_query("UPDATE cad SET town ='{$town}', location ='{$location}',
incident_type ='{$incident_type}' WHERE `id` = {$_GET['id']}") or die(mysql_error()); ;
Add new hidden key to post
<input type="hidden" name="savedid" value="<?php echo $_GET['id']?>" />
And in the update sql
$town = $_POST['town'];
$location = $_POST['location'];
$incident_type = $_POST['incident_type'];
$savedid = $_POST['savedid'];
mysql_query("UPDATE cad SET town ='{$town}', location ='{$location}',
incident_type ='{$incident_type}' WHERE `id` = $savedid") or die(mysql_error());
echo "Saved! Redirecting back to the home page.";
and you should filter your vars if security concerns you consider using intval for ids
I am a new PHP coder and I started a project of cms panel with, for start, three options: new article, delete article and edit article. There isn't even one error in my project but, when im trying to edit a post, everything is going well, except the save. The post isn't saved!!! and there aren't any errors! I am trying to fix that problem from yesterday. That's annoying.
Here is part of my code:
editTreat.php:
<!DOCTYPE html>
<?php
include("includes/functions.php");
$ctreat = getTreat($_GET["id"]);
?>
<html lang="en">
<head>
<script type="text/javascript" src="ckeditor/ckeditor.js"></script>
<meta charset="utf-8" />
<title>Control panel</title>
</head>
<body>
<form action="doEditt.php" method="post">
<table>
<tr>
<td>
<label for="tName">:Title</label>
</td>
<td>
<input type="text" name="tName" value="<?php echo $ctreat["Title"]; ?>"></input>
</td>
</tr>
<tr>
<td>
<label for="tContent">:Content</label>
</td>
<td>
<textarea name="tContent"> <?php echo $ctreat["Content"]; ?> </textarea>
<script type="text/javascript">
CKEDITOR.replace('tContent');
</script>
</td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="submit" value="Edit"></input></td>
<td> <input type="hidden" name="id" value="<?php echo $_GET["ID"]; ?>" /></td>
</tr>
</table>
</form>
</body>
</html>
doEditt.php:
<?php
include("includes/functions.php");
if(isset($_POST["submit"])) {
if(isset($_POST["tName"])) {
editTreat($_POST["tName"],$_POST["tContent"],$_POST["id"]);
header("Location: treatments.php");
} else {
echo "Please fill the title";
include("editTreat.php");
}
} else {
header("Location: editTreat.php");
}
?>
part of my includes/functions.php:
function editTreat($tName, $tContent, $id) {
$id = (int) $id;
$query = mysql_query("UPDATE `treatments` SET title = '$tName', content = '$tContent' WHERE ID = '$id'") or die(mysql_error());
header("Location: treatments.php");
}
function getTreat($id) {
$id = (int) $id;
$query = mysql_query("SELECT * FROM `treatments` WHERE ID = '$id'") or die(mysql_error());
return mysql_fetch_assoc($query);
}
So, if you can help me, please help me. Thanks!!
On line 4 you reference id lower case
$ctreat = getTreat($_GET["id"]);
Notice Lowercase id
Then in the form you reference ID Uppercase
<?php echo $_GET["ID"]; ?>
PHP is case sensitive... is id upper or lower case
The posting ID is not getting sent to the submit form, this looks to be your issue.
Some obvious issues:
I'm sure id column is not string so why quotes?
UPDATE `treatments` SET title = '$tName', content = '$tContent' WHERE ID = $id
You should escape any user input.
$tName = mysql_real_escape_string($tName);
PHP is case sensitive, and you use diferent case for $_GET["id"]. Im sure you want to use $_GET["id"]!
$ctreat = getTreat($_GET["id"]);
VERSUS
echo $_GET["ID"];