how to link mysql 'id' to html element - php

I have a database with some rows of data that display on a webpage. Now, I am looking for a way to link each 'ID' field in mysql to a button so that when the button is clicked, a php script will run that deletes the row of mysql information associated with that ID.
I know this is incorrect but I think its close. Just don't know about the php portion inside the id tag. Help?
<form action="remove.php" method="post">
<input type="submit" value="Remove Entry" id="<?php $row['id'] ?>" />
</form>
Am I even on the right path?
Would remove.php look like...
<?php
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if($conn === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "DELETE from newcars (stock, year, make, model, trim)
WHERE ('$_POST[id] = $row[id]');
if(mysqli_query($conn, $sql)){
echo "Records deleted successfully.";
}
else {
echo "ERROR: Could not execute $sql. " . mysqli_error($link);
}
mysql_close($conn)
?>
Any help would be greatly appreciated.
Thank you!

HTML:
<form action="remove.php" method="post">
<input type="hidden" name="id" value="<?php echo (int)$row['id']; ?>">
<input type="submit" value="Remove Entry" />
</form>
You want to pass the ID in a form element, NOT with the submit button.
The PHP would look like this - and this is more secure than your original code as it uses prepared statements.
<?php
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if($conn === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$stmt = $conn->prepare("DELETE FROM newcars WHERE id = ?");
// prepare() can fail because of syntax errors, missing privileges, ....
if(false === $stmt) {
// and since all the following operations need a valid/ready statement object
// it doesn't make sense to go on
// you might want to use a more sophisticated mechanism than die()
// but's it's only an example
die('prepare() failed: ' . htmlspecialchars($mysqli->error));
}
$rc = $stmt->bind_param('i', $_POST['id']);
// bind_param() can fail because the number of parameter doesn't match the placeholders in the statement
// or there's a type conflict(?), or ....
if(false === $rc) {
// again execute() is useless if you can't bind the parameters. Bail out somehow.
die('bind_param() failed: ' . htmlspecialchars($stmt->error));
}
$rc = $stmt->execute();
// execute() can fail for various reasons. And may it be as stupid as someone tripping over the network cable
// 2006 "server gone away" is always an option
if(false === $rc) {
die('execute() failed: ' . htmlspecialchars($stmt->error));
}
$stmt->close();
//redirect page back to view page
?>

If you want your Id be posted, it should be like this:
<form action="remove.php" method="post">
<input type="hidden" name="id" value="<?php echo (int)$row['id']; ?>">
<input type="submit" value="Remove Entry" />
</form>
Post a hidden field with the name id and the value $row['id'].
And you should take care of the comments above to avoid mysql-injection in your php.

Related

POST data not sending

UPDATE
Added all the code for the img upload as well as adding to the DB.
The output of print_r($_POST); :Array ( [prodName] => Test Product [prodPrice] => 100 [prodDescript] => Test description [submit] => UPLOAD )
Also the prodID col is auto increment.
Building off an image uploader you all so graciously helped me with, I am now trying to get the rest of this form to work. I am sending the data via POST but none of the info is being sent. I have verified the images upload, via the $_FILES array, but nothing is coming through in the $_POST data
I know my hosting service allows $_POST because I have another form that works perfectly with it. I cannot get to seem to get any errors to point me in the right direction. So once again. I come to you wonderful people.
<form action="inventory_add.php" method="POST" enctype="multipart/form-data">
<label>Product Name: </label>
<input type="text" name="prodName" id="prodName">
<br>
<label>Product Price: </label>
<input type="text" name="prodPrice" id="prodPrice">
<br>
<label>Product Description</label><br>
<textarea name="prodDescript" width="200px" id="prodDescript"></textarea>
<br>
Select Image Files to Upload:
<br>
<input type="file" name="upload[]" multiple >
<input type="submit" name="submit" value="UPLOAD">
</form>
Some of the code from inventory_add.php:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$servername = "**********";
$username = "**********";
$password = "***********";
$dbname = "************";
$prod_name = $_POST['prodName'];
$prod_price = $_POST['prodPrice'];
$prod_descript = $_POST['prodDescript'];
print_r($_POST);
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
if(isset($_FILES['upload'])){
$total = count($_FILES['upload']['name']);
for( $i=0 ; $i < $total ; $i++ ) {
$tmpFilePath = $_FILES['upload']['tmp_name'][$i];
if ($tmpFilePath != ""){
$newFilePath = "images/prod/" . $_FILES['upload']['name'][$i];
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
$img_names = implode(",",$_FILES['upload']['name']);
}
}
}
$prodID = $_SESSION['curcount'] + 1;
$sql = "INSERT INTO `inventory` (`prodId`, `prodTitle`, `prodDescript`, `prodCost`, `prodImages`) VALUES (' '," . $prod_name. "," . $prod_descript . "," . $prod_price ."," .$img_names.")";
if ($conn->query($sql) === TRUE) {;
// header('location:http://nerdsforhire.pnd-productions.com/shopmgr.php');
} else {
echo 'There was an issue adding this item.';
};
}
}
} else {
echo "Failed";
}
Would hope this would update the database... yet it is not. I keep getting "There was an issue adding this item."
UPDATE based on our conversation below, and the code above, I think the issue is in your SQL not your PHP. I suggest adding mariadb to your question.
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = 'INSERT INTO `inventory` ( `prodTitle`, `prodDescript`, `prodCost`, `prodImages`) VALUES (?,?,?,?)' ;
$stmt = $conn->prepare($sql)
$stmt->bind_param("ssss", $prod_name, $prod_descript, $prod_price, $img_names);
$stmt->execute()
if($stmt->affected_rows > 0) {
//header("location:https://sample.com"); #affected_rows > 0 so row was inserted
} else {
echo 'There was an issue adding this item.'; #failed to insert;
}
That should solve the issue. It is a prepared statement that will handle the issue with unescaped commas in the string as well as prevent SQL injection. Because prodId is auto increment, you don't need it in your statement, at least in MySQL you don't. The "ssss" part of the statement is assuming you are passing string values to the Db. Possible data types to be passed are:
i - integer
d - double
s - string
b - blob
See WC3Schools for more about php and prepared statements.

Trouble with PHP updating a database

Can I please have some help with a problem I'm having updating a mysql database with PHP.
I'm sorry to ask a question that has been asked a lot of times before, it's just driving me a bit nuts, and I've looked through similar questions but the answers don't seem to help with my problem.
I'm using two files, an admin page (admin.php) to edit content with, and an update file that is meant to update the database when the submit button is pressed.
Everything seems to be working fine, the values are being posted to the update.php page (I can see them when I echo them out) but it wont update the database.
If anyone can please point me in the right direction or tell me what I'm doing wrong I'd be very grateful!
Thank you very much:)
This is my admin.php page;
<head>
<?php
/*
Check to see if the page id has been set in the url.
If it has, set it as the $pageid variable,
If it hasn't, set the $pageid variable to 1 (Home page)
*/
if (isset($_GET['pageid'])) {
$pageid = $_GET['pageid'];
}
else {
$pageid = '1';
}
//Database connection variables
$servername = "localhost";
$username = "root";
$password = "";
$database = "cms";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Get information from the database
$sql = "SELECT title, sub_title, tab1, tab2, tab3, content FROM data WHERE id='$pageid'";
$result = $conn ->query($sql);
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc()) {
$conn->close();
//Store database information in variables to display in the form
$title = $row["title"];
$sub_title = $row["sub_title"];
$tab1 = $row["tab1"];
$tab2 = $row["tab2"];
$tab3 = $row["tab3"];
$content = $row["content"];
}
} else {
echo "0 results";
}
?>
</head>
<body>
//basic navigation
Page 1 | Page 2 | Page 3
<form action="update.php" method="post" name="adminform">
<input type="hidden" name="pageid" value="<?php echo "$pageid";?>">
NAME:<br>
<input type="text" name="title" value="<?php echo $title;?>"><br><br>
EMAIL:<br>
<input type="text" name="sub_title" value="<?php echo $sub_title;?>"><br><br>
CONTENT:<br>
<input type="text" name="tab1" value="<?php echo $tab1;?>"><br><br>
CONTENT:<br>
<input type="text" name="tab2" value="<?php echo $tab2;?>"><br><br>
CONTENT:<br>
<input type="text" name="tab3" value="<?php echo $tab3;?>"><br><br>
CONTENT:<br>
<textarea rows="4" cols="50" name="content">
<?php echo $content;?>
</textarea>
<br><br>
<input type="submit">
</form>
</body>
And this is the update.php page;
<?php
/*Values passed from the admin form, to be used as update variables*/
if (isset($_POST['adminform']))
{
$pageid = $_POST["pageid"];
$titleu = $_POST["title"];
$sub_titleu = $_POST["sub_title"];
$tab1u = $_POST["tab1"];
$tab2u = $_POST["tab2"];
$tab3u = $_POST["tab3"];
$contentu = $_POST["content"];
}
?>
<?php
if(isset($_POST['adminform']))
{
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Update the database
$sql = "UPDATE data SET title='$titleu', sub_title='$sub_titleu', tab1='$tab1u', tab2='$tab2u', tab3='$tab3u', content='$contentu' WHERE id =='$pageid'";
$result = $conn ->query($sql);
$conn->close();
}
?>
You're using == instead of = on the where clause.
On the other hand, don't pass user values to the query without validation and sanitization if you don't want to be vulnerable to sql injection attacks.
$sql = "UPDATE data SET title='" . $conn->real_escape_string($titleu) . "', sub_title='" . $conn->real_escape_string($sub_titleu) . "', tab1='" . $conn->real_escape_string($tab1u) . "', tab2='" . $conn->real_escape_string($tab2u) . "', tab3='" . $conn->real_escape_string($tab3u) . "', content='" . $conn->real_escape_string($contentu) . "' WHERE id = " . (int)$pageid;
This will work, but is not very elegant solution. You may use prepared statements instead, to pass the correct types and prevent sql injection.
Check your DB Connections and test whether you are connected to DB or not.
Change your query as below
$sql = "UPDATE data SET title='".$titleu."', sub_title='".$sub_titleu."', tab1='".$tab1u."', tab2='".$tab2u."', tab3='".$tab3u."', content='".$contentu."' WHERE id ='$pageid'";

Easier way for button information submits (secure)

When using a button to submit an information which is prepared but you want to add a something like title to the button, so the "value" with form like :
<form action="" method="POST">
<input type="submit" name="Man" value="Man">
</form>
With the php code like this :
if (isset($_POST['Man'])) {
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "
UPDATE users
SET gender = ?
WHERE username = ?
";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('ss', $_POST['Man'], $_SESSION['username']);
$ok = $stmt->execute();
if ($ok == TRUE) {
echo "<font color='#00CC00'>Your gender has been updated.</font><p>";
} else {
echo "Error: " .$stmt->error;
}
}
This is the code, which so many people using (normal easy code with prepared statements) but there is a one mistake... If somebody change the value of Man to eg. lol , the gender in database will be set to "lol" because the value is "lol"...
I noticed this problem in so many websites and codes here, and so the way to fix this, is to pre-define the $_POST... Check answer
You need to whitelist the allowed values in an array
if (isset($_POST['Man'])) {
$allowed_values=array("Man","Women");
if(!in_array($_POST['Man'],$allowed_values)){
echo"error message";
die();
}
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "
UPDATE users
SET gender = ?
WHERE username = ?
";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('ss', $_POST['Man'], $_SESSION['username']);
$ok = $stmt->execute();
if ($ok == TRUE) {
echo "<font color='#00CC00'>Your gender has been updated.</font><p>";
} else {
echo "Error: " .$stmt->error;
}
}
One simple thing to do is to pre-define the $_POST so the value will never be changed...
with simple one line code :
$_POST['Man'] = Man;
By adding this code to your code, the value cannot be changed with html so
the result wll be still the "Man" and you are good to go.

How to insert multiple textfield?

I'm working on a project for school.
It's an invoice program but I'm stuck, can anyone help me
figure out how to get the values out of multiple textboxes /fields
and insert them in to my database.
This is what it looks like.
The user can select the amount of textfields that will be inserted in to the database.
[IMG]http://i61.tinypic.com/2sagwt4.png[/IMG]
Easy example:
<?php
$host=''; //define host
$user='xxx'; //define username
$pass='xxx'; //define password
$db_name='xxx'; //define db name
$db = new mysqli($host, $user, $pass, $db_name);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if(isset($_POST['status'])) { //code called when user sent form
$status = mysqli_escape_string($db, ($_POST['status']));
//same way to save other fields, just rename "status" to your value
$sql = "INSERT INTO /* table name here */ (status, /* define other line in DB here */) VALUES ('$status', /* define other variables to save here */)"; //save into database, see the example below
//example: $sql = "INSERT INTO mydatabase (status, email, name) VALUES ('$status', '$email', '$name')";
if ($db->query($sql) === TRUE) {
echo "Saved.";
}
else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
?>
<form enctype="multipart/form-data" action="<?php $_PHP_SELF ?>" method="POST">
<label for="status">Status: </label>
<input id="status" name="status" value="" />
//add other fields here, just rename "status" to your value
<input type="submit" name="submit" value="Send form" /></form>
It may be what you are looking for, just adapt it yourself.

can not write data into an sql table,

I am trying to write some information into an SQL database from my website using PHP. I can access the database to login, however I can not write anything to it from my website. Also, I can not view any connection errors.
Form Page:
<?php
$dbh = new PDO('mysql:host='.$hostname.';dbname='.$dbname, $user, $pass);
if (!$dbh) { die('Could not connect: ' . mysql_error()); }else echo 'connected';echo '<br>';
if(isset($_COOKIE['username']))
?>
<div id="imagel">
<img class="imagel" src="../images/logos/logo2.jpg" width="300" height="300" alt="studio table" />
</div>
<div id="textr">
<form name="tableofevents" method="post" action="adminhome.php">
Name of Event(Maximum of 83 characters): <input type="text" name="noe"/>
<br>
Event Description (Maximum of 288 characters): <input type="text" name="eventdescription"/>
<br>
Date of Event: <input type="text" name="date"/>
<br>
Ticket Price: <input type="text" name="price"/>
<br>
<input type="submit" name="submit" text="submit"/>
</form>
Processing Page:
<?php
$hostname = 'localhost';
$user='******';
$pass='***********';
$dbname='sth420';
$handler = new PDO('mysql:host='.$hostname.';dbname='.$dbname,$user,$pass);
$dbh = mysql_connect ($hostname.';dbname='.$dbname, $user, $pass);
if (!$dbh) { die('Could not connect: ' . mysql_error()); }
else echo 'connected';echo '<br>';
if(isset($_COOKIE['username']))
{
$username=$_COOKIE['username'];
$password=$_COOKIE['password'];
$sql='SELECT * FROM Users WHERE ID=:id';
$results = $handler->prepare($sql);
$results->execute([':id' => $username]);
$row = $results->fetch();
if($row!=null)
{
$pword = $row['Password'];
if($pword == $password)
{
if(isset($_POST['submit']))
{
$noe=$_POST['noe'];
$ed=$_POST['eventdescription'];
$date=$_POST['date'];
$price=$_POST['price'];
$sql='INSERT INTO ismievents ( title, evtdesc, dandt, price ) VALUES(0, :noe, :eventdescription, :date, :price)';
mysql_error()
$results = $handler->prepare($sql);
$results->execute([':noe' => $noe, ':eventdescription' => $ed, ':date' => $date, ':price' => $price]);
$handler = null;
header('Location: events.html');
}
}
}
}
if (!mysql_query($sql,$dbh))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($dbh);
require_once('adminhome.html');
?>
You are mixing PDO and mysql_connect(). That is invalid, as they are incompatible APIs. Remove all references to mysql_*() and stick only with your PDO statements. You have basically duplicated every PDO statement with an incorrect call to mysql_query() but you should have none of mysql_connect(), mysql_query(), mysql_error(), mysql_fetch_*().
Refer to the manual on PDO prepared statements to see the many examples.
I see a mismatch between column counts here. You list 4 columns, but the VALUES () list contains 5:
// Prepared statemetn looks ok...
$sql='INSERT INTO ismievents ( title, evtdesc, dandt, price ) VALUES(0, :noe, :eventdescription, :date, :price)';
// But this is meaningless here...
mysql_error()
I note also that you are using PHP 5.4 array literals like:
$results->execute([':noe' => $noe, ':eventdescription' => $ed, ':date' => $date, ':price' => $price]);
Hopefully you are actually running this code in PHP 5.4.
Really, you need to take this code back to the drawing board to purge it of the incompatibilities between PDO and mysql_*(). After that, you will be able to narrow down other problems with it.
A final note here, it is really inadvisable to store a password in $_COOKIE. On a successful login, instead store a logged in state in $_SESSION.

Categories