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.
Related
I am simply trying to display data from a table in my database.
For some reason, it keeps rendering a blank page.
I have no training at all. SO I am sure my code looks like crap. But I can usually get it to work. I researched but all I could find were connection problems. I get a 'connected successfully' message but no data and no error message.
<?php
$db_host = 'localhost';
$db_user = 'user';
$db_pass = '';
$db_name = '';
$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$query = "SELECT * FROM `my_table`";
$result = mysql_query("SHOW COLUMNS FROM `my_table`");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
mssql_field_name($result,0);
// print_r($row);
}
}
?>
$db_name = ' ' ; is Null write Your Database Name
You should first provide a $db_name, because it's currently blank
$db_pass = '';
you need to provide your database name in here, else your application is literally trying to connect to nothing
You might have to check $mysqli_connect, that the $db_name=''; is null...put your database name inside ''
try like this.
<?php
$conn=mysqli_connect('localhost','root',' ','databasename');
$query="Select * from my_table";
$result = mysqli_query($conn,$query);?>
<table>
<tr>
<th>name</th>
<th>full_name</th>
</tr>
<?php
while($row = mysqli_fetch_assoc($result)) { ?>
<tr>
<td><?php echo $row["name"]; ?></td>
<td><?php echo $row["full_name"]; ?></td>
</tr>
<?php
}
?>
Please add your database name and database password, then you can try like this :
$sql = "Select * from table_name";
if ($result=mysqli_query($conn,$sql))
{
// Fetch one and one row
while ($row=mysqli_fetch_row($result))
{
$response[] = $row;
}
} else {
echo 'Could not run query: ' . mysqli_error();
exit;
}
print_r($response);
I wanna program a function that shows elements of my data base according to the input I enter
Here is my code but I got an error on the line 34
Notice: Undefined index: table[1]["des_dem"] in
C:\xampp\htdocs\gpc\test.php on line 34
<?php
$element = $_GET["element"];
echo $element;
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "gpc";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// $sql = "SELECT * FROM bons WHERE des_dem='$element'" ;
$sql = "SELECT * FROM bons" ;
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$table = $result->fetch_all(MYSQLI_ASSOC);
} else {
echo "0 results";
}/*
echo $table[1]["des_dem"];
echo "<br>";
echo $table[1]["des_dec"]; */
function afficher()
{
echo $GLOBALS['table[1]["des_dem"]'];
}
echo $table[4]["des_dec"];
echo "<br>";
afficher();
$conn->close(); ?>
<html>
<body>
<br>
<form action="test.php" method="get">
<tr>
<td>Name</td>
<td><input type="text" name="element"></td>
</tr>
<input type="submit" value="Submit">
</form>
</body>
</html>
Thanks a lot for answering my questions :)
You will have to use the global keyword to do this, you cannot call it within the $GLOBALS array like that, do this..
function afficher()
{
global $table;
echo $table[0][1];
}
I have a notification page. Here's my notification code:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testdb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM notification ORDER BY date desc";
$result = $conn->query($sql);
?>
<table>
<thead>
<tr style="background-color: #eee">
<th width="20%">Activity</th>
<th width="40%">Description</th>
<th width="20%">Date</th>
<th width="20%">Action</th>
</tr>
</thead>
<tbody>
<?php
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<tr>';
echo '<td width="20%">'.$row['activity'].'</td>';
echo '<td width="40%">'.$row['description'].'</td>';
echo '<td width="20%">'.$row['date'].'</td>';
?>
<td><a href="/test/admin/requests.php?view_id=<?php echo $row['id']; ?>" >VIEW</a></td>
<?php echo '</tr>';
}
// echo '<td width="20%">'.$row['date'].'</td>';
// echo '</tr>';
}
else {
echo "You have no notifications yet";
}
$conn->close();
$conn=mysql_connect("localhost", "root");
mysql_select_db("testdb", $conn);
if (! $conn){
DIE('Could not connect: ' . mysql_error());
}
$query="UPDATE notification set status ='read'";
$retval = mysql_query( $query, $conn );
?>
</tbody>
</table>
Output:
The code behind that VIEW link is:
<td><a href="/test/admin/requests.php?view_id=<?php echo $row['id']; ?>" >VIEW</a></td>
Now, for instance I click the VIEW link in of the "NEW MEMBERSHIP REQUEST" (refer to the photo please), the URL will lead me to that link and it should the information that I need to view or display for that certain member. And that's where my problem is because whenever I click the click, the information don't show up on the page, but the URL gives the correct ID number of that member..
This code is the page where the information of that certain member should appear when ever I click the link. But it display nothing but the correct id number. Help me please.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testdb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_GET['id']))
{
$id=$_GET['id'];
$sql = ("SELECT * FROM requests where id = ".$id);
$result = $conn->query($sql);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
?>
<?php echo $id ?>
<br/>Name: <?php echo $row['name'] ?>
<br/>Age: <?php echo $row['age'] ?>
<br/>Date of Birth: <?php echo $row['dob'] ?>
<br/>Occupation: <?php echo $row['occupation'] ?>
<?php
}
?>
The name, age, date of birth and occupation are examples of the data that I'm saying which doesn't show up. But there was no error. Please please I wish someone could help me out.
ADDITIONAL:
My notification table has 6 fields:
id, user, activity, desc, status, date
Requests table has 5 fields:
id, name, occupation, dob, age
When the user submits his membership form, the details he had input like name, occupation, dob, and age will be inserted requests table and at the same time it will notify the admin though the notification table/page. Now when I click that link, the ID that shows is the ID from the notification and not from the requests where his datas were stored. So I guess that's where my mistake is. And I just realized that. Hope you can still help me figure out how to get that id from the requests table. I hope I explained my problem well. I understand if you guys didn't understand it. Thank you for those who helped and for those who will help me. :)
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testdb";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_GET['id']))
{
$id=$_GET['id'];
$sql = "SELECT * FROM requests where id ='$id' ";
$result = $conn->query($sql);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
?>
<?php echo $id ?>
<br/>Name: <?php echo $row['name'] ?>
<br/>Age: <?php echo $row['age'] ?>
<br/>Date of Birth: <?php echo $row['dob'] ?>
<br/>Occupation: <?php echo $row['occupation'] ?>
<?php
}
?>
You are mixing OOP with procedural method. Use either one of them. If you are using OOP then don't use this:
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
It should be
$row=$result->fetch_array(MYSQLI_ASSOC);
I am trying to populate a dropdown list with PHP from a MySQL database. Right now nothing is populating in my dropdown. I have made sure I have the correct database name, server name, username, and password.
Here is my PHP file queryfunction.php:
<?php
function connect(){
$servername = "localhost";
$username = "root";
$password = "******";
$database = "lab4";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
mysqli_select_db($database);
}
function close(){
mysqli_close();
}
function query(){
$mydata = mysqli_query("Select * from country");
while($record = mysqli_fetch_array($mydata)){
echo '<option value = "' . $record['CountryAbbreviation'] . '">' .$record['CountryAbbreviation'] . '"</option>';
}
}
?>
Here is is my PHP file where I call this:
<?php
include_once "queryfunction.php";
connect();
?>
<!DOCTYPE html/>
<html>
Further down in the doc within a table:
<tr>
<th>Country</th>
<td>
<select name="CountryDropDown">
<?php query() ?>
</select>
<?php close()?>
</td>
</tr>
Try with change this line while($record = mysqli_fetch_array($mydata)){ to this while($record = mysqli_fetch_array($mydata,MYSQLI_ASSOC)){
or show us your $record variable data
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']);
}