I have this PHP code, when I try to click the yes button and check the database.The value remains the same. Is there something I am doing wrong? I also check my SQL query and it seems to be working fine but when I incorporate it in the php code . It is not working anymore?
<?php
require 'database.php';
$id = 0;
if ( !empty($_GET['gpx_field_id'])) {
$id = $_REQUEST['gpx_field_id'];
}
if ( !empty($_POST)) {
// keep track post values
$id = $_POST['gpx_field_id'];
// delete data
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE field_info SET verify = '1' WHERE gpx_field_id = ? ";
$q = $pdo->prepare($sql);
$q->execute(array($id));
Database::disconnect();
header("Location: index.php");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="assets/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<script src="assets/bootsrap/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="span10 offset1">
<div class="row">
<h3>Verify a Field</h3>
</div>
<form class="form-horizontal" action="verify.php" method="post">
<input type="hidden" name="gpx_field_id" value="<?php echo $id;?>"/>
<p class="alert alert-error">Are you sure to verify this field ?</p>
<div class="form-actions">
<button type="submit" class="btn btn-danger">Yes</button>
<a class="btn btn-danger" href="index.php">No</a>
</div>
</form>
</div>
</div> <!-- /container -->
</body>
</html>
Here I assume your query is working fine so
Please change your php code as below...
<?php
require 'database.php';
$id = 0;
if ( !empty($_GET['gpx_field_id'])) {
$id = $_REQUEST['gpx_field_id'];
}
if ( !empty($_POST)) {
try {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE field_info SET verify = '1' WHERE gpx_field_id IN :id ";
$q = $pdo->prepare($sql);
$q->execute(array($id));
Database::disconnect();
header("Location: index.php");
}
catch(PDOException $e) {
echo $e->getMessage();
}
}
?>
Hope it will help you.
You specify $id = 0 at the top, but it is never updated to some 'real' value. Therefore, the form is populated with
<input type="hidden" name="gpx_field_id" value="0"/>
and thus gpx_field_id always remains 0. Then, your query will update all rows with WHERE gpx_field_id = 0. Most probably, those rows will not exist...
You do need to get a proper value for $id before you insert it in the form.
On a side-note, since you are using html5 (<!DOCTYPE html>), the closing tag for input should be omitted. Write instead: <input type="hidden" ... >, leaving out the forward slash, just as you did with the meta and link tags in the head section.
Related
I'm building an ecommerce website project and right at the start, I kept on having the same problem. For some reason that I don't know, it feels like session_star() is not working or not displaying. I already done so many approach the last thing I have done is copy a source code online made by packetcode on youtube. but no results is showing in my browsers
I was expecting that the results will show but even though I referenced alot of sourece code it's still doesn't work and I have no any idea.
heres the index.php file:
<?php
session_start();
include "db.php";
include "retrieve.php";
include "function.php";
include "logic.php";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Exquisite</title>
</head>
<body>
<div class="container" id="main_cntr">
<div id="intro_cntr">
<div id="title_cntr">
<h2>Welcome to </h1>
<h1>Exquisite</h1>
</div>
<div id="paragraph_cntr">
<p>Here to provide an excellent support for your style!</p>
</div>
</div>
<?php if(empty($_SESSION['username'])){?>
<div class="container" id="form">
<div id="login_cntr">
<form method="POST">
<h2>Login</h2>
<label for="username">Username</label><br>
<input type="text" name="username" placeholder="Enter your Username"><br>
<label for="password">Password</label><br>
<input type="password" name="pass" placeholder="Enter your Password"><br>
<input type="submit" name="login" value="Login">
</form>
</div>
<?php }?>
<div id="signupOption_cntr">
Create an Account
<h4>or</h4>
Login as Admin
</div>
</div>
<?php if(!empty($_SESSION['username'])){?>
<div class="container">
<h1>Hello again<?php echo $_SESSION['username'];?></h1>
<form method="POST">
<button name="logout">Logout</button>
</form>
</div>
<?php }?>
</div>
</body>
</html>
I also devided the codes as seen in packetcode's video.
here the database code:
<?php
$conn = mysqli_connect('localhost', 'root', '', 'exquisite') or die ("Cannot connect to the Database");
?>
heres the account retrieval code:
<?php
if(isset($_REQUEST['login'])){
$uname = $_REQUEST['username'];
$pword = $_REQUEST['pass'];
}
?>
here's the function to take data from the server:
<?php
function login($conn, $uname, $pword){
$sql = "SELECT * FROM `user_acc` WHERE `username` = '$uname'";
$query = mysqli_query($conn, $sql);
return $query;
}
?>
and here's the code for validation:
<?php
if(isset($_REQUEST['login'])){
$result = login($conn, $uname, $pword);
foreach($result as $r){
$passw_check = password_verify($pword, $r['password']);
if($passw_check){
$_SESSION['username'] = $r['username'];
header("location: home.php");
}
}
}
if(isset($_REQUEST['logout'])){
session_destroy();
header("location: index.php");
exit();
}
?>
Need more information.
if you are using separate file to validation make sure you are include sessio_start(); on that file too.
without session_start(); session_destroy(); will not work.
<?php
session_start();
if(isset($_REQUEST['login'])){
$result = login($conn, $uname, $pword);
foreach($result as $r){
$passw_check = password_verify($pword, $r['password']);
if($passw_check){
$_SESSION['username'] = $r['username'];
header("location: home.php");
}
}
}
if(isset($_REQUEST['logout'])){
session_destroy();
header("location: index.php");
exit();
}
?>
Practising PHP by creating a very simple page that has a picture and the user can comment on it. I pretty much have everything down except adding the comment to the table within the database. I have it so I get an alert when the comment either gets added to the table or it does not go through. As far as I can tell, the code looks good but I could be wrong.
Here is the PHP file with the config info
<?php
$servername = "localhost";
$user = "user1";
$password = "";
$dbname = "comment_section";
//Create connection to database
$conn = mysqli_connect($servername, $user, $password, $dbname);
if(!conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "CREATE TABLE comment_list (
id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
nid VARCHAR(128) NOT NULL,
comments TEXT NOT NULL,
date datetime NOT NULL
)";
if (mysqli_query($conn, $sql)) {
echo "Table comment_list created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
And here is my index file
<?php
include 'comments.php';
error_reporting(0);
if (isset($_POST['submit'])) {
$name = $_POST['nid'];
$comment = $_POST['comments'];
$sql = "INSERT INTO comment_list (nid, comments)
VALUES ('$name', '$comment')";
$result = mysqli_query($conn, $sql);
if ($result) {
echo "<script>alert('Comment added')</script>";
} else {
echo "<script>alert('Comment not added')</script>";
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
<!-- CSS, JS, and PHP files goes here -->
<link rel="stylesheet" href="style.css">
<!-- javascript code goes here -->
<!-- end of js code -->
</head>
<body>
<!-- Intro to what the site is about, possible pages to include comments -->
<header>
<h1></h1>
<nav>
<ul>
</ul>
</nav>
</header>
<!-- Image with comment section -->
<article>
<img src="images/IMG_1560.JPG" alt="" ">
<div class="wrapper">
<form action="" method="POST" class="form">
<div class="name">
<label for="name">Name</label>
<input type="text" name="nid" id="nid" placeholder="Name" required>
</div> <!-- End div class name -->
<div class="comment">
<label for="comment">Comment</label>
<textarea name="comments" id="comments" placeholder="Comment" required></textarea>
</div> <!-- End of div for textarea -->
<div class="but">
<button name="submit" class="btn">Post Comment</button>
</div>
</form>
<?php
$sql = "SELECT * FROM comment_list";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
?>
<?php echo $row['nid']; ?>
<p><?php echo $row['comments']; ?></p>
<?php
}
}
?>
</div>
</article>
<footer>
<p></p>
</footer>
</body>
</html>
Now every time I try to test and click on the submit button. I get an alert and the Comment Not Added pops up. Am I missing something? I also want it to show under the form whenever a user has left a comment. I know I can use Ajax without having to refresh the page, but I at least want to get the comment into the db/table and displayed under the form.
I am trying to make a CRUD application. on the Create page I have to have three fields (title, text, category). the problem is that I have to make a method / function in PHP or JS that chooses a random picture from the "images" file and automatically loads it in the database along with the other 3 fields. then it has to appear on the admin.php page together with the other 3 fields.
Images have almost the same name except the last digit which differs (1-2-3)
I have no idea how to make this method/function.
my create.php page
// Include config file
require_once "config.php";
// Define variables and initialize with empty values
$title = $text = $category = "";
$title_err = $text_err = $category_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate title
$input_title = trim($_POST["title"]);
if(empty($input_title)){
$title_err = "Please enter a title.";
} else{
$title = $input_title;
}
// Validate text
$input_text = trim($_POST["text"]);
if(empty($input_text)){
$text_err = "Please enter an text.";
} else{
$text = $input_text;
}
// Validate category
$input_category = trim($_POST["category"]);
if(empty($input_category)){
$category_err = "Please enter the category.";
} else{
$category = $input_category;
}
// Check input errors before inserting in database
if(empty($title_err) && empty($text_err) && empty($category_err)){
// Prepare an insert statement
$sql = "INSERT INTO informatii (title, text, category) VALUES (?, ?, ?)";
if($stmt = $mysqli->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bind_param("sss", $param_title, $param_text, $param_category, );
// Set parameters
$param_title = $title;
$param_text = $text;
$param_category = $category;
// Attempt to execute the prepared statement
if($stmt->execute()){
// Records created successfully. Redirect to landing page
header("location: admin.php");
exit();
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
$stmt->close();
}
}
?>
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Create Record</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<style>
.wrapper {
width: 600px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<h2 class="mt-5">Create Record</h2>
<p>Please fill this form and submit to add employee record to the database.</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group">
<label>title</label>
<input type="text" name="title"
class="form-control <?php echo (!empty($title_err)) ? 'is-invalid' : ''; ?>"
value="<?php echo $title; ?>">
<span class="invalid-feedback"><?php echo $title_err;?></span>
</div>
<div class="form-group">
<label>Text</label>
<textarea name="text"
class="form-control <?php echo (!empty($text_err)) ? 'is-invalid' : ''; ?>"><?php echo $text; ?></textarea>
<span class="invalid-feedback"><?php echo $text_err;?></span>
</div>
<div class="form-group">
<label>Category</label>
<textarea name="category"
class="form-control <?php echo (!empty($category_err)) ? 'is-invalid' : ''; ?>"><?php echo $category; ?></textarea>
<span class="invalid-feedback"><?php echo $category_err;?></span>
</div>
<input type="submit" class="btn btn-primary" value="Submit">
Cancel
</form>
</div>
</div>
</div>
</div>
</body>
</html>
this should get you in the right direction (saving the image src is enough), you of course will have to adapt the path to your image folder, and image name
$nr_images = 3;
$random_nr_index = random_int(1,$nr_images);
$random_image_src = '/images/image-'.$random_nr_index.'.jpg';
To do it you need more than one step creating:
A simple html page to post 3 fields value and the image
A php file that receive the post fields and the image and save into mysql
A simple admin.PHP page that shows 3 fields and image
if you already have the images on the server please specify it in a comment
STEP 1:
<html>
<body>
<form method="POST" action="post.php">
f1:<input type="text" name="field1"><br>
f2:<input type="text" name="field2"><br>
f3:<input type="text" name="field3"><br>
im:<input type="file" name="image"><br>
<input type="submit" value="Save">
</form>
</body>
</html>
STEP 2: post.php
<?php
$f1=$_POST["field1"];
$f2=$_POST["field2"];
$f3=$_POST["field3"];
$im=$_POST["image"];
if ($f1 == "" || $f2 == "" || $f3 == "" ){
die("Errors: fields can't be empty! Go back check the fields and try Again");
}
//Saving image on Server's file system if any image
if(isset($_POST["image"])) {
//Saving image with no checking nothing: filetype, mime , extention (it may be very dangerous in a real server exposed to the public)
$where_save = "images/";
$im_name = basename($_FILES["image"]["name"]);
$tmp_name = $_FILES["image"]["tmp_name"];
move_uploaded_file ( $tmp_name , $where_save.$im_name );
}
$h = "localhost";
$u = "username";
$p = "password";
$db = "yourDB";
// Creating connection to mysql server
$conn = mysqli_connect($h, $u, $p, $db);
// Checking connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// WARNINGS ------------------------------------------------
// I do not care about security , please pay attention to it .
// use some mysql_escape_string , or real_mysql_escape_string
// could mitigate the violence of some sqlinjection attack
$sql = "INSERT INTO yourtable (field1, field2, field3,im_name)
VALUES ('$f1', '$f2', '$f3',$im_name)";
//executing mysql query to save data into it
if (!mysqli_query($conn, $sql)) {
die("Error: " . $sql . "<br>" . mysqli_error($conn));
}
//closing connection
mysqli_close($conn);
//Now we can redirect the user to admin.php where we show data
header("Location: admin.php");
?>
STEP 3:
<?php
$where_are_images="images/";
$h = "localhost";
$u = "username";
$p = "password";
$db = "yourDB";
// Again creating connection to mysql server
$conn = mysqli_connect($h, $u, $p, $db);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
//now we want to read the data from mysql
$sql = "SELECT * FROM yourtable LIMIT 1"; //just limit to the first record
$result = mysqli_query($conn, $sql);
?>
<html>
<body>
<h2>Admin page</h2>
<em> hey every one can see top secret data here , Needs soma care about security!</em>
<?php while($d = mysqli_fetch_assoc($result)){ // LOOPING ?>
<br>
f1:<?= $d["field1"] ?><br>
f2:<?= $d["field2"] ?><br>
f3:<?= $d["field3"] ?><br>
<img src="<?=$where_are_images.$d['im_name']?>">
<br>
<br>
<?php } ?>
</body>
</html>
<php? // CLOSING AND FREE RESOURCES
mysqli_free_result($result);
mysqli_close($conn); ?>
Now you have all you need . Have fun editing it with random images part ...
I hope there are no error (i have not tested it)
<?php
//Connect to Database
$link = mysqli_connect('localhost', 'xxxxxxx', 'xxxxxxx', 'xxxxxxx');
mysqli_set_charset($link,'utf8');
$delistpost= htmlspecialchars($_GET["delistpost"]);
//$request = $_SERVER['QUERY_STRING'];
$request = $delistpost;
//Error message on unsuccessful connection (connection failure)
if ($link==false){
//Print error information
echo(" ERROR: Could not connect.<br>".mysqli_connect_error());
}
//Successful connection message
else{
//Split the query string taking '=' as the delimiter
if (strpos($request, '='))
{
$n=split("=",$request);
// $queryStringType=$n[0];
$offset =$n[1];
}
$userchar = substr($offset,0,2);
$key = ltrim(substr($offset, 2, -1), '0');
$status = substr($offset,-1,1);
$query = "SELECT postid FROM userwisePost WHERE postid = $key AND user_email like '$userchar%' AND status = '$status'" ;
$updatequery = "UPDATE userwisePost SET post_status = 'draft' WHERE postid = $key AND user_email like '$userchar%' AND status = '$status'" ;
//Print the confirmation of SQL query
$verify = mysqli_query($link,$query);
if(mysqli_num_rows($verify) > 0){
$updateresult = mysqli_query($link,$updatequery);
if($updateresult==true){
RUN FUNCTION TO SHOW SUCCESS UPDATION.
}
else RUN FUNCTION TO SHOW FAILURE.
?>
Here I'm connecting to a database. I decrypt the query-string as per my requirement. After i decrypt the query-string, I match it with a record in the database, if everything matches, I need to run an update query.
Currently my program is updating it without confirmation. I need the user to press a confirmation button to run the update query.
I know I require javascript to track user button click. I need to display a HTML page on button click if the user confirms else the page should redirect to the homepage.
<?php
//Connect to Database
include "dbconnect.php";
$delistpost= htmlspecialchars($_GET["delistpost"]);
//$request = $_SERVER['QUERY_STRING'];
//$request = $delistpost;
//Split the query string taking '=' as the delimiter
$userchar = substr($delistpost,0,2);
$key = ltrim(substr($delistpost, 2, -1), '0');
$status = substr($delistpost,-1,1);
$query = "SELECT postid FROM userwisePost WHERE postid = $key AND user_email like '$userchar%' AND status = '$status'" ;
$verify = mysqli_query($dbconnect,$query);
if($verify==true){
if(mysqli_num_rows($verify) > 0)
{
echo '<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Confirmation</title>
<link rel="stylesheet" href="alertstyle.css">
</head>
<body>
<div class="container">
<form id="contact" action="changepoststatus.php?delistpost='.$delistpost.'" method="post">
<center><h3>Confirmation</h3>
<h4>Are you sure you want to delist your post?<br>If you wish to activate the post again, please contact the system administrator or email us at xxxxxxxxxx.</h4>
</center>
<fieldset>
<center>
<button name="delistpost" type="submit" id="contact-submit" style="width: 49%;">Confirm</button>
</center>
</fieldset>
</form>
</div>
</body>
</html>';
}
else {
echo '<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Failure</title>
<link rel="stylesheet" href="alertstyle.css">
</head>
<body>
<div class="container">
<form id="contact" action="https://xxxxxxxxxx" method="post">
<center><h3>Failure</h3>
<h4>Something went wrong<br>Please contact the system administrator or email us at xxxxxxxxxx.</h4>
</center>
<fieldset>
<center>
<button name="delistpost" type="submit" id="contact-submit" style="width: 49%;">Homepage</button>
</center>
</fieldset>
</form>
</div>
</body>
</html>';
}
}
?>
This is how I did it. I call another link on press of the button. changepoststatus.php has almost the same code but with update query instead of the select query.
I am saving latlong with the help of geolocation api into mysql db but problem is same latlong are inserted in database.I am trying to check last row of my mysql table and then comparing with current latlong if both are same,it should not be executed.Please help me to get this..Thanks in advance.
$latitude = 19.1579;
$longitude = 72.9935;
$address = airoli;
$sql = "SELECT latitude FROM tracklatlong ORDER BY id DESC LIMIT 1";
$result = mysqli_query($sql, $conn);
$row = mysqli_fetch_array($result);
$currentlat = $_row["latitude"];
if($currentlat != $latitude){
$query = "INSERT INTO `tracklatlong` (latitude, longitude,address) VALUES ('$latitude','$longitude','$address')";
if($conn->query($query) === TRUE){
echo "success";
}
else{
echo "failed";
}
}
else{
echo"Already exists";
}
As understood you need to check weather the latitute or longitute is in database Table insert it only if found false.
I am using PHP Object oriented with mysqli prepared statements.
This code returns false only when both latitute and longitute are same.
if you want output to return false were any one matchs the output than just add OR operator in SELECT query.
Here is the table image with data
Here is html code :index.php
<?php
include('co_ordinate.php');
$newcoordinate = new co_ordinate();
?>
<!DOCTYPE html>
<html>
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="col-md-6 col-md-offset-3" style="margin-top:100px;">
<form action="" method="post">
<div class="form-group">
<i>Add Latitute</i>
<input type="text" name="latitute" class="form-control">
</div>
<div class="form-group">
<i>Add Longitute</i>
<input type="text" name="longitute" class="form-control">
</div>
<div class="form-group">
<input type="submit" name="addcoordinate" class="btn btn-primary">
</div>
</form>
<?php
if(isset($_POST['addcoordinate'])){
$latitude = $_POST['latitute'];
$longitute = $_POST['longitute'];
$newcoordinate->getCo_ordinates($latitude,$longitute);
}
?>
</div>
</body>
</html>
Here is the class file :co_ordinate.php
<?php
class co_ordinate{
private $link;
function __construct(){
$this->link = new mysqli ('localhost','root','','example');
if(mysqli_connect_errno()){
die("connection Failed".mysqli_connect_errno());
}
}
function getCo_ordinates($latitude,$longitute){
$sql = $this->link->stmt_init();
if($sql->prepare("SELECT latitude,longitude FROM tracklatlong WHERE latitude=? AND longitude= ?")){
$sql->bind_param('dd',$latitude,$longitute);
$sql->execute();
$sql->store_result();
if($sql->num_rows > 0){
echo "The Co-Ordinates Already Exists";
}
else
{
$query = $this->link->stmt_init();
if($query->prepare("INSERT INTO tracklatlong (latitude,longitude) VALUES (?,?)")){
$query->bind_param('dd',$latitude,$longitute);
$query->execute();
echo "The Co-Ordinates Inserted Successfully";
}
}
}
else
{
echo $this->link->error;
}
}
}
?>