PDO cannot able to fetch database values - php

I'm newbie to pdo. Here I'm trying to edit and update my database records using pdo. Below I posted my two pages coding here. In main page I've fetch the details of particular database table. If user clicks Edit link it will redirect to another page for edit the values of particular record using GET['id'];. In editpage I'm trying to fetch my already stored values. But I cannot able to fetch it. I tried print_r($username); and var_dump($username);. It didn't show the value in editpage.
Mainpage PHP coding :
<?php
include('config.php');
$sql = "SELECT * FROM ebusers";
$db = $conn->query($sql);
$db->setFetchMode(PDO::FETCH_ASSOC);
while($row = $db->fetch())
{
echo "<td>". $row['UserID'] ."</td>";
echo "<br>";
echo "<td><a target=_blank href='edit.php?id=". $row['UserName'] ."'>Edit</a></td>";
echo "<br>";
}
?>
Editpage PHP coding:
<?php
include('config.php');
$uid = $_GET['id'];
$sql = "SELECT * FROM ebusers WHERE UserID = '$uid'";
$db = $conn->query($sql);
$db->setFetchMode(PDO::FETCH_ASSOC);
if($db->fetchColumn()>=1)
{
while($row = $db->fetch())
{
$username = $row['UserName'];
}
}
?>
<html>
<head>
<title></title>
</head>
<body>
<form action="delete.php" method="post">
<input type="text" name="name" value="<?php echo $username;?>" />
<input type="submit" />
</form>
</body>
</html>
Config PHP page
$user = "root";
$password = "password";
try
{
$conn = new PDO('mysql:host=localhost;dbname=evouchers', $user, $password);
$conn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo 'DATABASE ERROR : ' . $e->getMessage();
}
I don't know where I made a mistake?

Why are you fetching the first column first. Evaluate it in an if statement. And after that fetch the whole row?
What happens when you change
if($db->fetchColumn()>=1)
{
while($row = $db->fetch())
{
$username = $row['UserName'];
}
}
to
while($row = $db->fetch())
{
var_dump($row['UserName']);
}

Related

Pull database info and display to html problem?

I'm trying to display the information from the database to the html page but it is only displaying the message "connected successfully". The name of the database is "admin" and the table within that database is called "users". I have no idea how to get past the message and just display the table I have created.
Index page (index.php):
<?php
include_once('connection.php');
$query="select * from users";
$result=mysql_query($query);
?>
<!DOCTYPE html>
<html>
<title>
<head> Fetch Data Frome Database</head>
</title>
<body>
<table align="center" border="1px" style="width:250px; line-height: 30px;">
<tr>
<th colspan="4"><h2>Account Record</h2></th>
</tr>
<t>
<th>ID</th>
<th>Username</th>
<th>Password</th>
</t>
<?php
while($rows=mysql_fetch_assoc($result))
{
?>
<tr>
<td><?php echo $rows['ID'];?></td>
<td><?php echo $rows['username'];?></td>
<td><?php echo $rows['password'];?></td>
</tr>
<?php
}
?>
</table>
</body>
</html>
CONNECTION PAGE (connection.php):
<?php
//Include your own values for username, password and dbase name
$host = "localhost";
$username = "root";
$password = "root";
$dbname = "admin";
// Create connection
$conn = new mysqli($host, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Try putting all of your PHP into a single block
<?php
include_once('connection.php');
$query="select * from users";
$result=mysql_query($query);
while($rows=mysql_fetch_assoc($result))
{
echo "<tr>";
echo "<td>".$rows['ID']."</td>";
echo "<td>".$rows['username']."</td>";
echo "<td>".$rows['password']."</td>";
echo "</tr>";
}
?>
First problem is that your while loop is not set up correctly. The equals operator will pass the value of mysql_fetch_assoc($result) to $rows so this just wont do anything. Just think that a single equals sign does not mean equal it really means becomes. So rows becomes result. If you have two equals signs you are comparing the two values but this wont help you either. What your really need to do is first set rows to zero then say while the rows are less then the result echo the id echo the username echo the password and add 1 to rows.
So the while loop should look more like this
$rows = 0;
while($rows < mysql_fetch_assoc($result) ){
$rows++
?>
<tr>
<td><?php echo $rows['ID'];?></td>
<td><?php echo $rows['username'];?></td>
<td><?php echo $rows['password'];?></td>
</tr>
<?php
}
}
Assuming that $result=mysql_query($query) actually has a value this should work.
If you need to test if your result is good use PHP's array print to check print_r($result); This will echo all the results to the screen.
So I prefer using this method since its a little better than any other method I have tried. Plus I tuck the connection into a class and it makes it soo much easier to handle db connections.
DB CONNECTION Page:
class Database
{
private $host = "localhost";
private $db_name = "root";
private $username = "root";
private $password = "admin";
public $conn;
public function dbConnection()
{
$this->conn = null;
try
{
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $exception)
{
echo "Connection error: " . $exception->getMessage();
}
return $this->conn;
}
}
Now I create a class for the connection. I usually name it the site name.
require_once "db/config/page/location.php";
class localhost {
// Create conn to db
private $conn;
public function __construct()
{
$database = new Database();
$db = $database->dbConnection();
$this->conn = $db;
}
public function runQuery($sql)
{
$stmt = $this->conn->prepare($sql);
return $stmt;
}
}
Note: when you would like to use the connection on any page.
You can do the following:
EG Index Page:
<?php
include_once('class.php');
$lHost = new localhost();
//calling the users
$stmt = $lHost->runQuery('SELECT * FROM `users`');
$stmt->execute();
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html>
<title>
<head> Fetch Data Frome Database</head>
</title>
<body>
<table align="center" border="1px" style="width:250px; line-height: 30px;">
<tr>
<th colspan="4"><h2>Account Record</h2></th>
</tr>
<t>
<th>ID</th>
<th>Username</th>
<th>Password</th>
</t>
<?php
foreach ($users as $key => $user) {
?>
<tr>
<td><?php echo $user['ID'];?></td>
<td><?php echo $user['username'];?></td>
<td><?php echo $user['password'];?></td>
</tr>
<?php
}
?>
</table>
</body>
</html>
Feel free to ask me any questions.
Try this in your file. Use this file as one first to test.
<html>
<head>
<title>Selecting Table in MySQLi Server</title>
</head>
<body>
<?php
$dbhost = 'localhost:3306';
$dbuser = 'root';
$dbpass = '';
$dbname = 'admin';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname);
if(! $conn ) {
die('Could not connect: ' . mysqli_error());
}
echo 'Connected successfully<br>';
$sql = 'SELECT name FROM tutorials_inf';
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
</body>
</html>
Note: You can test for errors using mysqli_error()such as echo mysqli_error(); after your select query.

php search works as seperate page, but not on same page

I'm working on a project where I can use multiple forms on an html page to search and update tables from a mysql database. I have created a basic html form that will run a search on a separate php file. When I try to integrate that same php script into that same html it finds no results. Any help would be appreciated.
basic html
<html>
<body>
<form name="search" method="post" action="searchresults.php">
<input name="search" type="text" size="40" maxlength="50" />
<input type="submit" name="Submit" value="Search" />
</form>
</body>
</html>
search php
<?php
$database = "dbname";
$username = "name";
$password = "pass";
$host = "host";
$conn = new mysqli($host, $username, $password, $database);
if ($conn->connect_error){
die("Failed:" . $conn->connect_error);
}
echo"Successful";
$query = $_POST['search'];
$query = htmlspecialchars($query);
$raw_results = mysqli_query($conn,"SELECT * FROM beers WHERE name LIKE '%".$query."%'");
if(mysqli_num_rows($raw_results) > 0){ // if one or more rows are returned do following
while($results = mysqli_fetch_array($raw_results)){
echo "<p><h3>".$results['Name']."</h3>".$results['Brewery']."</p>";
}
}
else{ // if there is no matching rows do following
echo "No results";
}
?>
This works separated, but if I copy the same php script and insert it into the main html it connects but finds no results. Tried using _GET instead of _POST removed the action field and Ive searched all over for similar issues. If I scale everything completely down it gives me a parse error for $query = htmlspecialchars($query); , any thoughts?
Apply if (isset($query)) {...}. Only when search name is valid can you gain results.
<?php
$query = $_POST['search'];
// Apply validation.
if (isset($query)) {
$query = htmlspecialchars($query);
echo"Successful";
$conn = new mysqli($host, $username, $password, $database);
if ($conn->connect_error) {
die("Failed:" . $conn->connect_error);
}
$raw_results = mysqli_query($conn, "SELECT * FROM beers WHERE name LIKE '%" . $query . "%'");
if (mysqli_num_rows($raw_results) > 0) { // if one or more rows are returned do following
while ($results = mysqli_fetch_array($raw_results)) {
echo "<p><h3>" . $results['Name'] . "</h3>" . $results['Brewery'] . "</p>";
}
} else { // if there is no matching rows do following
echo "No results";
}
}
?>

PHP and SQL - Echoing Rows from Database [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am trying to select data from a database, dependent on the user and echo it in the html code, but for some reason it won't capture the data.. please see code below:
<?php
$loginuser = $_GET['uid'];
$check = mysql_query("select * from users where username='$loginuser'");
while($row = mysql_fetch_array($check)){
$result = $row['email'];
$result = $row['firstname'];
}
?>
<html>
<head>
<title> SIAA Dashboard </title>
</head>
<body>
<h1> User Dashboard </h1>
<p> You should only see this screen if you are a registered user. </p>
<?php
echo "Your username is: " . $loginuser . "<br><br>";
echo "Your first name is: " . $result=$row['firstname'] . " ";
?>
</body>
</html>
If someone could tell me what I'm doing wrong, it will be much appreciated!
Thanks
Sohail.
A few notes:
Don't use mysql_... functions: they're deprecated. See the documentation
Check whether the input is supplied using isset: if uid is missing from $_GET the visitor will see a PHP warning.
Escape/sanitize user input! If anyone requests your php file with ?uid='; drop table users;-- you're going to have a problem!
If you expect 0 or 1 results, don't use a while loop
Better not use constructs like echo "foo" . $bar = $baz . "something";: it's unclear.
And a suggestion on how to structure your page:
<html>
<head>
<title> SIAA Dashboard </title>
</head>
<body>
<?php
$loginuser = isset( $_GET['uid'] ) ? $_GET['uid'] : null;
if ( empty( $loginuser ) )
{
echo "Missing parameter!";
}
else
{
$check = mysql_query("select * from users where username='"
. mysql_real_escape_string( $loginuser ) . "'" );
if ( $row = mysql_fetch_array($check) )
{
?>
<h1> User Dashboard </h1>
<p> You should only see this screen if you are a registered user. </p>
Your username is: <?php echo $loginuser; ?>
<br><br>
Your first name is: <?php echo $row['firstname']; ?>
<?php
}
else
{
echo "Unknown user!";
}
}
?>
</body>
</html>
Besides that your code is prone to SQL injection as you do not sanitze the $__GET Parameter 'uid' before inserting it in the query and you are using the deprecated mysql extension, your problem is the line
echo "Your first name is: " . $result=$row['firstname'] . " ";
which should read
echo "Your first name is: " . $row['firstname'];
Additionally, you did not establish a connection to the database.
First do not use mysql_* functions and you need to create a mysql connection. This is still as risk for injection but should work.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$loginuser = $conn->real_escape_string($_GET['uid']);
$sql = "SELECT * FROM `users` WHERE `username` = '$loginuser'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$data = $result->fetch_assoc();
}
$conn->close();
?>
<html>
<head>
<title> SIAA Dashboard </title>
</head>
<body>
<h1> User Dashboard </h1>
<p> You should only see this screen if you are a registered user. </p>
<?php
echo "Your username is: " . $loginuser . "<br><br>";
echo "Your first name is: " . $data['firstname'] . " ";
?>
</body>
</html>
/*
* Best to start using PDO for db, If i was you i would rewrite your entire db script and stay away from mysql.
*
*/
$id = $_GET['uid'];
try {
$conn = new PDO('mysql:host=localhost;dbname=myDatabase', $DBusername, $DBpassword);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT * FROM users where username= :id');
$stmt->execute(array('id' => $id));
$result = $stmt->fetchAll();
if ( count($result) ) {
foreach($result as $row) {
print_r($row); // $row will give you access for your variables.
}
} else {
echo "No rows returned.";
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
<html>
<head>
<title> SIAA Dashboard </title>
</head>
<body>
<h1> User Dashboard </h1>
<p> You should only see this screen if you are a registered user. </p>
<?php
echo "Your username is: " . $loginuser . "<br><br>";
echo "Your first name is: " . $result=$row['firstname'] . " ";
?>
</body>
</html>

PHP form processing issue

PHP newbie here. I have struggling with this code for the past few days-
I have a dropdown menu. The options are coming from a table in my database-
<?php
include('Macintosh HD/Applications/MAMP/htdocs/Deals/processform3.php');
$host = 'localhost';
$username = '';
$password = '';
$database = 'database';
$conn = mysqli_connect($host, $username, $password, $database);
$query = mysqli_query($conn,"SELECT * FROM DealCat");
echo "<form action='processform.php' method='POST'>
<select name = 'dealcat'>/n";
while ($row = mysqli_fetch_assoc($query))
{
echo "<option value='{". $row['dealcat']."}'>" .$row['dealcat']."</option>";
}
echo "</select>\n";
?>
The navigation menu shows up fine on the webpage. However, I am not able to process user-input. I want the user to click on one of the options on my dropdown and PHP runs a script to get the results. I know this could be done with Javascript but I don't know that so trying to use only PHP.
Here is the form process script-
<?php
$host = 'localhost';
$username = '';
$password = '';
$database = 'database';
$conn = mysqli_connect($host, $username, $password, $database);
$dealcat=$_POST["dealcat"];
$query = "SELECT * FROM Deals WHERE dealcategory=\"{$_POST['$dealcat']"");
$result=mysqli_query($conn,$query) or die ("Couldn’t execute query.");
while($row = mysqli_fetch_assoc($result))
{
echo "<p>" . $row['description'] ."</p>";
echo "<br>";
echo "<a href =' {$row['weblink']}'> {$row['Header']}</a>";
echo "<br>";
echo "<br>";
echo "<button >Get Deal</button>";
echo "<hr>";
}
?>
Is there a way that PHP shows results based on user clicking on a dropdown option? Thanks a lot!
Try this
<select name="fieldname">
while ($row = mysqli_fetch_assoc($query))
{
echo "<option value=".$row['dealcat'].">".$row['dealcat']."</option>";
}
</select>

Pulling multiple fields from database using forms and php

I have a database with multiple rows with various fields.
I have a form that contains a drop down list.
The drop down list displays one of the database fields (field_name) for each row in the database.
When the user selects the desired entry hits SUBMIT, that value is passed to the results.php page and can be used via $_POST.
All of this currently works.
I would like a way to send the rest of the row's fields that correspond to the row of the selected field (not just the "field_name") from the database along with what is selected from the drop down menu.
For instance, if I have a database with rows with a fields named "name", "date", and "age", I would like to have all the database rows "name"s appear in the drop down list and once submitted, pass that particular name's "date" and "age" on to the results.php for use on that page.
<html>
<head>
<title>Drop Down Test</title>
</head>
<body style="font-family: verdana; font-size: 11px;">
<?php
//Variables for connecting to database.
$hostname = "abcd";
$username = "abcd";
$dbname = "abcd";
$password = "abcd";
$usertable = "abcd";
//Connecting to database
$connection = mysql_connect($hostname, $username, $password) OR DIE ("Unable to connect to database!");
$db = mysql_select_db($dbname);
$query = "SELECT * FROM abcd";
$result = mysql_query($query) or die(mysql_error());
?>
<h2>Drop Down Test Form</h2>
<p>Please fill out the form below and click submit.</p>
<form action="results.php" method="POST">
<p>Drop Down Test:
<select name='event'>
<!-- Drop down -->
<?php
while($row = mysql_fetch_array($result))
{
echo '<option>' . $row['field_name']. '</option>';
}
?>
</select>
<p><input type="submit" value="Submit"><p>
</form>
you should put a value on your option like this:
echo '<option value = "'.$row['field_name'].'" name = "">' . $row['field_name']. '</option>';
then you can access it by $_POST['event'];
UPDATE
getting all the values from the select, you can use $_SESSION variables to pass it to the other php.file.
// First of all, I advice you to connect via PDO, or at least msqli, because mysql_query is depreciated.
// To connect with database you need:
DEFINE("USER", "root");
DEFINE("DBNAME", "test");
DEFINE("DBPASSWORD", "");
DEFINE("DBHOST", "localhost");
$dbh = new PDO('mysql:host='.DBHOST.';dbname='.DBNAME,USER,DBPASSWORD,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
//The query:
$sth = $dbh->prepare("SELECT name,age,date FROM test");
$sth->execute();
//the drop down form
echo '<form action="results.php" method="POST">
<select name="event"><option value=0></option>';
while ($result = $sth->fetch(PDO::FETCH_ASSOC)) { extract($result);
echo '<option value="date:'.$date.'-age:'.$age.'"/>'.$name.'</option>';
echo '</select>
<p><input type="submit" value="Submit"><p>
</form>';
}
//the event in the records.php by clicking submit
if(isset($_POST['event'])){
echo 'name:',$name'-date:',$date,'-$age',$age;
}
This did the trick (in results.php):
<?php
$hostname = "****";
$username = "****";
$dbname = "****";
$password = "****";
$usertable = "abcd";
$connection = mysql_connect($hostname, $username, $password) OR DIE ("Unable to connect to database!");
$db = mysql_select_db($dbname);
//it was this SQL query that was the key, namely the WHERE statement
$query = "SELECT * from abcd where field_name='$_POST[event]'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_row($result);
echo "id: " . $row[0] . "<br/>";
echo "field_name: " . $row[1] . "<br/>";
//etc...
//try to throw the individual results into variables
$variable = $row[1];
echo "Check to see that the variable was passed a value: " . $variable . "<br />";
echo "Check to see that form selection carried over: " . $_POST['event'] . "<br />";
?>
I realize this is not the "up-to-date" way of doing things and I will now try to get everything "modernized".
Thanks for all the help!

Categories