This question already has answers here:
PHP update table in MySQL not working
(2 answers)
Closed 6 years ago.
I have received an ID from a get request and put it into new variable $id. I am trying to include this variable in an SQL query but it doesn't work. It does however work when I hardcode the ID.
This works fine.
$query = "UPDATE products SET p_name = " . "'TEST' WHERE p_id=000007;";
The following code does NOT work. Can anyone explain it?
$query = "UPDATE products SET p_name = " . "'TEST' WHERE p_id=" . $id . ";";
All of my code if anyone can help:
<?php
// Connection file
//require 'db.php';
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check Connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$id = $_GET['id'];
echo $id;
if (isset($_POST["updateSubmit"])) {
$query = "UPDATE products SET p_name = " . "'TEST' WHERE p_id=" . $id . ";";
$result = mysqli_query($conn, $query);
}
?>
<div>
<form id="updateForm" name="updateForm" action="update.php" method="post">
<label>Product name:</label><br>
<input type="text" name="updateProductName"><br>
<label>Product type</label><br>
<select name="updateProductType">
<option value="Jackets/coats">Jackets/coats</option>
<option value="Accessories">Accessories</option>
<option value="Shirts">Shirts</option>
<option value="Jeans">Jeans</option>
<option value="Trousers">Trousers</option>
<option value="Shoes">Shoes</option>
<option value="Suits">Suits</option>
</select>
<p>Product description:</p>
<textarea name="updateProductDesc" rows="10" cols="30"></textarea><br>
<label>Product price:</label><br>
<input type="text" name="updateProductPrice"><br>
<label>Stock level:</label><br>
<input type="text" name="updateProductStock"><br>
<input type="submit" name="updateSubmit" value="Submit">
</form>
</div>
<?php
?>
I have used this link from another page which contains the ID.
<a href="update.php?mode=update&id=<?php echo $productDetails['p_id']; ?>"
title="Update <?php echo $productDetails['p_name']; ?>">Update</a>
You didn't get id because there is no id in your url
<form id="updateForm" name="updateForm" action="update.php?id=<?php echo $id; ?>" method="post">
or pass id as hidden like
<input type="hidden" name="id" id="your_id"/>
Change your query to
$query = "UPDATE products SET p_name = 'TEST' WHERE p_id=". $id;
Related
Technically it accepts all the input but there no any error message that there is something wrong with my code. The insert is located at the bottom part of the code which is strangely not working because I tried my insert statement in the database and of course changing the variables with real values and it worked that way.
Tried this insert statement in my workbench and it worked:
INSERT INTO members (organization,login,password,name,title,profil,created,logout_time,timezone) VALUES ('1','Kristen','123','Kristen Crooks','Volunteer','2','2016-10-11 14:09','0','0')
Code:
<html>
<head>
<meta charset="UTF-8">
<title></title>
<center><b> Volunteer Management </b></center>
<center>
Add User
Add Skills
Assign User
</center>
</head>
<body>
<?php
$config = parse_ini_file('/config.ini');
$conn = new mysqli($config['servername'], $config['username'], $config['password'], $config['database']);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT skillName FROM skills";
$result = $conn->query($sql);
$num=mysqli_num_rows($result);
$conn->close();
?>
<form method="get">
Username: <br>
<input type="text" name="username"> <br>
Password: <br>
<input type="text" name="password"> <br>
Name: <br>
<input type="text" name="name"> <br>
Title: <br>
<input type="text" name="title"> <br> <br>
Permission:
<select id="permission" name="permission">
<option selected disabled>Choose here</option>
<option value="0">Admin</option>
<option value="1">Project Manager</option>
<option value="2">Volunteer</option>
<option value="6">Accounting Officer</option>
</select> <br><br>
Skills: <br>
<?php
$i=0;while ($row = mysqli_fetch_assoc($result)) {
$skillName=$row['skillName'];
?>
<input type="checkbox" name="skills" value="<?php echo $skillName; ?>" ><?php echo $skillName; ?><br>
<?php $i++;} ?>
<br>
<input type="submit" name="submit">
</form>
<?php
if(isset($_GET['submit']))
{
$config = parse_ini_file('/config.ini');
$conn = new mysqli($config['servername'], $config['username'], $config['password'], $config['database']);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$login = $_GET['username'];
$password = $_GET['password'];
$name = $_GET['name'];
$title = $_GET['title'];
$profil = $_GET['permission'];
$created = date('Y-m-d H:i:s');
$sql = "INSERT INTO members (organization,login,password,name,title,profil,created,logout_time,timezone)
VALUES ('1','$login','$password','$name','$title','$profil','$created','0','0')";
$result = $conn->query($sql) or die('Error, insert query failed');
$conn->close();
}
?>
</body>
Okay I already dissected the code and it appears that the $created = date('Y-m-d H:i:s'); is causing the error. By the time I tried not to include it in the data in the insert statement, it worked! I guess I have to get another way to get the date from the system.
Also I've checked that the reason why there is an error is because the date format is in VARCHAR and not in date and another problem is that it does not fit in the length that set. Although I want to ask why it is not detected by the server that there is an error like that
Check PHP log and mysql log, write what is there.
Put an echo before the INSERT, check if your script comes to that place.
If echo is not working- then the problem is not in INSERT
As the title suggests I am trying to link a populated drop down list to a form on another page.
My dropdown list is currently connected to my database which displays the addressID's of 6 people. So when the user selects for example AddressID 3 it will take them to the next page (customerdetails.php) which will then allow them to update the form which will update the database accordingly.
My current code is as follows
<?php
//adding the database connection
$username = "root";
$password = "";
$hostname = "localhost";
//connection to the databse
$dbhandle = mysql_connect ($hostname, $username, $password)
or die ("Unable to Connect to MySQL");
echo "Connected to MySQL";
//selecting the database we want to work with
$selected = mysql_select_db("my_guitar_shop2", $dbhandle)
or die("Could not select my_guitar_shop2");
?>
<p>AddressID:</p> <br>
<?php
$sql = "SELECT addressID FROM addresses";
$result = mysql_query($sql);
echo "<select name='addressID' onchange = 'getAddressID(this)'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['addressID'] ."'>" . $row['addressID'] ."</option>";
}
echo "</select>";
?>
Now on the customerdetails.php page i have the code:
<?php
$adrresIDSelected = $_GET['addressID'];
?>
For the life of me I cannot seem to connect the 2 pages together.
Am i anywhere near the correct path? I would prefer not to use javascript as I have no prior knowledge of it.
Many thanks in advance
UPDATE
customerdetails.php page
<?php
//adding the database connection
$username = "root";
$password = "";
$hostname = "localhost";
//connection to the databse
$dbhandle = mysql_connect ($hostname, $username, $password)
or die ("Unable to Connect to MySQL");
echo "Connected to MySQL";
//selecting the database we want to work with
$selected = mysql_select_db("my_guitar_shop2", $dbhandle)
or die("Could not select my_guitar_shop2");
?>
<?php
$addrresIDSelected = $_GET['addressID'];
?>
Contact Form
<form class="form">
<p class="first">
<label for="name">FirstLine</label>
<input type="text" name="firstline" id="first" />
</p>
<p class="second">
<label for="email">SecondLine</label>
<input type="text" name="secondline" id="second" />
</p>
<p class="city">
<label for="web">City</label>
<input type="text" name="city" id="web" />
</p>
<p class="state">
<label for="web">State</label>
<input type="text" name="state" id="web" />
</p>
<p class="zip">
<label for="web">Zip Code</label>
<input type="number" name="zip" id="web" />
</p>
<p class="update">
<input type="button" value="Update" />
</p>
<p class="remove">
<input type="button" value="Remove" />
</p>
</form>
First solution (no Javascript)
For a solution without Javascript, you will need to use the select within a form element and use a submit button too to send the information completed/selected in the form to the desired page:
...
<form action="customerdetails.php" method="get">
<select name="addressID">
<?php
$sql = "SELECT addressID FROM addresses";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['addressID'] ."'>" . $row['addressID'] ."</option>";
}
?>
</select>
<input type="submit" value="Take me to the other page">
</form>
...
UPDATE - Second solution (with Javascript)
For using the getAddressID Javascript function to send the ID instead of using a form, you will need to update the function a bit:
<script>
function getAddressID (option) {
var addressID = option.value;
// you do not need the <your_domain> prefix here, as probably both your php scripts are on the same server/domain and same folder
window.location.replace ("customerdetails.php?addressID =" + addressID);
//-----------------------------------------------------^
// Extra space must be removed!
}
</script>
I have a select dropdown list that contains all existing usernames found in my table. I want to delete an entry from my table by selecting the corresponding username. I can't seem to find the error in my php file...I get the "Successfully deleted" message even if the entry is still there. Want to know what's wrong with my php. Thanks.
Here's the concerned portion of the View:
<form action="deleting.php" method="post">
<select id="username">
<option ng-repeat="user in users">
{{user.username}}
</option>
</select>
<input type="submit" value="Delete"/>
</form>
Here's my deleting.php file
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "abc";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$deletecontent= isset( $_POST["username"] ) ? $_POST["username"] : "null" ;
$sql = "DELETE from users where username='$deletecontent'";
if (mysqli_query($conn, $sql)) {
echo "Successfully deleted";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
You can get value in $_POST only when there is name attribute in your input. so try
<select id="username" name="username">
You have to add name attribute to select option. Then only it can be accessed using $_POST.
<select id="username" name = "username">
Set name="username" in <select>
and,
set value attribute in <option>.
<form action="deleting.php" method="post">
<select id="username" name="username">
<option ng-repeat="user in users" value="{{user.username}}">
{{user.username}}
</option>
</select>
<input type="submit" value="Delete"/>
</form>
This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 8 years ago.
I'm new to PHP and I've read many of the other undefined index error solutions on stackoverflow, but I still can't figure out why this rather simple code is receiving it. There's data in the database and everything else is pulling ok.
Right now I'm just trying to make sure the function and query are flowing through properly. So I purposely don't have if statements to check and see if the items are selected on the form because I'm always selecting them during testing. I must be missing something simple. Please help and thank you!
Form:
<!DOCTYPE html>
<html>
<head><title>Databases</title></head>
<body>
<h1>Music Store Database</h1>
<form method='POST' action='display.php'
<label>Select a table:</label>
<select name="tableName">
<option value="products">Products</option>
<option value="categories">Categories</option>
</select>
<p>Retrieve Record(s) - Select field(s) below:</p>
<input type="checkbox" name="productIDcb"/>
<label>ProductID</label><br />
<input type="checkbox" name="categoryIDcb"/>
<label>CategoryID</label><br />
<input type="checkbox" name="productCodecb"/>
<label>Product Code</label><br />
<input type="checkbox" name="productNamecb"/>
<label>Product Name</label><br />
<input type="checkbox" name="listPricecb"/>
<label>List Price</label><br />
<input type="checkbox" name="categoryNamecb"/>
<label>Category Name</label><br />
.
.
.
<p>Select the appropriate action based on your selection from above:</p>
<input type="radio" name="operation" value="retrieve"/>
<label>Retrieve Information</label><br />
<input type="radio" name="operation" value="addition"/>
<label>Add Information</label><br />
<input type="radio" name="operation" value="delete"/>
<label>Delete Information</label><br />
<p><input type="submit" value="Submit Request"/></p>
display.php File
<?php
require('database.php');
require('product_list.php');
$table = $_POST['tableName'];
$operation = $_POST['operation'];
$productIDcb = $_POST['productIDcb'];
$categoryIDcb = $_POST['categoryIDcb'];
$productCodecb = $_POST['productCodecb'];
$productNamecb = $_POST['productNamecb'];
$listPricecb = $_POST['listPricecb'];
if($operation == 'retrieve')
{
if($table == "products")
{
include_once('product_list.php');
show_products($table, $productIDcb, $categoryIDcb, $productCodecb, $productNamecb, $listPricecb);
}
}
?>
product_list.php file
<?php
include('database.php');
function show_products($table, $productIDcb, $categoryIDcb, $productCodecb, $productNamecb, $listPricecb)
{
global $db;
$theQuery = "select productId, categoryID, productCode, productName, listPrice ";
$theQuery .=" from ". $table;
echo($theQuery);
$rSet = $db -> query($theQuery);
$list = "";
foreach($rSet AS $products)
{
$list .= "".$products['productID']
. "".$products['categoryID']
. "".$products['productCode']
. "".$products['productName']
. "".$products['listPrice']
. "<br>";
}
echo($list);
}
?>
it is productId not productID in your select statement.
$products['productID'] should be $products['productId'] in product_list.php.
<?php
include('database.php');
function show_products($table, $productIDcb, $categoryIDcb, $productCodecb, $productNamecb, $listPricecb)
{
global $db;
$theQuery = "select productId, categoryID, productCode, productName, listPrice ";
$theQuery .=" from ". $table;
echo($theQuery);
$rSet = $db -> query($theQuery);
$list = "";
foreach($rSet AS $products)
{
$list .= "".$products['productId']
. "".$products['categoryID']
. "".$products['productCode']
. "".$products['productName']
. "".$products['listPrice']
. "<br>";
}
echo($list);
}
?>
productId and productID are considered different keys in php.
I'm trying to make a form that uses a drop down, radio buttons, text field, textarea, and a hidden value(the time) then takes that information from that form and updates SQL database.
My form is below and it all loads correctly but I'm having issues updating the values and trying to figure out how to make the radio buttons and dropdowns to work since I can't make the value php code and need to pass the value. Everything I'm finding on the web is how to do text fields where the user types something.
When I select update it just submits the data but nothing changes. On my update.php I have a sanitize function at the very end and am unsure how to pass the variables in. Do I create an array named $var and input all my variables into it or pass each variable at a time?
I've been searching the web for HOW TO's and am currently reading two books but they don't go into enough detail so thanks for any assistance.
control.php
<?php
session_start();
if( !isset($_SESSION['myusername']) ){ header("Location: login.php"); }
?>
<?php
require("../../system/templates/includes/constants.php");
$connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS);
if(!$connection) { die("Database connection failed: " .mysql_error()); }
$db_select = mysql_select_db(DB_NAME,$connection);
if(!$db_select) { die("Database selection failed: " . mysql_error()); }
?>
<form method="post" action="update.php">
<select name="name" required="true" value="<?php echo $row['name']; ?>">
<?php
$query="SELECT id, name FROM modules";
$result=mysql_query($query);
while ($row=mysql_fetch_array($result)) {
echo "<option value=\"" . $row['id'] . "\">" . $row['name'] . "</option>";
}
?>
</select>
<br />
Select Status:
Red <input type="radio" value="red" name="status" />
Yellow <input type="radio" value="yellow" name="status" />
Green <input type="radio" checked="checked" value="green" name="status" />
<br />
Reason:
<br />
<select name="reason" required="true">
<option value="0" selected="selected" value="">Select Reason</option>
<option value="ONLINE">Online</option>
<option value="MAINTENANCE">Maintenance</option>
<option value="ERROR">Error</option>
<option value="OFFLINE">Offline</option>
<option value="">No Reason</option>
</select>
<br />
ETA:
<br />
<input type="text" name="eta" value="<?php echo $row['eta']; ?>" maxlength="8" />
<br />
Description:
<br />
<textarea rows="5" cols="30" name="explanation" wrap="hard" required="true" maxlength="320" value="<?php echo $row['description']; ?>" /></textarea>
<br />
<div align="right">
<input name="update" type="submit" value="Update"/>
<input type="hidden" name="last_updated" value="<?php $mysqldate = date ('H:i'); $phpdate = strtotime ( $mysqldate );?> />
</form>
update.php
<?php
print_r(_POST);
if(isset($POST['update']))
{
$connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS);
if(! $connection)
{
die('Could not connect: ' .mysql_error());
}
$name = $POST['name'];
$status = $POST['status'];
$reason = $POST['reason'];
$eta = $POST['eta'];
$description = $POST['description'];
$last_updated = $POST['last_updated'];
$updated_by = $POST['updated_by'];
$sql = "UPDATE module SET status = $status , reason = $reason , eta = $eta , description = $description , last_updated = $last_updated , updated_by = $updated_by WHERE name = $name";
mysql_select_db('status');
$retval = mysql_query ( $sql, $connection);
if (!retval)
{
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully";
mysql_close($connection);
} else {
// not sure what to do here
}
function sanitizeString($var)
{
$var = stripslashes($var);
$var = htmlentities($var);
$var = strip_tags($var);
return $var;
}
function sanitizeMySQL($var)
{
$var = mysql_real_escape_string($var);
$var = satnizeString($var);
return $var;
}
header("Location: control.php");
?>
As always I greatly appreciate any assistance anyone can offer. I'm still in the very early stages of learning this and this website and community has helped me more than any book/tutorial I've read so far.
Your SQL statement needs quotation marks for each parameter.
$sql = "UPDATE module SET status = '$status' , reason = '$reason' , eta = '$eta' , description = '$description' , last_updated = '$last_updated' , updated_by = '$updated_by' WHERE name = '$name' ";
As for the sanitizeString() function, it only takes in one string at a time. Maybe something like the one below may be simple and clean:
$params = array($name, $status, $reason); // put all your params in here
foreach ($params as &$p) { // the '&' before $p is essential, so do not forget it
$p = sanitizeString($p);
}
Hope it helps.