My goal is to populate an HTML select box from MySQL using a PHP function. I started by putting the code directly on the HTML page, and I got it working.
<label for="product_Category">Product Category</label>
<?
$field_Name = "category_Name";
$table_Name = "Product_Category";
$sql = "Select " . $field_Name . " From " . $table_Name;
$results = mysqli_query($link, $sql);
echo "<select>";
echo "<option value = \" \" >Select Category"</option>;
while($row = mysqli_fetch_array($results, MYSQLI_ASSOC)){
echo "<option value = ' " .$row[$field_Name] . "'>" . $row[$field_Name]. "</option>";
}
echo "</select>";
?>
I have multiple select boxes, so I thought it would be easier to create a function and pass the table name, and field name as arguments
I moved the PHP function to its own file, and use an include statement in my HTML. But once I tried to call the PHP function, the select box won't populate. The select box shows up on the form like it should, but its empty.
PHP
<?
function Populate_Select($table_Name, $field_Name){
$sql = "Select " . $field_Name . " From " . $table_Name;
$results = mysqli_query($link, $sql);
echo "<select>";
echo "<option value = \" \" >Select Category </option>";
while($row = mysqli_fetch_array($results, MYSQLI_ASSOC)){
echo "<option value = ' " .$row[$field_Name] . "'>" . $row[$field_Name]. " </option>";
}
echo "</select>";
}
?>
DB Config
<?
$host = "localhost";
$db_userName = "root";
$db_Password = "root";
$db_Name = "mydb";
$link = mysqli_connect($host, $db_userName, $db_Password, $db_Name);
if (!$link){
die("Database Connection failed " . mysqli_connect_error);
}
?>
HTML Code
<? include 'PopulateSelect.php' ?>
<? include 'DB_Config.php ?>
<!--Rest of HTML CODE-->
<label for="product_Category">Product Category</label>
<? Populate_Select('Product_Category', 'category_Name'); ?>
Where did I go wrong when I called the function?
Is it better practice to use a function or am I better off just writing separate code for each select box?
The problem is that your $link variable is not defined. You need to create a class, OOP makes life easier, like this:
//myclass.php
class MyClass {
private $link;
function __construct() {
$host = "localhost";
$db_userName = "root";
$db_Password = "root";
$db_Name = "mydb";
$this->link = mysqli_connect($host, $db_userName, $db_Password, $db_Name);
if (!$this->link) {
die("Database Connection failed " . mysqli_connect_error);
}
}
function __destruct() {
mysqli_close($this->link);
}
function Populate_Select($table_Name, $field_Name) {
$sql = "Select $field_Name From $table_Name";
$results = mysqli_query($this->link, $sql);
$select = "<select>";
$select .= "<option value=''>Select Category</option>";
while ($row = mysqli_fetch_array($results, MYSQLI_ASSOC)) {
$select .= "<option value='$row[$field_Name]'>$row[$field_Name]</option>";
}
$select .= "</select>";
return $select;
}
}
Then you can call this on your other pages by including that .php file and accessing the class, like this:
//your some_html.php
include 'myclass.php';
$obj = new MyClass();
$select = $obj->Populate_Select("your_table_name", "your_field_name");
echo $select;
It looks like your $link object is not available in the function you declared. Try passing the $link object to the function.
It could look something like this:
function Populate_Select($link, $field_Name, $table_Name){ ... }
You could also pass the connection as a reference to the function.
function Populate_Select($field_Name, $table_Name, &$link){ ... }
And then when you call it, add $link as the third argument. Otherwise, you're looking for a global variable inside of a function.
Related
I am new to php. I have the following code that auto fetches all the rows and columns from the db. I want to make the script to fetch a particular row using its ID column. for example: www.site.com/view.php?id=22
I am trying to get it work with the $_GET['link']; variable like this:
if (isset($_GET['id'])) {
$result = mysqli_query($connection,"SELECT * FROM $_GET['link']");
} else {
$result = mysqli_query($connection,"SELECT * FROM reservations");
}
But I am unable to get it work.
The complete code is as below:
<?php
$host = "localhost";
$user = "user";
$pass = "Pass1";
$db_name = "test";
//create connection
$connection = mysqli_connect($host, $user, $pass, $db_name);
//test if connection failed
if(mysqli_connect_errno()){
die("connection failed: "
. mysqli_connect_error()
. " (" . mysqli_connect_errno()
. ")");
}
//get results from database
$result = mysqli_query($connection,"SELECT * FROM reservations");
$all_property = array(); //declare an array for saving property
//showing property
echo '<table class="data-table" border="1">
<tr class="data-heading">'; //initialize table tag
while ($property = mysqli_fetch_field($result)) {
echo '<td>' . $property->name . '</td>'; //get field name for header
array_push($all_property, $property->name); //save those to array
}
echo '</tr>'; //end tr tag
//showing all data
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
foreach ($all_property as $item) {
echo '<td>' . $row[$item] . '</td>'; //get items using property value
}
echo '</tr>';
}
echo "</table>";
?>
Any help would be appreciated..
You can do this
Add
$query = 'SELECT * FROM reservations';
if (!empty($_GET['id']) and ($id = (int)$_GET['id']))
$query .= " WHERE id = {$id} LIMIT 1";
and change this
mysqli_query($connection,"SELECT * FROM reservations");
to this
$result = mysqli_query($connection, $query);
In the above code I added a bit of security so that if $_GET['id'] is not a valid integer it will revert to query where it fetches all the data. I added that because you should never put $_GET directly into your query.
Here is a your code I have modified it to your requirements
<?php
$host = "localhost";
$user = "user";
$pass = "Pass1";
$db_name = "test";
//create connection
$connection = mysqli_connect($host, $user, $pass, $db_name);
//test if connection failed
if(mysqli_connect_errno()){
die("connection failed: "
. mysqli_connect_error()
. " (" . mysqli_connect_errno()
. ")");
}
$query = 'SELECT * FROM reservations';
if (!empty($_GET['id']) and ($id = (int)$_GET['id']))
$query .= " WHERE id = {$id} LIMIT 1";
//get results from database
$result = mysqli_query($connection, $query);
$all_property = array(); //declare an array for saving property
//showing property
echo '<table class="data-table" border="1">
<tr class="data-heading">'; //initialize table tag
while ($property = mysqli_fetch_field($result)) {
echo '<td>' . $property->name . '</td>'; //get field name for header
array_push($all_property, $property->name); //save those to array
}
echo '</tr>'; //end tr tag
//showing all data
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
foreach ($all_property as $item) {
echo '<td>' . $row[$item] . '</td>'; //get items using property value
}
echo '</tr>';
}
echo "</table>";
if(isset($_GET['id'])) {
$id = $_GET['id'];
} else {
$id=NULL;
}
$sql = "SELECT * FROM reservations WHERE id = '".$id."'";
$result = mysqli_query($connection,$sql);
$row = mysqli_fetch_assoc($result);
if(mysqli_num_rows($result) == 1) {
dd($row);
} else {
echo "no records found with this id";
}
Hope this script meets your answer
Sorry for asking a duplicate question. I tried few ways given on this website for fetching data. But any of them did not work. I'll put my coding down below.
<?php
mysql_connect('localserver', 'root', '123');
mysql_select_db('database');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
echo "Connected successfully";
$sql = "SELECT name FROM company";
$result = mysql_query($sql);
echo "<select name='name'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['name'] ."'>" . $row['name'] ."</option>";
}
echo "</select>";
}
?>
Any help would be greatly appreciated.
I think you could use this code.
Make sure you have the correct credentials.
establish your DB connection :
<?php
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT name FROM company";
$result = $conn->query($sql);
$conn->close();?>
Then to view the results in your html:
<select name="name">
<?php
while($row = $result->fetch_assoc()) {
echo "<option value='" . $row['name'] ."'>" . $row['name'] ."</option>";
}
?>
</select>
I think this would do the trick.
I am trying to get my PHP script to print all rows i have in my database in a neat order. Currently Im not getting anything. My table has 4 columns, Name, Address, Long and Lat, and 2 rows with data. The table is called Locations. I am using the following code but im not getting to to work:
<?php
$con=mysqli_connect("localhost","user","pass","db");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM `Locations` ";
if ($result = mysqli_query($con, $sql))
{
$resultArray = array();
$tempArray = array();
while($row = $result->fetch_object())
{
$tempArray = $row;
array_push($resultArray, $tempArray);
}
echo json_encode($resultArray);
}
// Close connections
mysqli_close($con);
?>
Here is a simple example using pdo instead of mysqli
$dbHOST = 'localhost';
$dbNAME = 'nilssoderstrom_';
$dbUSER = 'nilssoderstrom_';
$dbPASS = 'Durandal82!';
$pdo = new PDO('mysql:host=' . $dbHOST . ';dbname=' . $dbNAME, $dbUSER, $dbPASS); // create connection
$stmt = $pdo->prepare("SELECT Name, Address, Long, Lat FROM Locations");
//you should never use *, just call each field name you are going to use
$stmt->execute(); // run the statement
$arr = $stmt->fetchAll(PDO::FETCH_ASSOC); // fetch the rows and put into associative array
print_r($arr); // print all array items, unformatted
and you can echo out the data and format it yourself using a for loop like so
for($i=0; $i<sizeof($arr); $i++) { // this will loop through each row in the database. i prefer this method over while loops as testing has shown this is much faster for large scale tables
echo 'Name: ' . $arr[$i]['Name'] . '<br />'; // $arr is the array name, $i is the number of the array item, or iterator, ['Name'] is the field name
echo 'Address: ' . $arr[$i]['Address'] . '<br>';
echo 'Long: ' . $arr[$i]['Long'] . '<br>';
echo 'Lat: ' . $arr[$i]['Lat'] . '<br>';
}
If the names are correct, this would echo out your row ID and row CITY. Just change the names to your field names. If you want further assistance, feel free to ask.
However, if you want to stick with mysqli, give the following code a wirl.
$dbHOST = 'localhost';
$dbNAME = 'nilssoderstrom_';
$dbUSER = 'nilssoderstrom_';
$dbPASS = 'Durandal82!';
$mysqli = mysqli_connect($dbHOST, $dbUSER, $dbPASS, $dbNAME);
$query = "SELECT Name, Address, Long, Lat FROM Locations";
$result = mysqli_query($mysqli, $query);
if($result) {
while($row = mysqli_fetch_assoc($result)) {
echo 'Name: ' . $row['Name'] . '<br />';
echo 'Address: ' . $row['Address'] . '<br>';
echo 'Long: ' . $row['Long'] . '<br>';
echo 'Lat: ' . $row['Lat'] . '<br>';
}
}
change fieldname to the field you want to display
EDIT: Paste the following code. It will echo out the number of rows. This will tell you if the query statement is correct.
$dbHOST = 'localhost';
$dbNAME = 'nilssoderstrom_';
$dbUSER = 'nilssoderstrom_';
$dbPASS = 'Durandal82!';
$pdo = new PDO('mysql:host=' . $dbHOST . ';dbname=' . $dbNAME, $dbUSER, $dbPASS);
$stmt = $pdo->query("SELECT Name, Address, Long, Lat FROM Locations");
echo $stmt->rowCount();
Fetch query result as associative array and use for each to print all results
<?php
$con=mysqli_connect("localhost","user","pass","db");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM `Locations` ";
if ($result = mysqli_query($con, $sql))
{
while($rows = mysqli_fetch_assoc($result)) {
foreach($rows as $key => $val)
{
echo $val;
}
}
}
mysqli_close($con);
?>
so the line of code
echo "<option value = '$name'>$name</option>";
is where i am having a problem. I am trying to get drop down menu to have the values of every name in the database. here is my code, it is in a html file:
<select name = "author" id = "author">
<?php
$servername = "localhost";
$username = "user";
$password = "pass";
$database = "db";
$con = mysqli_connect($servername,$username,$password,$database);
if($con->connect_error){
die("Connection failed " . $con->connect_error);
}
$sql = "select first, last from Employee";
$result = mysqli_query($con,$sql);
while ($row = mysqli_fetch_array($result)) {
$name = $row['first'] . ' ' . $row['last'];
echo "<option value = '$name'>$name</option>";
/*echo <<<EOT
<option value = '$name'>$name</option>"
EOT;*/
}
?>
</select>
I have tried it using a normal string, and as an EOT. Currently when i look at the html page it shows "$name" instead of the actual name. I have done output testing and $name is storing what i expect it to store.
I just take a step in the dark, You saved your file as HTML (.html) and not as a PHP file (.php)?
Try:
echo "<option value = '".$name."'>".$name."</option>";
or
echo "<option value = '{$name}'>{$name}</option>";
I remember there being something about PHP not processing variables between single quotes. The best way may be to break and concat the string
echo "<option value = '".$name."'>$name</option>";
I am trying to retreive data from a database and populate a list from it, there doesnt seem to be errors in my code and still the list is not populating, my code
<?php
$hostname = "localhost";
$username = "username";
$password = "password";
$dbase = "db";
$link = # mysql_connect($hostname, $username, $password);
$db_selected = # mysql_select_db($dbase);
?>
<?php
include("scripts/dbconnect.php");
$query="select class from school";
$result=mysql_query($query);
$numrows=mysql_num_rows($result);
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)){
echo '<option value="'.$row['class'].'">'.$row['class'].'</option>';
}
?>
any help much appreciated, thanks
Options must be wrapped with select tag:
echo "<select name='class'>";
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)){
echo '<option value="'.$row['class'].'">'.$row['class'].'</option>';
}
echo "</select>";
Additionally do:
if (!$link) {
die('Could not connect: ' . mysql_error());
break;
}
To see if there are any errors of mysql connection.
You need to echo a select element.
<?php
include("scripts/dbconnect.php");
$query="select class from school";
$result=mysql_query($query);
$numrows=mysql_num_rows($result);
echo "<select>"
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)){
echo '<option value="'.$row['class'].'">'.$row['class'].'</option>';
}
echo "</select>"
?>