How to display fetched result inside php form? - php

i am a PHP MYSQL beginner! trying to get the id (primary key) value of a row and update its corresponding values in a database. My search results are working perfecting and am getting redirected to my update form page, where in which i wanted to display the fetched result, so that i can edit the result and update the values.
My PHP
<?php
require_once 'db_alternate2.php';
session_start();
try{
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
if( isset($_GET['edit']) )
{
$id = $_GET['edit'];
$res= "SELECT * FROM staff_db WHERE staff_id='$id'";
$r = $conn->query($res);
$r->setFetchMode(PDO::FETCH_ASSOC);
}
if( isset($_POST['new_staf_id']) && isset($_POST['new_staf_name']) && isset($_POST['new_staf_acc']) && isset($_POST['new_staf_bnkaddrs']) )
{
$staf_id = $_POST['new_staf_id'];
$staf_name = $_POST['new_staf_name'];
$staf_acc = $_POST['new_staf_acc'];
$staf_bnkaddrs = $_POST['new_staf_bnkaddrs'];
$sql = $conn->prepare("UPDATE staff_db SET staff_id='$staf_id' staff_name='$staf_name' staff_acc='$staf_acc' staff_bnkaddrs='$staf_bnkaddrs' WHERE sl_no ='$id'");
$sql->execute();
$result1 = $sql->fetch(PDO::FETCH_ASSOC);
echo "<meta http-equiv='refresh' content='0;url=staff_update.php'>";
}
} catch (PDOException $pe) {
die("Could not connect to the database $dbname :" . $pe->getMessage());
}
?> .
My HTML
<form class="" style="right:10px !important;" action="staff_db.php" method="post">
<div class="main-left" style="width:38% !important; margin-left:100px;">
<p>Staff ID:</p> <input type="text" name="staf_id" value="______"/>
<p>Name:</p> <input type="text" name="staf_name" value="______"/>
</div>
<div class="main-right" style="width:38% !important; margin-right:100px;">
<p>Account no:</p> <input type="text" name="staf_acc" value="______"/>
<p>Bank Address:</p> <input type="text" name="staf_bnkaddrs" value="______"/>
</div>
<div class="bottom-centre" style="padding-top:50px; ">
<input class="submit" type="submit" value="Update"/>
</div>
</form>
I know this is a simple question, but guide me here! how to display the PDO fetched results inside the value="______" of form.
Thanks in advance!

Just few modifications in your code
if( isset($_GET['edit']) )
{
$id = $_GET['edit'];
$res= "SELECT * FROM staff_db WHERE staff_id='$id'";
$r = $conn->query($res);
$r->setFetchMode(PDO::FETCH_ASSOC);
$result = $r->fetch();
}
and few modification in your form to put value
<input type="text" name="staf_name" value=<?php echo $result["staff_name"]; ?>/>

Related

PHP only taking the last row from MySQL DB in login form

I've been stuck on this issue for 3 days now. I'm trying to make a login form (I've already created a register form) and the database is working too. But now while I'm trying to make the login form, I've noticed that PHP only takes the last row from the database.
As you can clearly see in the first picture, my database has 3 records.
But when I try to log in on my account, it only lets me log in to the most recently created account, and not the others. Here's my current code:
<div class="login-form">
<form method="POST">
<p style="float:left;">
<input type="email" class="login-input" maxlength="40" name="login-email" id="login-email" placeholder="email" required><span style="color: red;"> *</span><br><br>
<input type="password" class="login-input" maxlength="32" name="login-passw" id="login-passw" placeholder="password" required><span style="color: red;"> *</span><br><br>
<input type="submit" class="btn" name="login-btn">
</p>
<?php
$email = $_POST["login-email"];
$passw = $_POST["login-passw"];
$encrypted_passw = md5($passw);
$sql = "SELECT id, email, passw FROM users";
$result = $db->query($sql);
// if (isset($_POST["login-btn"])) {
// if ($_POST["login-email"] == $result["email"]) {
// echo "<p>Logged in</p>";
// } else {
// echo "<p>wrong</p>";
// }
// }
while ($row = $result->fetch_assoc()) {
$get_email = $row["email"];
$get_usr = $row["username"];
$get_passw = $row["passw"];
}
if (isset($_POST["login-btn"])) {
if ($_POST["login-email"] == $get_email && $encrypted_passw == $get_passw) {
echo "<p>Logged in</p>";
} else {
echo "<p> wrong</p>";
}
}
?>
</form>
</div>
Try this. First of all I would place the php code above the HTML.
You only need to listen the post param login-btn. Read the other post data into vars and confirm its there before proceeding.
When you poll the DB you dont need to read every record (imagine you have thousands of records, you wouldn't want to pull them all down). Just filter for the supplied email with a where clause.
If the email exists it will return a result with the hashed password. Verify this matches and you are good to go.
The issue you're having where the last record in the db is beiung used is becuase in your loop, you are overwriting the var $get_email each time.
<?php
if (isset($_POST["login-btn"])) {
$email = (isset($_POST["login-email"]) ? $_POST["login-email"] : '');
$passw = (isset($_POST["login-passw"]) ? $_POST["login-passw"] : '');
if($email != "" && $passw != ""){
$encrypted_passw = md5($passw);
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');
$stmt = $mysqli->prepare("SELECT email, passw FROM users where email = ?");
$stmt->bind_param($email);
$stmt->execute();
while ($row = $result->fetch_row()) {
$get_passw = $row["passw"];
if($encrypted_passw == $row['passw']){
echo "logged in";
}else{
echo 'no match';
}
}
}
}
?>
<div class="login-form">
<form method="POST">
<p style="float:left;">
<input type="email" class="login-input" maxlength="40" name="login-email" id="login-email" placeholder="email" required><span style="color: red;"> *</span><br><br>
<input type="password" class="login-input" maxlength="32" name="login-passw" id="login-passw" placeholder="password" required><span style="color: red;"> *</span><br><br>
<input type="submit" class="btn" name="login-btn">
</p>
</form>
</div>
Gottem! I was using array's instead of values
<?php
session_start();
include_once "../php/db_connect.php";
if (isset($_POST["login-btn"])) {
$email = $_POST["email"];
$passw = $_POST["passw"];
$encrypted = md5($passw);
$sql = "SELECT * FROM users WHERE email = '". $email ."'";
$result = $db->query($sql);
$get_result = $result->fetch_assoc();
if ($encrypted == $get_result["passw"]) {
echo "<p>Logged in!</p>";
$_SESSION["username"] = $get_result["username"];
$_SESSION["id"] = $get_result["id"];
$_SESSION["email"] = $get_result["email"];
Header("Location:../../../");
} else {
echo "<p>Error</p>";
}
}
?>
change your query to this
"SELECT id, email, passw FROM users where email='".$row["email"]."'
and password= '".$row["password"]."'"
you do not need to use foreach for all rows this query return only one row that you need

My login page is not working, if statement keeps activating nonetheless

<div class = "login">
<?php
$lusername=$_POST['lusername'];
$lpassword=$_POST['lpassword'];
$mysql = new mysqli("localhost", "root", null, "webdb");
$stmt = $mysql ->prepare("select username, password from webdb.user where username=?");
$stmt->bind_param("s", $lusername);
$stmt->execute();
$stmt->bind_result($u, $p);
$stmt->fetch();
$stmt->close();
$mysql->close();
if($lusername == $u && $lpassword == $p) {
echo "the log in is successful";
}
else {
echo "<b><font color='red'>Login unsuccessful. Please go back and try again </font></b>";
}
?>
<form action="sign in.php" method="post">
<div class = "details">
<br>
&nbsp<input type="text" name="lusername" placeholder="Username" required>
<br>
<br>
<br>
<input type="password" name="lpassword" placeholder ="Password" required>
</div>
<div class = "enter">
<br>
<br>
<input type="submit" name="submit" value="Enter">
</div>
I've been working on my login page for a day but I cannot seem to find the error in my codes. Currently, when I click on login, it automatically activates the if statement "the log in is successful" without even having to key in the username and password.
<div class = "login">
<?php
if(isset($_POST['submit'])){
$lusername=$_POST['lusername'];
$lpassword=$_POST['lpassword'];
$mysql = new mysqli("localhost", "root",'', "webdb");
$stmt = $mysql ->prepare("select username, password from webdb.user where username=?");
$stmt->bind_param("s", $lusername);
$stmt->execute();
$stmt->bind_result($u, $p);
$stmt->fetch();
$stmt->close();
$mysql->close();
if($lusername == $u && $lpassword == $p) {
echo "the log in is successful";
}
else {
echo "<b><font color='red'>Login unsuccessful. Please go back and try again </font></b>";
}
}
?>
<form action="sign in.php" method="post">
<div class = "details">
<br>
&nbsp<input type="text" name="lusername" placeholder="Username" required>
<br>
<br>
<br>
<input type="password" name="lpassword" placeholder ="Password" required>
</div>
<div class = "enter">
<br>
<br>
<input type="submit" name="submit" value="Enter">
</div>
try this as you are first checking the GET request, and it will always give the login successful, for that you need to check whether the submit button has been pressed, and remove the null from the database password as for blank password you keep '' and not null
1st : use isset to avoid undefined index error on page load for the first time .
if(isset($_POST['submit'])){ //all you php code here }
2nd : Don't save the password as plain text in database .Try to use password_hash() and password_verify()
3rd : On the error debugging mode. On top of page add these two lines
ini_set('display_errors','On'); ini_set('error_reporting', E_ALL);
1) Do no store password as a plain text use password_hash() to store it correclty. And use password_verify() to verify if the password is correct. Link: http://www.phptherightway.com/#password_hashing. I hope it is not a live app.
2)Use this to escape : htmlentities( $slusername, ENT_QUOTES | ENT_HTML5, $encoding = 'UTF-8' )
--------------------SOLUTION-------------------------------------------
The problem is that you don't submit the data with if ( $_SERVER['REQUEST_METHOD'] == "POST" ) and sign in.php should be sign_in.php. There is a space. AND REMOVE THE NULL on your mysqli database put ''.
2)In your your sign_in.php. Use this code.
<?php
/* Database connection start */
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=webdb", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
/*if submission button */
if ( $_SERVER['REQUEST_METHOD'] == "POST" ) {
/*There is no protection here*/
/*use $lusername=$htmlentities( $slusername, ENT_QUOTES |
ENT_HTML5, $encoding = 'UTF-8' );*/
$lusername=$_POST['lusername'];
$lpassword=$_POST['lpassword'];
/*Query*/
$query = 'SELECT password, username FROM user WHERE username
=:username';
$stmt = $conn->prepare($query);
$stmt -> bindParam(':username', $lusername);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->execute();
$stmt->CloseCursor();
/*Arranging query*/
function returnArray( $rows, $string )
{
foreach( $rows as $row )
{
return $row[ $string ];
}
}
/*Verification of the user*/
if( returnArray( $rows, 'password') == $lpassword)
{
echo "the log in is successful";
}
else
{
echo "<b><font color='red'>Login unsuccessful. Please
go back and try again </font></b>";
}
}
?>
In your login.php
<div class = "login">
<form action="sign_in.php" method="post">
<div class = "details">
<br>
&nbsp<input type="text" name="lusername"
placeholder="Username" required>
<br>
<br>
<br>
<input type="password" name="lpassword" placeholder
="Password" required>
</div>
<div class = "enter">
<br>
<br>
<input type="submit" name="submit" value="Enter">
</div>
</form>
</div>

PHP: Record is not updating in SQL

My problem is in updating the SQL record. It fetches SQL data into form correctly (For editing) but when I press save edits button it returns following erro inside input field:Notice: Undefined variable: row in C:\xampp\htdocs\edit.php on line 46Please can you tell me how to fix it
<html>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "zz224466";
$database = "zain";
$conn = mysqli_connect($servername,$username,$password,$database);
if($conn->connect_error) {
die("connection failed: " . $conn->connect_error);
}
if(isset($_GET['edit'])) {
$id = $_GET["edit"]; //Get id of sql table from other php page.
echo $id; //It gives true result. It means that $_GET method above gets id of sql table correctly
$res = mysqli_query($conn, "SELECT * FROM product where product_id=$id");
if ($res == FALSE) {
die("Error");
}
$row = mysqli_fetch_array($res);// Getting row from sql of specific id above selected above
if (isset($_POST['Edit'])) { ///Checking if Edit button has been pressed
$product_category = $_POST['product_category'];
$product_id = $id;
//// SQL query
$sql_category = "UPDATE product SET product_category='$product_category' WHERE product_id=$id";
if (mysqli_query($conn, $sql_category)) {
}
}
}
?>
////////////////////HTML FORM/////////////////////////
<form method="post" action ="edit.php" id="contact-form">
<input type="text" name="product_category" placeholder="product_category" value="<?php echo $row['product_category'];//It prints sql record in input field which is to be updated and it prints correctly. But when I press edit button it gives above mentioned error ?>"/>
<div class="btn-group" role="group">
<input type="submit" class="btn btn-default" name="Edit" value="Save Edits" style="margin-top: 15px; margin-right: 15px; border-radius: 4px;">
</div>
</form>
</body>
</html>
Kindly tell me that how to fix it
Try this. Because, when you are pressing submit button. It's going to edit.php with POST value and no GET parameters (after pressing Edit submit button. So, browser is unable to find $id resulting to it, no $row values.)
<input type="text" name="product_category" placeholder="product_category" value="<?php if(isset($row['product_category'])) { echo $row['product_category'];}?>"/>
for example, https:www.example.com/edit.php?edit=1
after pressing submit button, URL changes to
https:www.example.com/edit.php
So, no edit=1
Updated Code
Change your <form> to
<form method="post" action ="edit.php?edit=<?echo $_GET['edit'];?>" id="contact-form">
Additional to what i did before.
Full Updated Code (See lines where i have written Change Here)
<html>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "zz224466";
$database = "zain";
$conn = mysqli_connect($servername,$username,$password,$database);
if($conn->connect_error) {
die("connection failed: " . $conn->connect_error);
}
if(isset($_GET['edit'])) {
$id = $_GET["edit"];
echo $id;
$res = mysqli_query($conn, "SELECT * FROM product where product_id=$id");
if ($res == FALSE) {
die("Error");
}
$row = mysqli_fetch_array($res);
if (isset($_POST['Edit'])) {
$product_category = $_POST['product_category'];
$product_id = $_GET['edit']; // Change Here
// Changes here
$sql_category = "UPDATE product SET product_category='$product_category' WHERE product_id=$product_id";
if (mysqli_query($conn, $sql_category)) {
}
}
}?>
// Changes here in form tag
<form method="post" action ="edit.php?edit=<?echo $_GET['edit'];?>" id="contact-form">
<input type="text" name="product_category" placeholder="product_category" value="<?php if(isset($row['product_category'])) { echo $row['product_category']; }?>"/>
<div class="btn-group" role="group">
<input type="submit" class="btn btn-default" name="Edit" value="Save Edits" style="margin-top: 15px; margin-right: 15px; border-radius: 4px;">
</div>
</form>
</body>
</html>

Echo same MySql query in different part of the page

This might be a silly question but I am trying to call the same query to two different pages but once I call the second time, the link to the page would not work anymore. The way I have it setup at the moment is that all the pages in the app are on one file (index.php). I am linking to each page by using id (href="#page2"). If I call the same query, depending on the order of pages, only the "top" page, or in this case, Page 1 will work. I tried changing the variable names so that it would treat it as a different call but to no avail.
I am developing this app using Phonegap Build and it would be really helpful if ANYBODY can help.
Page 1
<div data-role="page" id="page1">
<form action="post-comment.php" method="POST">
<h3>COMMENT</h3>
<input type="text" name="name" placeholder="Name"><br />
<textarea name="comment" cols="50" rows="2" placeholder="Enter Comment"></textarea><br />
<input type="submit" value="comment" onClick="javascript.ajax_post()"></input><br />
</form>
<?php
$find_comments = mysql_query("SELECT * FROM COMMENTS");
while($row = mysql_fetch_assoc($find_comments))
{
$comment_name = $row['name'];
$comment = $row['comment'];
echo "$comment_name - $comment<br />" ;
}
?>
</div>
Page 2
<div data-role="page" id="page2">
<?php
$find_comments1 = mysql_query("SELECT * FROM COMMENTS");
while($row = mysql_fetch_assoc($find_comments1))
{
$comment_name1 = $row['name'];
$comment1 = $row['comment'];
echo "$comment_name1 - $comment1<br />" ;
}
?>
</div>
I suggest using PDO - DOC instead of mysql, I would do it this way :
Connect to your database :
$hostdb = "your_host";
$namedb = "db_name";
$userdb = "user_name";
$passdb = "pass";
$options = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING);
try {
$db = new PDO("mysql:host=$hostdb; dbname=$namedb; charset=utf8", $userdb, $passdb, $options);
return $db;
} catch (PDOException $e) {
$err = "DB Connection Error, because: ". $e->getMessage();
print $err;
}
Now you can use $db to connect to your database in your script and fetch comments :
<div data-role="page" id="page1">
<form action="post-comment.php" method="POST">
<h3>COMMENT</h3>
<input type="text" name="name" placeholder="Name"><br />
<textarea name="comment" cols="50" rows="2" placeholder="Enter Comment"></textarea><br />
<input type="submit" value="comment" onClick="javascript.ajax_post()"></input><br />
</form>
<?php
$find_comments ="SELECT * FROM COMMENTS";
$stmt = $db->prepare($find_comments);
if(!$stmt->execute()){
print "error";
} else {
$comments = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($comments as $comment) {
echo $comment['name']."</br>";
echo $comment['comment'] ;
}
$stmt->closeCursor(); // Close connection
}
?>
</div>
then in your Page2 just do the same as Page1. You can define the SQL statement as a global variable and re-use it in your second query. just make sure to use closeCursor(); to close your db connection.

how to fetch data from mysql and write it to innerhtml of a div in PHP

Apologies for the newbie question, I just started with PHP, trying to fetch data when the user writes ID, and get info from database and write it into innerhtml of div's inside the form. How can I do it? thanks.
<form action="read.php" method="post">
Bring Data of ID <input type="text" name="id" />
<br/>
<input type="submit" />
<br/>
<div id="username" style="font-weight:bold;" /></div>
<br/>
<div id="email" style="font-weight:bold;" /></div>
<br/>
<div id="password" style="font-weight:bold;" /></div>
</form>
<?php
$db_username = "root";
$db_password = "";
$con = new PDO('mysql:host=localhost;dbname=test', $db_username, $db_password);
if (!$con) {
echo "error";
}
else {
echo "connected";
}
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$query = $con->prepare(" SELECT * FROM bucky (username, email, password) WHERE id=:id ");
$query->execute(array(
':id' => $_POST['id']
));
}
else {
die("Die hacker!");
}
In your read.html, append your html code at the end:
<?php
[...]
$query = $con->prepare(" SELECT * FROM bucky (username, email, password) WHERE id=:id ");
$query->execute(array(
':id' => $_POST['id']
));
$result = $sth->fetchAll();
}
else {
die("Die hacker!"); // seriously?
}
?><html><body><?php
print_r($result); ?>
</body></html>
This will print you the result of your query.
You can also iterate over the result, but i think you should really just read the documentation on PDO and how to use it. Maybe a simple introduction to PHP as well. This is a VERY basic Question.

Categories