im trying to match my textfield input of a "coupon_code" to a value in a sql table. i have three files that connect to each other. also, there should be an alert if the texfield matches.
HTML: (membership.php)
<?php
session_start();
require_once('membership.vc.php');
?>
<form>
<div class="form-row">
<div class="col col-md-8">
<input type="text" class="form-control" aria-describedby="sizing-addon1" name="promocode3" placeholder="ENTER PROMO CODE">
</div>
<div class="col col-md-4">
<input type="submit" class="btn color-white mwc-orange-background-color" name="redeem" value="REDEEM">
</div>
</div>
</form>
PHP: (membership.vc.php)
<?php
require_once($routePath . "_mc/PromoCode.mc.php");
$mcPromoCode = new PromoCode_MC();
if (isset($_POST['redeem']) && $_POST['redeem'] == 'REDEEM'){
$pcode3_txtfield = $_POST['promocode3'];
$rowpcode3 = $mcPromoCode->SelectPromoCode3($db, $p3id);
$pcode3 = $rowpcode3['coupon_code'];
if ($pcode3_txtfield == $pcode3 ){
echo "<script>
alert('There are no fields to generate a report');
window.location.href='admin/ahm/panel';
</script>";
}
}
?>
SQL Function: (PromoCode.mc.php)
<?php Class PromoCode_MC {
public function SelectPromoCode3($db, $p3id) {
$stmt = $db->prepare(
" SELECT *
FROM mywhitecard.promocode_3
WHERE p3id = :p3id ");
$stmt->bindValue(':p3id', $p3id, PDO::PARAM_INT);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
return $row; } } ?>
$pcode3 should get the column and $pcode3_txtfield should get the textfield input, which part did i do wrong? since there is no alert popup.
UPDATE: tried to do what the comments said, i thought using the primary key of the table will work but still no effect
UPDATE: i tried:
<?php Class PromoCode_MC {
public function SelectPromoCode3($db, $pcode3_txtfield) {
$stmt = $db->prepare(
" SELECT *
FROM mywhitecard.promocode_3
WHERE pcode3_txtfield = :coupon_code ");
$stmt->bindValue(':pcode3_txtfield', $pcode3_txtfield, PDO::PARAM_INT);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
return $row; }
} ?>
no effect
Related
I have a form that outputs images and their related titles and tags via a while loop, and at the bottom of this form I have the option to delete an image.
Because the input elements inside the form produce an array of values, when deleting an image I need to run the PDO statements and PHP glob methods that delete the images from their folders inside a parent foreach loop.
I cannot get this to work though. Without the foreach loop I'm getting the PHP Array to string conversion error, which I understand/expect. This error throws on the line $stmt->bindParam(':image_id', $image_id); in the second section of code below.
I think I need to wrap the code from in-between the // ---- START FOREACH ? and // ---- END FOREACH ? comments in an associative foreach loop, but I can't work how to do this in terms of the key/value pairs?
Any help would be really appreciated.
Output onto page (the issue is in the block of code after this)
<?php
isset($_REQUEST['username']) ? $username = $_REQUEST['username'] : header("Location: login.php");
$user_id = $_SESSION['logged_in'] ?? header("Location: login.php");
?>
<form method="post" enctype="multipart/form-data">
<?php
$stmt = $connection->prepare("SELECT * FROM lj_imageposts WHERE user_id = :user_id");
$stmt->execute([
':user_id' => $user_id
]);
while ($row = $stmt->fetch()) {
$db_image_id = htmlspecialchars($row['image_id']);
$db_image_filename = htmlspecialchars($row['filename']);
$db_image_ext = htmlspecialchars($row['file_extension']);
?>
<div class="upload-details-component">
<div>
<img src="project/images-lib/image.jpg">
</div>
<div class="edit-zone">
<div class="form-row">
<label for="upload-details-title">Image Title</label>
<input id="upload-details-title" type="text" name="image-title[]">
</div>
<div class="form-row upload-details-form-row">
<label for="upload-details-tags">Comma Separated Image Tags</label>
<textarea name="image-tags[]"></textarea>
</div>
<div class="form-row">
<input type="hidden" name="username" value="<?php echo $username;?>">
<input type="hidden" name="image-id[]" value="<?php echo $db_image_id;?>">
<button name="upload-details-delete[]">DELETE</button>
</div>
</div>
</div>
<?php } ?>
<div class="form-row upload-details-submit-row">
<button type="submit" name="upload-submit">COMPLETE UPLOAD</button>
</div>
</form>
Deleting An Image
<?php
if(isset($_POST['upload-details-delete'])) {
$loggedInUser = $user_id;
$imagesLibrary = 'images-lib/';
$imagesDownload = 'images-download/';
$image_id = $_POST['image-id'];
try {
$sql = "DELETE FROM `lj_imageposts` WHERE image_id = :image_id AND user_id = :user_id";
$stmt = $connection->prepare($sql);
// ---- START FOREACH ?
$stmt->bindParam(':image_id', $image_id);
$stmt->bindParam(':user_id', $loggedInUser);
$stmt->execute();
// delete image files from 'images-lib' folder
foreach(glob($imagesLibrary . $db_image_filename . '-{500,750,1000,1500}' . '.' . $db_image_ext, GLOB_BRACE) as $i) {
unlink($i);
}
// delete files from 'images-download' folder
foreach(glob($imagesDownload . $db_image_filename . '.' . $db_image_ext) as $i) {
unlink($i);
}
// ---- END FOREACH ?
header("Location: upload-details.php?username={$db_username}");
exit;
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
}
?>
This is some messy code, and there's a lot you can do to clean it up. With regards to your core problem, the fix is simple. According to the HTML spec:
A button (and its value) is only included in the form submission if the button itself was used to initiate the form submission.
In other words, a button is not submitted unless it is clicked. Simply adding the ID as value to each delete button should make things quite simple. You know you'll only get one value sent with that button's name.
But first, you need to separate your logic from your presentation. Ideally the HTML should be in a separate file, but we'll stick them together here for ease, moving all the PHP code to a separate block. Use of alternative control structure syntax and short echo tags will clean things up nicely in your HTML.
You are abusing operators in your first two lines when a simple conditional statement would be more understandable.
It's not clear what your escape() function does, but use of htmlspecialchars() is all that's needed for HTML display.
The id attribute of an element must be unique in the document, and must be present for the for attribute of the <label> element to work properly. Typically a database ID is used to make the values unique.
Where do you think $db_image_filename is coming from in the delete code? You've defined it on the display page inside a loop, and then aren't submitting it which is obviously not going to be of any help. So you'll need to fetch it again here. (A better strategy would have been to name the files with the database ID so you could just delete image_XXX_.* where XXX is your id.)
Never echo database errors to your users. At best it confuses them; at worst it gives them details of your code and database schema that can be used in an attack.
<?php
// avoid gross misuse of the ternary and null coalesce operators
if (empty($_REQUEST["username"]) || empty($_SESSION["logged_in"])) {
header("Location: login.php");
exit;
}
// why is this not in the session?
$username = $_REQUEST['username'];
// this array key should have a better name (like "user_id" for example)
$user_id = $_SESSION['logged_in'];
if(isset($_POST['upload-details-delete'])) {
// delete files and database entries
$imagesLibrary = 'images-lib/';
$imagesDownload = 'images-download/';
// get image ID from the button value
$image_id = $_POST['upload-details-delete'];
try {
// get the file info before we delete the entry
$sql = "SELECT * FROM lj_imageposts WHERE image_id = ? AND user_id = ?";
$stmt = $connection->prepare($sql);
$stmt->execute([$image_id, $user_id]);
$fileinfo = $stmt->fetch(\PDO::FETCH_ASSOC);
// delete the entry
$sql = "DELETE FROM `lj_imageposts` WHERE image_id = ? AND user_id = ?";
$stmt = $connection->prepare($sql);
$stmt->execute([$image_id, $user_id]);
// delete image files from 'images-lib' folder
$pattern = $imagesLibrary . $fileinfo["image_filename"] . "-{500,750,1000,1500}" . "." . $fileinfo["image_ext"];
foreach(glob($pattern, GLOB_BRACE) as $i) {
unlink($i);
}
// delete files from 'images-download' folder
$pattern = $imagesLibrary . $fileinfo["image_filename"] . "." . $fileinfo["image_ext"];
foreach(glob($pattern) as $i) {
unlink($i);
}
} catch (\Throwable $e) {
error_log($e->getMessage());
// don't echo database errors to your users
http_response_code(500);
echo "Database Error";
exit;
}
}
if (isset($_POST["upload_submit"])) {
// do your upload stuff
}
try {
$stmt = $connection->prepare("SELECT * FROM lj_imageposts WHERE user_id = ?");
$stmt->execute([$user_id]);
// fetch all the rows into a single array
$data = $stmt->fetchAll(\PDO::FETCH_ASSOC);
// escape the data for html display
foreach ($data as &$row) {
$row = array_map('htmlspecialchars', $row);
}
} catch (\Throwable $e) {
$data = [];
}
?>
<form method="post" enctype="multipart/form-data">
<div class="upload-details-component">
<div>
<img src="project/images-lib/image.jpg">
</div>
<?php foreach ($data as $row): ?>
<div class="edit-zone">
<div class="form-row">
<label for="upload-details-title<?=$row["image_id"]?>">Image Title</label>
<input id="upload-details-title<?=$row["image_id"]?>" type="text" name="image-title[]" value="<?=$row["image_title"]?>"/>
</div>
<div class="form-row upload-details-form-row">
<label for="upload-details-tags<?=$row["image_id"]?>">Comma Separated Image Tags</label>
<textarea id="upload-details-tags<?=$row["image_id"]?>" name="image-tags[]"><?=$row["image_tags"]?></textarea>
</div>
<div class="form-row">
<input type="hidden" name="image-id[]" value="<?=$row["image_id"]?>"/>
<button name="upload-details-delete" value="<?=$row["image_id"]?>">DELETE</button>
</div>
</div>
<?php endforeach ?>
</div>
<div class="form-row upload-details-submit-row">
<input type="hidden" name="username" value="<?=$username?>"/>
<button name="upload-submit">COMPLETE UPLOAD</button>
</div>
</form>
<div class="row">
<?php
$connection = mysqli_connect('localhost','root','','product-store');
if(isset($_POST['search'])) {
$searchKey = $_POST['search'];
$sql = "SELECT * FROM products WHERE code_no LIKE '%$searchKey%'";
} else {
$sql = "SELECT * FROM products order by code_no desc";
$searchKey = "";
}
?>
<form action="tabledata.php" method="POST">
<div class="col-md-12 col-sm-12 col-xs-12">
<input type="text" name="search" class="form-control" placeholder="Search By Code" value="<?php echo $searchKey; ?>" >
</div>
<br>
<div class="input-group">
<button class="btn btn-success">Search</button>
</div>
<br>
</form>
<br>
<br>
</div>
</div>
</div>
</div>
$(document).ready(function(){
$("#search").keyup(function() {
var query = $(this).val();
if (query != "") {
$.ajax({
url:"tabledata.php",
method:"POST",
data:{query:query},
success:function(data)
{
$('#result').html(data);
}
});
}
$('#searchKey').keyup(function(){
var search = $(this).val();
if(search != '')
{
load_data(search);
}
else
{
load_data();
}
});
});
you are missing the id in the input field
<input type="text" id="search" name="search" class="form-control" placeholder="Search By Code" value="<?php echo $searchKey; ?>" >
You are not only missing the id in the input field but you also never execute the query in your php code and fetch the result. And sql injection is possible, sanitize your $searchKey or use prepared statements.
Maybe you can alse place the search query in a differant php file, and create there the html you whant to return to your ajax function.
Maybe this will help:
Create a new php file for your ajax search function like searchData.php
<?php //searchData.php
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['query'])) {
$connection = mysqli_connect('localhost','root','','product-store');
$searchKey = $_POST['query']; // Needs to be sanitized to prevent sql injections
$sql = mysqli_query($connection, "SELECT * FROM products WHERE code_no LIKE '%$searchKey%'");
if (mysqli_num_rows($sql) > 0) {
// Fetch the rows
$rows = mysqli_fetch_array($sql, MYSQLI_ASSOC);
$html = '';
// Loop through all the rows
foreach ($rows as $row) {
// Create here your html you want to return to your ajax function
}
echo $html;
} else {
// No results, echo html/ text to the ajax function to inform the user
}
}
Change the url in your ajax function to searchData.php the ajax function will then get all the text/html you echo in this file
I am retrieving values from the database into the form for update, on the press of submit button.
The values do get retrieved but update process fails without any error.
Here's the code:
<?php
session_start();
$username=$_SESSION['uname'];
$cn=mysqli_connect("localhost", "root", "", "testdb");
// Define variables and initialize with empty values
$course = $category = "";
$title = $descp = "";
// Processing form data when form is submitted
if(isset($_POST["pid"]) && !empty($_POST["pid"])){
// Get hidden input value
$pid = $_POST["pid"];
// Check input errors before inserting in database
if(empty($course) && empty($category) && empty($title) && empty($descp)){
// Prepare an update statement
$sql = "UPDATE posts SET course=?, category=?, title=?, descp=? WHERE pid=?";
if($stmt = mysqli_prepare($cn, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "ssssi", $param_course, $param_category, $param_title, $param_descp, $param_pid);
// Set parameters
$param_course = $course;
$param_category = $category;
$param_title = $title;
$param_descp = $descp;
$param_pid = $pid;
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Records updated successfully. Redirect to landing page
header("location: CAposts.php");
exit();
} else{
echo "Something went wrong. Please try again later.";
}
// Close statement
mysqli_stmt_close($stmt);
}
}
// Close connection
mysqli_close($cn);
} else{
// Check existence of id parameter before processing further
if(isset($_GET["pid"]) && !empty(trim($_GET["pid"]))){
// Get URL parameter
$pid = trim($_GET["pid"]);
// Prepare a select statement
$sql = "SELECT * FROM posts WHERE pid = ?";
if($stmt = mysqli_prepare($cn, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "i", $param_pid);
// Set parameters
$param_pid = $pid;
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
$result = mysqli_stmt_get_result($stmt);
if(mysqli_num_rows($result) == 1){
/* Fetch result row as an associative array. Since the result set contains only one row, we don't need to use while loop */
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
// Retrieve individual field value
$pid = $row['pid'];
$uname = $row['uname'];
$course = $row['course'];
$category = $row['category'];
$pdate = $row['pdate'];
$title = $row['title'];
$descp = $row['descp'];
} else{
// URL doesn't contain valid id. Redirect to error page
header("location: CAposts.php");
exit();
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
// Close connection
mysqli_close($cn);
} else{
// URL doesn't contain id parameter. Redirect to error page
header("location: CAposts.php");
exit();
}
}
?>
<html>
<head>
<title>IMEDTalks-Post-
<?php echo $title;?>
</title>
<link href="./css/bootstrap.min.css" rel="stylesheet" />
<script src="./scripts/jquery-3.3.1.min.js"></script>
<script src="./scripts/bootstrap.min.js"></script>
<style>
/* Make the image fully responsive */
.carousel-inner img {
width: 100%;
height: 30%;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="page-header">
<h2 class="text-center">Update Post</h2>
</div>
<p class="text-center">Please edit the input values and submit to update the post.</p>
<form action="<?php echo htmlspecialchars(basename($_SERVER['REQUEST_URI'])); ?>" method="post">
<div class="form-group">
<div class="row">
<label class="col-form-label col-md-1 offset-3" for="course">Course:</label>
<div class="col-md-2">
<select name="course" class="form-control" required>
<option value="<?php echo $course;?>" selected>
<?php echo $course;?>
</option>
<option value="">Choose any:</option>
<option value="comp">Comp</option>
<option value="theo">Theory</option>
</select>
</div>
<label class="col-form-label col-md-1" for="category">Category:</label>
<div class="col-md-3">
<select name="category" class="form-control" required>
<option value="<?php echo $category;?>" selected>
<?php echo $category;?>
</option>
<option value="">Choose any:</option>
<option value="plang">Programming Language</option>
<option value="web">Web Technologies</option>
<option value="maths">Mathematics and Statistics</option>
<option value="others">Others</option>
</select>
</div>
</div>
</div>
<div class="form-group row">
<label for="title" class="col-form-label col-md-2">Title:
</label>
<div class="col-md-10">
<input type="text" class="form-control" value="<?php echo $title;?>" name="title" required>
</div>
</div>
<div class="form-group row">
<label for="desc" class="col-form-label col-md-12">Description:
</label>
<div class="col-md-12">
<textarea class="form-control" name="descp" rows="20" required><?php echo $descp;?></textarea>
</div>
</div>
<input type="hidden" name="pid" value="<?php echo $pid;?>" />
<div class="form-group row">
<div class="col-md-4 offset-4">
<a href="CAposts.php"><button type="button" name="cancel"
class="btn-lg btn-danger">Cancel</button></a>
</div>
<div class="col-md-4">
<button type="submit" name="update" class="btn-lg btn-success">Submit</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
PS:
pid is being bought from the previous page where the data is listed in table format, and on the click of the button, that data/post gets loaded into the form for editing using the pid, which is primary key in my database table.
using bootstrap 4.
Edited after first comments.
You have 5 columns in your query but you only bind 4 of them, so you forgot an s
$sql = "UPDATE posts SET course=?, category=?, title=? descp=? WHERE pid=?";
if($stmt = mysqli_prepare($cn, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "sssi", $param_course, $param_category, $param_title, $param_descp, $param_pid);
Here a cleaner code for your update:
$stmt = $conn->prepare("UPDATE posts SET course=?, category=?, title=?, descp=? WHERE pid=?");
$stmt->bind_param("ssssi", $course, $category, $title, $descp, $pid);
$stmt->execute();
I just saw that you are trying to display all your data from DB using
// Prepare a select statement
$sql = "SELECT * FROM posts WHERE pid = ?";
if($stmt = mysqli_prepare($cn, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "i", $param_pid);
// Set parameters
$param_pid = $pid;
And also, the value of all your form is using these informations fetched from DB, which is nothing since, i just can't understand. You are trying to fetching all your data using a variable which comming from data of DB itself...
Try something, change the hidden form for your ID and use this (if you have data in db using id 1)
<input type="hidden" name="pid" value="1" />
I'm new to PHP. I'm trying to display search result based on user query. My issue is that I'm not getting all other similar search results (only the exact results are showing). Is it the right method I'm implementing from security point of view? Thanks in advance.
define('HOST','localhost');
define('USER','root');
define('PASSWORD_HOST','');
define('DATABASE','test');
if(defined('HOST') && defined('USER') && defined('PASSWORD_HOST') && defined('DATABASE')){
$conn = mysqli_connect(HOST, USER, PASSWORD_HOST, DATABASE);
}else{
die(connection_failed.mysqli_connection_error());
}
Here is HTML
<div class="container">
<div class="row">
<div class="col-sm-12">
<form action="" method="POST">
<h4>Search By</h4>
<input type="text" name="delName"/>
<button type="submit" name="submit">search</button>
</form>
</div>
</div>
</div>
Here is PHP
if(isset($_POST['submit'])){
$delName = "%{$_POST['delName']}%";
$stmt =$conn->prepare("SELECT id, delName, medName, contact1, contact2, address, pin, creditLimitDealer FROM dealerentrytable WHERE delName LIKE ?");
$stmt->bind_param("s", $delName);
$stmt->execute();
$stmt->bind_result($id, $delName, $medName, $contact1, $contact2,$address,$pin,$creditLimitDealer);
while ($stmt->fetch()) {
echo "<table>";
echo "<tr><td>ID: $id</td>";
echo "<td>delName: $delName</td>";
echo "<td>medName: $medName</td>";
echo "<td>contact1: $contact1</td>";
echo "<td>contact2: $contact2</td>";
echo "<td>address: $address</td>";
echo "<td>pin: $pin</td>";
echo "<td>creditLimitDealer: $creditLimitDealer</td></tr>";
echo "</table>";
}
$stmt->close();
}
?>
I'm trying to use a form to update a sql table by first getting its data (editrower.php) and setting that as values in the form, then using the form to update the table (update_contactrequest.php) but it returns saying the rower was updated yet the table does not update.
editrower.php
<?php
require('login.php');
?>
<?php
include 'php/mysql_connect.php';
if(isset($_GET['id'])){
$q = $db->prepare('SELECT * FROM rowercontacts WHERE id=:id LIMIT 1');
$q->execute(array(':id'=>$_GET['id']));
$row = $q->fetch(PDO::FETCH_ASSOC);
if($row){
echo '
<form method="post" action="php/update_contactrequest.php"><div class="col-xs-9 col-md-6 col-lg-6">
<div class="form-group">
<input type="hidden" name="id" id="id" value="'.$_GET['id'].'">
<label for="firstname">First Name</label>
<input type"text" class="form-control" name="firstname" placeholder="First Name" value="'.$row['firstname'].'" />
</div>
<div class="form-group">
<label for="lastname">Last Name</label>
<input type="text" class="form-control" name="lastname" placeholder="Last Name" value="'.$row['lastname'].'" />
</div>
<br><br>
<br><br>
<input type="submit" class="btn btn-default" value="Update" />
</div></form>
';
}
else{
echo 'No rower found';
}
}
else{
echo 'No rower found';
}
?>
update_contactrequest.php:
<?php
session_start();
if($_SESSION['loggedIn'] == true){
$rower_id= $_POST['id'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
// connection to the database
try {
$bdd = new PDO('mysql:host=localhost;dbname=home','username','password');
} catch(Exception $e) {
exit('Unable to connect to database.');
}
// insert the records
$sql = "UPDATE rowercontacts SET firstname=:firstname, lastname=:lastname WHERE id=:rower_id";
$q = $bdd->prepare($sql);
if($q->execute(array(':firstname'=>$firstname, ':lastname'=>$lastname, ':rower_id'=>$id))){
echo '<script type="text/javascript">alert("Rower Updated.");location.href="../rowerlist.php";</script>';
}
else{
echo '<script type="text/javascript">alert("Something went wrong...");location.href="../rowerlist.php";</script>';
}
}
?>
With $q->rowCount(). Prepared statements will return the number of affected rows.
If the query itself is error free and executes fine, you need the affected rows.
$q = $bdd->prepare($sql);
if($q->execute(array(':firstname'=>$firstname, '...'))){
$updRows = $q->rowCount();
if($updRows==0){
echo '<script type="text/javascript">alert("Affected Rows = 0 !!!");location.href="../rowerlist.php";</script>';
}
else{
echo '<script type="text/javascript">alert("Rows affected : '.$updRows.'");location.href="../rowerlist.php";</script>';
}
}
else{
echo '<script type="text/javascript">alert("Something went wrong...");location.href="../rowerlist.php";</script>';
}
Over 70% of update queries with 0 affected rows are due to an incorrect WHERE the rest comes from the attempt to replace a record with exactly the same values that already exist.
The first thing I do in such a case, I let my query as readable text display.
With $q->debugDumpParams(); you get that query array.
WHERE id = null is usually not what anyone expected.
To your problem I'm sure you can find the wrong part yourself in following 3 lines . :-)
$rower_id= $_POST['id'];
....
$sql = "UPDATE rowercontacts ... WHERE id=:rower_id";
if($q->execute(array(':firstname'=>$firstname,...,':rower_id'=>$id)))