Echo same MySql query in different part of the page - php

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.

Related

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>

Inserting HTML Form data into MySQL with PHP

I'm trying to make a simple message board MySQL database where you can write a review and submit it via an HTML form on one page and view all of the reviews on a separate page once you've submitted your review.
My problem is two of the fields from the HTML form are not being inserted into my MySQL database which results in my view all reviews page to be missing the Name and Title.
Link to what the "Read all Reviews" page looks like.
The code works without any issue when I tested it doing MySQL queries with just PHP but I need my HTML form to work.
HTML form:
<form action ="process.php" method = "post">
<fieldset>
<legend>Review Field</legend>
Reviewer Name: <br />
<input type="text" name "name" id = "name"><br />
Title of Review:<br />
<input type="text" name "title" id = "title"><br />
Enter your review below:
<!--Textbox start-->
<textarea name="body" id = "body" rows="10" cols="100">
</textarea>
<!--Textbox end-->
<br />
<input type="submit" name = "submit" id="submit">
<br />
</fieldset>
</form>
Code for process.php:
<?php // Create a database connection.
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "password";
$dbname = "ya_reviews";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
//Test if connection occurred.
if (mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}
//Perform database query
$name = $_POST['name'];
$title = $_POST['title'];
$body = $_POST['body'];
//This function will clean the data and add slashes.
// Since I'm using the newer MySQL v. 5.7.14 I have to addslashes
$name = mysqli_real_escape_string($connection, $name);
$title = mysqli_real_escape_string($connection, $title);
$body = mysqli_real_escape_string($connection, $body);
//This should retrive HTML form data and insert into database
$query = "INSERT INTO reviews (name, title, body)
VALUES ('".$_POST["name"]."','".$_POST["title"]."','".$_POST["body"]."')";
$result = mysqli_query($connection, $query);
//Test if there was a query error
if ($result) {
//SUCCESS
header('Location: activity.php');
} else {
//FAILURE
die("Database query failed. " . mysqli_error($connection));
//last bit is for me, delete when done
}
mysqli_close($connection);
?>
View all Reviews:
<?php
//This will fetch the data from the database
$query = "SELECT * FROM reviews";
$result = mysqli_query($connection, $query);
//Test if there was a query error
if (!$result) {
die("Database query failed.");
}
// This will let me display the data.
// The loop will be spilt so I can format with HTML
while ($row = mysqli_fetch_assoc($result)) {
//output data from each row
?>
Name: <?php echo $row["name"] . "<br />"; ?>
Title: <?php echo $row["title"] . "<br />"; ?>
Review: <?php echo $row["body"] . "<br />";
echo "<hr>"; ?>
<?php
} ?>
Note: I connected to the database with the same code seen in process.php before the above code, I excluded it to save space.
Your HTML attribute syntax is incorrect. Its missing = sign between attribute and value.
Change name "name" to name="name" and name "title" to name="title"
<input type="text" name="name" id = "name"><br />
Title of Review:<br />
<input type="text" name="title" id = "title"><br />
Also during insert you aren't using escaped values.
Use $name instead of $_POST["name"] in insert query. Same goes for title and body values.
The problem is that the name attribute is not correct in HTML.
<input type="text" name="name" id = "name"><br />
<input type="text" name="title" id = "title"><br />
I think you messed up with syntax of HTML
<form action ="process.php" method = "post">
<fieldset>
<legend>Review Field</legend>
Reviewer Name: <br />
<input type="text" name="name" id = "name"><br />
Title of Review:<br />
<input type="text" name="title" id = "title"><br />
Enter your review below:
<!--Textbox start-->
<textarea name="body" id = "body" rows="10" cols="100">
</textarea>
<!--Textbox end-->
<br />
<input type="submit" name = "submit" id="submit">
<br />
</fieldset>
</form>
It will work surely!
Yo, you're just missing some syntax, therefore creating errors when it comes to gathering the data from those elements,
<input type="text" name "title" id = "title">
You're missing the "=" sign from the name parameter

Shows wrong data Decrypy PDO/PHP

I have a question about my code. The problem is that when i say echo $collumB than he shows the student_city. that is in my database but i want that it shows the decrypted password. It just shows the wrong data
(there is an another page where i encrypt the password but i need the decrypted password echo'ed
<html>
<head>
<title>insert data in database using PDO(php data object)</title>
<link rel="stylesheet" type="text/css" href="style-login.css">
</head>
<body>
<div id="main">
<h1>Login using PDO</h1>
<div id="login">
<h2>Login</h2>
<hr/>
<form action="" method="post">
<label>Email :</label>
<input type="email" name="stu_email" id="email" required="required" placeholder="john123#gmail.com"/><br/><br />
<label>Password :</label>
<input type="password" name="stu_ww" id="ww" required="required" placeholder="Please Enter Your Password"/><br/><br />
<input type="submit" value=" Submit " name="submit"/><br />
</form>
</div>
</div>
<?php
//require ("encrypt.php");
if(isset($_POST["submit"])){
$hostname='localhost';
$username='root';
$password='';
$pdo = "college";
$student_email = $_POST["stu_email"];
$encrypt_key = "4ldetn43t4aed0ho10smhd1l";
try {
$dbh = new PDO("mysql:host=$hostname;dbname=college","root","$password");
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Query
$statement = $dbh->prepare("SELECT student_email, student_city, AES_DECRYPT(student_password, '$encrypt_key')
AS student_password FROM students WHERE student_email = :student_email ORDER BY student_email ASC");
// Assign and execute query
$statement->bindParam(':student_email', $student_email, PDO::PARAM_STR);
$statement->setFetchMode(PDO::FETCH_ASSOC);
$statement->execute();
// Get data
while($row = $statement->fetch()) {
echo "1 ,";
//$columnA_value = $row['student_city'];
$columnB_value = $row['student_password'];
}
echo "2 ,";
echo $columnB_value;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
?>
</body>
</html>
SELECT student_email, student_city, CAST(AES_DECRYPT(student_password, '$encrypt_key') AS char(50)) AS student_password FROM students WHERE student_email = :student_email ORDER BY student_email ASC;
Try to explicitly cast it to string. You can change the '50' according to your requirement.
Also your echo is outside while loop, hence it will print only last record if there are more than 1 records.

How to display fetched result inside php form?

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"]; ?>/>

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