Dropdown not populating from MySQL - php

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

Related

How to write WHERE referring to a drop down list select?

There is a drop-down list on the PHP website that contains names taken from the database,
after selecting a name from the list, e.g. "Aprilia", I would like all records to be displayed from the database
where mark = Aprilia
I know I should add in the code below just in a SELECT WHERE x = y query
but I just don't know how to do it;
it should look like this in my opinion:
$result = mysqli_query($conn, "SELECT * FROM motorcycles WHERE mark = X");
And I just can't find this X (X should be the user pick from the dropdown list)
How to write it?
Photos:
https://imgur.com/a/PMu4At7
<?php
require_once 'header.php';
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "projectinz";
// Create connection
//$conn = new mysqli($servername, $username, $password, $dbname);
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
<select name="mark" id="mark">
<?php
$query = $conn->query("SELECT mark FROM motocykle");
while($kategoria = mysqli_fetch_array($query))
{
echo '<option>'.$kategoria['mark'].'</option>';
}
?>
</select>
<?php
$wynik = mysqli_query($conn,"SELECT * FROM motocykle");
while($row = mysqli_fetch_array($wynik))
{
echo "<br>".$row['mark']." ".$row['model']." ".$row['capacity']." ".$row['power']."<br>";
}
mysqli_close($conn);
?>
</body>
</html>
EDIT !!!
find1.php
<?php
require_once 'header.php';
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "projectinz";
// Create connection
//$conn = new mysqli($servername, $username, $password, $dbname);
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
<form action="../includes/find.inc.php" method="post">
<select name="mark" id="mark">
<?php
$query = $conn->query("SELECT mark FROM motocykle");
while ($kategoria = mysqli_fetch_array($query)) {
echo '<option value="id">'.$kategoria['mark'].'</option>';
}
?>
</select>
<button type="submit" name="findmoto">Find</button>
</form>
<?php
$wynik = mysqli_query($conn,"SELECT * FROM motocykle ");
while ($row = mysqli_fetch_array($wynik)) {
echo "<br>".$row['mark']." ".$row['model']." ".$row['capacity']." ".$row['power']."<br>";
}
mysqli_close($conn);
?>
</body>
</html>
find.inc.php
<?php
session_start();
if (isset($_POST['findmoto'])) {
require 'dbh.inc.php';
$id = $_POST["id"];
$marka = $_POST["mark"];
echo $id;
echo $marka;
$display = "SELECT * FROM motocykle WHERE id='$id';";
$run = mysqli_query($conn, $display);
if ($run) {
echo $display;
} else {
echo "not";
}
}
BUT:
https://imgur.com/a/RA5wuus
Where is the problem?
<option value="1">Name</option> has attribute value witch is sent to POST when form is submitted. You need to set it with probably ID from table and then after POST you filter by that ID in WHERE part of your SQL.
First change
<select name="mark" id="mark">
<?php
$query = $conn->query("SELECT id, mark FROM motocykle");
while($kategoria = mysqli_fetch_array($query))
{
echo '<option value="'.$kategoria['id'].'">'.$kategoria['mark'].'</option>';
}
?>
</select>
Second change
if(isset($_POST['findmoto'])) {
require 'dbh.inc.php';
$selectedId = intval($_POST["mark"]);
echo $selectedId;
$display = "SELECT * FROM motocykle WHERE id='$selectedId';";
$run = mysqli_query($conn, $display);
if($run)
{
echo $display;
}
else
{
echo "not";
}
}

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.

Trying to echo out every name in database table inside hrml list

I have been trying to echo out database data through a while loop now for awhile but it doesn't work, I can't find where the issue is. I have tried echoing out data manually and that works just fine.
<?php $results = mysqli_query($con,"SELECT * FROM guestbook ORDER BY id DESC"); ?>
<?php while ($row = mysqli_fetch_assoc($results)) : ?>
<li>
<?php echo $row['message']; ?>
</li>
<?php endwhile ?>
First of all make sure you are connected to the database. I don't know if you omitted that on purpose or not. Also, check if the connection is established.
<?php
//Insert your server info here
$servername = "servername";
$username = "root";
$password = "root";
$dbname = "test_database";
// Create and check your connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM guestbook ORDER BY id DESC";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo '<li>' . row["message"] . '</li>';
}
} else {
// Your query produced 0 results
echo "Empty result!";
}
// Remember to close the connection
mysqli_close($conn);
?>

How to show table from MySQL database using php and html

I am trying to connect my html page with MySQL database to show data from one specific table to my page, but I always get an error actually it just goes to die part of an SQL code. I am really new to PHP programming so please can someone help me, what am I doing wrong?
Here is my code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>AJDE</title>
</head>
<?php
$servername = "localhost";
$username = "******";
$password = "*****";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$query = "select * from PERCENTILE";
$result = mysqli_query($conn,$query);
if(!$result) {
die ("Umro!");
}
/* close connection */
$mysqli->close();
?>
<body>
</body>
</html>
Thank you!
Do you want to show the table as a HTML table or just an array?
The following is what I did to display my table as a HTML table:
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '*****';
$dbname = 'dbname';
$selectedTable = 'whateverTableYouWant';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname);
if (!$conn){
die('cannot connect to mysql');
}
$query = "SELECT * FROM $selectedTable";
if ($result = mysqli_query($conn , $query)) {
echo("<div class = 'data_wrapper'>");
// Display Header of the table
$fieldcount=mysqli_num_fields($result); //value = number of columns
$row = mysqli_fetch_assoc($result); //Fetch a result row as an associative array:
//array to string conversion
echo("<table id='example' class='table table-striped table-bordered' cellspacing='0' width='100%'>");
echo("<thead> <tr>");
foreach($row as $item){
echo "<th>" .$item. "</th>";
}
echo("</tr> </thead>");
//Footer
echo("<tfoot> <tr>");
foreach($row as $item){
echo "<th>" .$item. "</th>";
}
echo("</tr> </tfoot>");
//Display Data within the table
echo("<tbody>");
while ($row = mysqli_fetch_assoc($result)){
echo "<tr>";
foreach ($row as $item){
echo "<td contenteditable = 'true'>" . $item . "</td>"; //Change contenteditable later
//Editable data should be constricted, int = numbers only, string = words, date = date
}
echo "</tr>";
}
echo("<tbody>");
echo "</table>";
echo("</div>");
}
The following is just displaying as an array:
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '*****';
$dbname = 'dbname';
$selectedTable = 'whateverTableYouWant';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname);
if (!$conn){
die('cannot connect to mysql');
}
$query = "SELECT * FROM $selectedTable";
if ($result = mysqli_query($conn , $query)) {
while ($row = mysqli_fetch_array($result)){
print_r($row);
}
}
Please change the connection string like mentioned below.
<?php
$con = mysqli_connect("localhost","username","password","dbname");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
Please let me know if you've any queries.
I Think you need to select a database where you will run the query:
Try with this code:
<?php
$username = "your_name";
$password = "your_password";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
//select a database to work with (so replace the database name examples)
$selected = mysql_select_db("examples",$dbhandle)
or die("Could not select examples");
//execute the SQL query and return records
$result = mysql_query("SELECT * FROM PERCENTILE");
//fetch the data from the database and display results
//replace id,name,year with the columns you have on your table PERCENTILE and you want to show
while ($row = mysql_fetch_array($result)) {
echo "ID:".$row{'id'}." Name:".$row{'name'}."Year: ". $row{'year'}."<br>";
}
//close the connection
mysql_close($dbhandle);
?>
Hope it helps,
Vince.

How to display member request Information from DB when clicking a link

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);

Categories