How to trigger a sql query by clicking a button in PHP? - php

so I am trying to make a a online shop , basically what isn't working is to execute a query when the buy clicks the "BUY" button.The query is :
$sql = mysql_query("INSERT INTO vehicles (model,owner) VALUES ('$vehid','$id')");
and the button is
<form action=\"\" method=\"post\">
<input type=\"submit\" value=\"BUY\">
</form>
The whole code :
<?php
$id = $_SESSION['SESS_MEMBER_ID'];
include ('config2.php');
$result = mysql_query("select * from shop_vehicule ORDER BY id DESC");
$result2 = mysql_query("select * from accounts where id = '$id'");
while($row = mysql_fetch_array($result2))
$credit = $row['credits'];
while($row = mysql_fetch_array($result)){
$name = $row['nume'];
$price = $row['pret'];
$left = $credit - $price;
$vehid = $row['vehid'];
echo "<p><center><b>$name</b> | $price </center>
More information about $name</p>
<div id=\"toPopup\">
<div class=\"close\"></div>
<span class=\"ecs_tooltip\">Press Esc to close <span class=\"arrow\"></span></span>
<div id=\"popup_content\"> <!--your content start-->
<p>
The $name costs $price, after you'll have $left !</p>
<form action=\"\" method=\"post\">
<input type=\"submit\" value=\"BUY\">
</form>
</div>
</div>
<div class=\"loader\"></div>
<div id=\"backgroundPopup\"></div>";
$sql = mysql_query("INSERT INTO vehicles (model,owner) VALUES ('$vehid','$id')");
}
mysql_close();
?>

Here's my attempt to help, I didn't test the codes but it should be working. Please read the comments in the codes. It explains what it does.
$id = $_SESSION['SESS_MEMBER_ID'];
/* To use PDO the following line must be included in your config2.php
define('DB_HOST', 'localhost');
define('DB_NAME', 'database');
define('DB_USER', 'username');
define('DB_PASS', 'password');
$db = new PDO('mysql:host='. DB_HOST .';dbname='. DB_NAME, DB_USER, DB_PASS);
You can either use define or put the info straight into the PDO() function but I like it when it's easy to read and modify if needed.
*/
include ('config2.php');
$query = $db->prepare("SELECT * FROM accounts WHERE id = :id"); //Please use PDO or MySQLi, MySQL is outdated and unsecure. For this example, I am using my favorite method which is PDO.
$query->execute(array(':id' => $id));
$account = $query->fetchObject(); //Since we only need one line, we're going to use fetchObject object.
$query2 = $db->prepare("SELECT * FROM shop_vehicule ORDER BY id DESC");
$query2->execute();
$vehicules = $query2->fetchAll(); //I am using fetchAll due to multiple row will be returned.
foreach ($vehicules as $row) {
echo '<p><center><b>'.$row['nume'].'</b> | '.$row['pret'].' </center>
More information about $name</p>
<div id="toPopup">
<div class="close"></div>
<span class="ecs_tooltip">Press Esc to close <span class="arrow"></span></span>
<div id="popup_content"> <!--your content start-->
<p>The '.$row['nume'].' costs '.$row['pret'].', after you\'ll have '.$account->credit - $row['pret'].' !</p>
BUY
</div>
</div>
<div class="loader"></div>
<div id="backgroundPopup"></div>';
}
// Basically what this part does is whenever the user click on the link, purchase will be set and it'll trigger the query to insert into the vehicule table then return a message if it was successful or not.
if ( isset($_GET['purchase']) ) {
$query = $db->prepare("INSERT INTO vehicles (model,owner) VALUES (':vehid',':id');");
$query->execute(array(':vehid' => $_GET['purchase'], ':id' => $id));
if ($query) {
echo 'Congratulations! You have successfully purchased the vehicule!';
} else {
echo 'An error has occured, the purchase was not complete.';
}
}

Use action=$_SERVER['PHP_SELF'] in the form tag and make a write the MySQL Insert Code in condition where isset($_POST['Buy']) is true.

you can do this in php, but in 2 different files.
The first will have the form, and the second will read the POST value and perform the query
Example(please fill missing pieces)
File 1 . php
<form action="file2.php" method="post">
<input type="hidden" value=<?php echo $vehid;?>" name="vehid">
<input type="hidden" value=<?php echo $id;?>" name="id">
<input type="submit" value="BUY">
</form>
File2.php
$vehid=$_POST['model'];
$id=$_POST['id'];
$sql = mysql_query("INSERT INTO vehicles (model,owner) VALUES ('$vehid','$id')");
For a complete tutorial see http://www.w3schools.com/php/php_mysql_insert.asp

Related

How to search based on HTML option tag

I have my search form, where the cities are fetched from the database, but how can I make the search work when I select some option? I need to get "printed" everything about all houses that are in that particular selected city
HTML Form:
<form action="./server/Search.php" method="post">
<div class="col-auto mt-5">
<select name="city" class="form-select" aria-label="Default select example ">
<option selected disabled>City</option>
<?php
$query = $conn->query("SELECT * FROM `houses`") or die(mysqli_error());
while($fetch = $query->fetch_array()){
?>
<option value=""><?php echo $fetch['city']?></option>
<?php
}
?>
</select>
</div>
<div class="col-auto mt-5">
<button type="search" name="search" class="btn btn-primary"><i class='bx bx-search-alt-2'></i></button>
</div>
</form>
Search.php
<?php
$con= new mysqli("localhost","root","","KBHestate");
$name = $_post['search'];
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con, "SELECT * FROM houses
WHERE city LIKE '%{$city}%'");
while ($row = mysqli_fetch_array($result))
{
echo $row['city'];
echo "<br>";
}
mysqli_close($con);
?>
I don't know how to connect selected option with the query. Is there any way how to handle this the best way possible?
First change in the html form, to avoid selecting columns and rows you don't need:
<?php
$query = $link->query("SELECT distinct city FROM `houses`");
while($fetch = $query->fetch_array(MYSQLI_ASSOC)){
echo "<option value='{$fetch['city']}'>{$fetch['city']}</option>\n";
}
?>
Then search.php with bind variables.
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = new mysqli("localhost","root","","KBHestate");
$name = $_POST['city'];
$query = $link->prepare("SELECT id FROM houses where city = ?");
$query->bind_param("s", $name);
$query->execute();
$query->bind_result($id);
while($query->fetch()){
echo "{$id}</br>\n";
}
?>
It seems that a few things are missing here:
The value is missing in the HTML Form so nothing gets posted
You should not use the cities name (because there are a lot of cities with problematic characters) but a numerical id for the value.
This also means that you need a seperate lookup table with cities and the city id and join this with the houses table.
">
Then your second script search.php does not use the posted value
$city_id = $_POST['city_id'];
[...]
now you can use $city_id in the query:
$result = mysqli_query($con, "SELECT * FROM houses
WHERE city_id ='{$city_id}'");
BUT in fact this is not the proper way to do it - use prepared statments instead.

Why is the last iteration given, instead of the current one?

I have some PHP & HTML code which fetches id's, names & statuses from a mysql database.
Using buttons and $_POST i'm attempting to update the MYSQL database when said the users button is clicked (it's a simple in/out board)
Here is my code
<?php
include 'confile.php';
if(isset($_POST['update'])) {
echo $_POST['update']. " "; //test to show correct name
echo $_POST['staffid']; //test to show the correct staffid << **THIS IS WHERE THE ISSUE IS**
//$incid = $_POST['staffid'];
//$sql = "SELECT status FROM staff WHERE id=$incid";
//$result = $conn->query($sql);
//echo $result; //show the status
} else {
//do nothing.
}
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
<title>Staff Board</title>
<body>
<div align="center" class="header">
<div class="header text">
<h1>Staff Board</h1>
</div>
<div class="header logo">
<img src="/assets/img/logo.gif" width="64px" height="64px">
</div>
</div>
<div id="conbox" align="center" class="content">
<hr>
<?php
//get all staff and their statuses
$sql = "SELECT id, firstname, surname, status FROM $staff ORDER BY surname ASC";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
// assign results to values
$id = $row["id"];
$firstname = $row["firstname"];
$surname = $row["surname"];
$status = $row["status"];
$fullname = $firstname . " " . $surname . " " . $id; //The $id variable will be dropped from here... it's just for testing. note, it works here, the correct ID is added to the button value
if ($status == 1) { //pick the correct color for the status
$color = "butGreen";
} else {
$color = "butRed";
}
?>
<form class="staffGrid" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="POST">
<input type="hidden" id="staffid" name="staffid" value="<?php echo htmlspecialchars($id); ?>"/> <!-- hidden input to pass the id to $_POST -->
<input type="submit" id="update" name="update" value="<?php echo htmlspecialchars($fullname); ?>"/> <!-- submit button to trigger POST -->
</form> <!-- added as per devpro & billyonecan -->
<?php
};
?>
</div>
</div>
</body>
</html>
When I first load the page, the buttons show correctly, and there is no test output at the top of the page, which I expect.
however, when I click a button, the page refreshes correctly, and shows the correct name for the button being pushed (from the echo on line 5), but the wrong staffid is given. It gives the LAST id for the while loop, instead of correct value for that button.
I had assumed that for each iteration, the values would be set for that specific element (the button)... obviously i'm incorrect here.
Why is this happening and how do I fix it?
Additional info
Confile.php has the following variables used in the code:-
$conn = new mysqli($server, $username, $password);
$staff = [Location of db table]
some output :-
echo $sql;
SELECT id, firstname, surname, status FROM inout.staff ORDER BY surname ASC
echo print_r($_POST);
Array ( [staffid] => 17 [update] => First Second 8 )
The solution was to ensure that the closing tag was present in the code, and in the correct location to prevent erroneous iteration!

Indicate the newly added user with different color or symbol or div highlighting

I want to indicate the currently newly added user through symbol or unique color, like when someone click on Save and the user that is added should be shown in a different color or highlighted at that glimpse and then disappear after refresh, something like what the stackoverflow does in commenting system.
This is my code of index.php in this page I'v form and after submitting this form I' added the user to the database and then I'v shown them in descending order
<form action="save.php" method="post">
<div class="text-center" id='input_tag'>
<input type="text" name="name" id= 'input'>
<input type="submit" name="submit" class="btn btn-dark " id = "button" value="Save">
</div>
</form>
<div class="container">
<div class="row">
<div class="col-md-4">
<table width="100" class="table" id = 'tb'>
<?php
$connect = mysqli_connect('localhost','root','root','user');
$query = "SELECT name from userdata order by id DESC";
$run = mysqli_query($connect,$query);
while($row = mysqli_fetch_array($run))
{
echo "<tr>";
echo "<td>".$row['name']."<td>";
echo "</tr>";
}
?>
</table>
</div>
</div>
</div>
This is save.php where the user are added to DB and then redirected to the index.php page
$connect = mysqli_connect('localhost', 'root' ,'root' ,'user');
if($connect){
if(isset($_POST['submit']))
{
$name = $_POST['name'];
$query = "INSERT INTO `userdata`(`name`) values ('$name')";
if(mysqli_query($connect,$query)){
header('location:index.php');
}
}
}
else{
echo "not connected";
}
You can achieve this with simple CSS and JS.
Change the header function in save.php to
header('location:index.php?added=1');
Add CSS style to index.php
<style type="text/css">
tr:last-of-type {
transition: .7s background;
}
</style>
At the end of index.php add the following
<?php
if (isset($_GET['added'])){
print '<script type="text/javascript">
document.querySelector("tr:first-of-type").style.background = "red";
setTimeout(function() {document.querySelector("tr:first-of-type").style.background = unset"},2000);
</script>';
}
?>
I'm assuming that the new user is going to be displayed at first.
If you want to display the user differently the first time, then you will need
some sort of flag that says if the user has been shown yet or not.
At the time you insert the user, set the didShow flag to false.
When you show the user, check the flag and if false, show the user
with the symbol and set the didShow flag to true.
When you show the user, if the didShow flag is false, show the
user without the symbol.
Add a new column named didShow to your database. Set it to default to 0 (false).
Change the query like this:
$query = "SELECT id, name, didShow from userdata order by id DESC";
In the loop, use different formatting and update the rows that have to be updated.
$run = mysqli_query($connect, $query);
$style = 'style="color:#ccc"';
while($row = mysqli_fetch_array($run))
{
echo "<tr>";
if ( $row['didShow'] == 0 ) {
echo "<td><span {$style}>".$row['name']."</span><td>";
$updateQuery = "UPDATE `userdata` SET didShow=1 WHERE id = {$row['id']}";
mysqli_query($connect, $updateQuery);
} else {
echo "<td>".$row['name']."<td>";
}
echo "</tr>";
}

Use php/MySQL result in new query

I've searched around and haven't found anything similar, but it sounds like it should be pretty easy...
I have a search query that searches for a specific userID and displays that information for that user. However, I have one field (let's call it "favorite color" for this example) that will need to be manually updated frequently. So, I want to Search by userID, display the results, somehow re-use the original userID, and update the "favorite color" by the user entry. The part I can't figure out yet is how to store/re-use the userID.
The only way I can get it to work is ->
Search for userID, display results and also populate two new text form fields with original userID as well as "favorite color" to be submitted again by a new UPDATE query. But I don't want the userID to be a text form field, I just want to store the variable use it again.
Does that make sense? =)
Here is a sample of my current code. BTW, it works 100% this way right now, just need to figure out how to store the variable instead of using it again in a text box where I submit the UPDATE query.
<div class="searchBox">
<form method="POST" name="search" action="filter-update.php" class="form-wrapper cf">
<input type="text" name="querySearch" placeholder="User ID" required>
<button type="submit">Search</button>
</form>
</div>
<div id="results">
<?php
if (isset($_POST['querySearch'])){
$query = $_POST['querySearch'];
$min_length = 8;
if(strlen($query) >= $min_length){
$query = htmlspecialchars($query);
$query = mysqli_real_escape_string($conn, $query);
$sql = "SELECT * FROM sites WHERE userID = $query";
$raw_results = mysqli_query ($conn, $sql) or die ('error getting data from database');
if(mysqli_num_rows($raw_results) > 0){
while ($results = mysqli_fetch_array($raw_results)) {
echo "<div class='title'>User ID:</div><div class='info'>".$results['userID']."</div>";
echo "<div class='title'>Name:</div><div class='info'>".$results['name']."</div>";
echo "<div class='title'>Fav Color:</div><div class='info'>".$results['favColor']."</div>";
$userID = $results['userID'];
}
}
else { // if there is no matching rows do following
echo "No results";
}
}
else{ // if query length is less than minimum
echo "<br>Minimum length is ".$min_length;
}
}
?>
</div>
<div class="searchBox">
<form method="POST" name="filterUpdate" action="filter-update.php" class="form-wrapper cf">
<input type="text" name="UserID" value="<?php echo $userID;?>" required><br><br><br>
<input type="text" name="favColor" placeholder="New favColor here..." required>
<button type="submit">Update</button>
</form>
</div>
<div id="results">
<?php
if (isset($_POST['filterUpdate'])){
$queryFilter = $_POST['filterUpdate'];
$userID = $_POST['userID'];
$min_length = 1;
if(strlen($queryFilter) >= $min_length){
$queryFilter = htmlspecialchars($queryFilter);
$userID = htmlspecialchars($userID);
$queryFilter = mysqli_real_escape_string($conn, $queryFilter);
$userID = mysqli_real_escape_string($conn, $userID);
$sql = "UPDATE sites SET favColor = '$queryFilter' WHERE userID = '$userID'";
$raw_results = mysqli_query ($conn, $sql) or die ('error getting data from database');
}
else{ // if query length is less than minimum
echo "<br>Minimum length is ".$min_length;
}
}
?>
</div>
You can try either of this:
Hidden Field:
<input type="hidden" name="UserID" value="<?php echo $userID;?>">
Session:
$_SESSION['userID'] = $userID;
Don't know if this will work, but you can put the $userID above all the codes(like a global var).

Deleting something in a mysqli database with a button?

So I'm just making a simple program that puts names into a database. I got that part down, I can enter a name into a form, then display it on the page, but now I'd like to know how to delete them from the database, and no longer show them on the page.
I added a button next to each name that triggers the third if statement (with the commented out query), and from what I can tell it's best to run a query based on the element's id (my primary key that auto increments), but I have no idea how to get the id from the element who's button I'm clicking on.
How do I get the id from one of the elements in my while loop? Or if there's a better way to delete them, what's that?
if (mysqli_connect_errno()) {
die('could not connect');
}
if (isset($_POST['first_name'], $_POST['last_name'])){
$first_name = trim($_POST['first_name']);
$last_name = trim($_POST['last_name']);
$putitin = mysqli_query($db, "INSERT INTO names (first_name, last_name) VALUES ('$first_name', '$last_name')");
}
if (isset($_POST['del'])){
//$takeitout = mysqli_query($db, "DELETE FROM names WHERE id = ");
}
?>
<html>
<head>
</head>
<body>
<form action='' method='post'>
<div>
<label for "first_name">First name</label>
<input type="text" name="first_name">
</div>
<div>
<label for "last_name">Last name</label>
<input type="text" name="last_name">
</div>
<div>
<input type="submit" value="Insert">
</div>
</form>
<hr>
<?php
$resultset = $db->query('SELECT * FROM names');
if($resultset->num_rows != 0){
while($rows = $resultset->fetch_assoc()) {
$fname = $rows['first_name'];
$lname = $rows['last_name'];
$id = $rows['id'];
echo "<form action='' method='post'><p>Name: $fname $lname $id<input type='submit' name='del'></form></p>";
}
} else {
echo 'No results';
}
?>
</body>
</html>
This is one way.
change your html part to
<form action='' method='post'>
<input type='hidden' name='id' value='$id' />
<p>Name: $fname $lname $id
<input type='submit' name='del' value=''>
</form></p>
and your php
if (isset($_POST['del'])){
$id = $_POST['id'];
$takeitout = mysqli_query($db, "DELETE FROM names WHERE id = '$id'");
}
Note:
What you can do is to put all your input fields inside your while loop. Then assign values to each of them, but we have to use array to store them accordingly.
We can use checkbox to store the IDs.
What will happen, is user can select from the list of names they wanted to delete by ticking the corresponding checkbox, then pressing the Delete button below.
Your code
<form action="" method="POST">
<?php
$resultset = $db->query('SELECT * FROM names');
if($resultset->num_rows != 0){
while($rows = $resultset->fetch_assoc()) {
$fname = $rows['first_name'];
$lname = $rows['last_name'];
$id = $rows['id'];
echo '<input type="checkbox" name="id[]" value="'.$id.'">'.$fname.' '.$lname.'<br>';
} /* END OF WHILE LOOP */
?>
<input type="submit" value="Delete" name="delete">
</form>
And your PHP that will process the form:
<?php
if(isset($_POST["delete"])){
$counter = count($_POST["id"]);
for($x = 0; $x<$counter; $x++){
if(!empty($_POST["id"][$x])){ /* CHECK IF AN ITEM IS SELECTED */
/* DELETE QUERY */
if($stmt = $db->prepare("DELETE FROM names WHERE id = ?")){
$stmt->bind_param("i",$_POST["id"][$x]);
$stmt->execute();
$stmt->close();
} /* END OF PREPARED STATEMENT */
} /* END OF IF; CHECKING IF IT IS SELECTED */
} /* END OF FOR LOOP */
} /* END OF ISSET DELETE */
?>

Categories