Extracting values from a database to populate a dropdown - php

I have a db, am trying to extract values into a list
Here is the code I am trying to run (I had to adapt it from elsewhere), which should return an array, from which I want to select the AllianceName attribute
<?php
//database connection file setting.inc will need to be modified for production
include ("settings.inc");
$con = mysqli_connect("$dbhost", "$dbuser", "$dbpass");
if (!$con) {
exit('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
//set the default client character set
mysqli_set_charset($con, 'utf-8');
mysqli_select_db($dbname, $con);
$options = array();
$options[] = "<option value=''>--?--</option>";
$query = "
SELECT *
FROM `City`
GROUP BY `AllianceName`
";
$db = mysqli_query($query);
foreach ( $db as $d ) {
$options[] = "<option value='{".$d['AllianceName']."}'></option>";
}
?>
<select class="" id="articles" size="1" name="articles">
<?php echo implode("\n", $options); ?>
</select>*/
Right now this only returns the --?-- that I have defined in the options array. It does not parse any of the values from the query. I know the query by itself is correct since I have run it exactly in this syntax in the SQL server and it works.
I am pretty sure that this is a syntax error ... var_dump($db) gives me a bool(false) output.
Here's the latest code I am using:
<?php
//database connection file setting.inc will need to be modified for production
include ("settings.inc");
$db = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
?>
<select class="Select" id="articles" size="1" name="articles">
<?php
$sql = <<<SQL
SELECT DISTINCT `AllianceName`
FROM `City`
SQL;
if(!$result = $db->query($sql)){
die('There was an error running the query [' . $db->error . ']');
}
while($row = $result->fetch_assoc()){
echo "<option value="'.{$row['AllianceName']}.'"></option>";
}
?>
</select>
The query by itself runs fine when I just echo the results. Trying to put it into a dropdown fails every time. No values get populated.

There are a couple problems here.
First you don't need the GROUP BY 'AllianceName' in your query, you are not performing any functions on your data, that might have been causing you to not return any results.
Secondly, normally you loop through query results with a while loop. You don't have to, but its common practice, so your code should look like this..
<?php
//database connection file setting.inc will need to be modified for production
include ("settings.inc");
$con = mysqli_connect("$dbhost", "$dbuser", "$dbpass", "$dbname");
if (!$con) {
exit('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
//there is no need to make an array first, just have it spit out the options if you aren't making a class or function
?>
<select class="" id="articles" size="1" name="articles">
<?php
$query = "SELECT * FROM `City` ";
$db = mysqli_query($query);
while ( $d=mysqli_fetch_assoc($db)) {
echo "<option value='{".$d['AllianceName']."}'></option>";
}
?>
</select>
Try that out and see if it works for you.

From the mysqli_query() docs:
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or
EXPLAIN queries mysqli_query() will return a mysqli_result object. For
other successful queries mysqli_query() will return TRUE.
So what you have after the query succeeded is a mysqli_result object. Now you have to fetch the result into an (associative) array or object, row by row.
if($query === false) die('Query failed to execute');
while($row = $result->fetch_assoc()) {
echo $row['AllianceName'] . PHP_EOL;
}
All this is described in hundreds of tutorials in the web, so please read one of these. I recommend these written in the current decade, e.g. http://codular.com/php-mysqli

Here is the code that finally worked. Both #Syndrose and #Zombiehunter provided clues to this.
#Syndrose - you might want to take into account the syntax used here as this is what was failing from your codebase...especially the syntax for the echo tag line.
<?php
//database connection file setting.inc will need to be modified for production
include ("settings.inc");
$db = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
$sql = <<<SQL
SELECT DISTINCT `AllianceName`
FROM `City`
SQL;
if(!$result = $db->query($sql)){
die('There was an error running the query [' . $db->error . ']');
}
?>
<select style="width:300px" class="" id="AllianceName" size="1" name="Alliance Name">
<?php
while($row = $result->fetch_assoc()){
echo '<option value='.$row['AllianceName'].'>'.$row['AllianceName'].'</option>';
}
?>
</select>

Related

Creating Dropdown list from sql database in PHP

*The condition for "die" had been left out of my code by mistake when I copied it to the question. I put it back in.
I know this question might seem repetitive, but I have not found an answer in any of the other questions. I am trying to create a drop-down list based off a column in a database. I have tried two different ways and neither gave me correct results. Does anyone know a correct way of doing this?
The first way I saw in other StackOverflow answers (Fetching data from MySQL database to html drop-down list, Fetching data from MySQL database to html dropdown list). My code is below:
<?php
$connect = mysql_connect('localhost', 'root');
if ($connect == false)
{
die ("Unable to connect to database<br>");
}
$select = mysql_select_db('ViviansVacations');
if ($select == false)
{
die ("Unable to select database<br>");
}
$query = "SELECT * FROM Destinations";
$result = mysql_query($query);
?>
<select name="select1">
<?php
while ($row = mysql_fetch_array($result))
{
echo "<option value='". $row['Europe'] ."'>" .$row['Europe'] ."</option>" ;
}
?>
</select>
NetBeans sends me an error saying that "Text not allowed in element 'select' in this context".
The second way I tried:
<?php
$connect = mysql_connect('localhost', 'root');
{
die ("Unable to connect to database<br>");
}
$select = mysql_select_db('ViviansVacations');
{
die ("Unable to select database<br>");
}
$query = "SELECT * FROM Destinations";
$result = mysql_query($query);
?>
<select name="select1">
<?php
while ($line = mysql_fetch_array($result))
{
?>
<option value="<?php echo $line['Europe'];?>"> <?php echo
$line['field'];?> </option>
<?php
}
?>
</select>
This code did not produce any errors. However, inside the form were the opening php lines followed by an empty drop down box:
"); } $select = mysql_select_db('ViviansVacations'); { die ("Unable to select database
"); } $query = "SELECT * FROM Destinations"; $result = mysql_query($query); ?>
So there are many problems with your approach. First of all you are using a deprecated mysql_* functions which is bad idea and second you are not debugging your database connection properly :
$connect = mysql_connect('localhost', 'root');
{
die ("Unable to connect to database<br>");
}
In above code the die statement will always execute stopping further execution.
Also make sure the database ViviansVacations and table Destinations and column Europe exists with correct names(Follow standards and try to use all small letters for database/table/column naming)
The correct mysqli_* approach is(tested locally and the select box forms correctly) :
<?php
$db = 'ViviansVacations';
$mysqli = new mysqli('localhost', 'root', '', $db);
if($mysqli->connect_error)
die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
$query = "SELECT * FROM Destinations";
$result = mysqli_query($mysqli, $query);
?>
<select name="select1">
<?php
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['Europe'] . "'>" . $row['Europe'] . "</option>";
}
?>
</select>
There are couple of things, you to verify and correct.
First of all, your database connection code, that doesn't seems to be correct. I didn't see any condition on which you are suppose to invoke die.
$connect = mysql_connect('localhost', 'root');
{
die ("Unable to connect to database<br>");
}
From the above code, below line will execute all the time
die ("Unable to connect to database<br>");
You should correct your database connection code to below :
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
You can refer mysql_connect for the usage.
Also, verify your file extension is .php
Mainly your problem is database connection. Try this -
<?php
mysql_connect("localhost", "root", "") or
die("Could not connect: " . mysql_error());
mysql_select_db("your_db");
$result = mysql_query("SELECT * FROM your_table");
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
print_r($row);
echo "<br>";
}
mysql_free_result($result);
?>
There could be few issues:
Use mysqli_connect instead of mysql_connect because mysql is depreciated
Make 3rd parameter as empty `mysqli_connect('localhost', 'root', '');//as per standards
Debug your code for example: (print_r($connect), execute your query in phpmyadmin, print_r($result) and then in loop print_r($row).
At end, I am sure you will get your desired result and also you will know in detail that what was happening.
You might want to try to use this ..The dept_id and the description u have to change according to your database .Hope this will help you
<?php
$sql = mysql_query("SELECT dept_id ,description FROM department
ORDER BY dept_id ASC");
db_select($sql,"dept_id",$dept_id,"","-select Department-","","");
?>

Calculate sum in mysqli database

I have a small database with products and prices. I want to calculate the sum of the column "orderpris", in my table called orders. And print this to the screen. Not sure if I'm anywhere near the solution but I thought this would work but it dont. What have I done wrong?
<?php
function sum() {
/* Connect to database */
$db = new mysqli('localhost', 'admin2', 'password', 'myshop');
if($db->connect_errno > 0){
die('Fel vid anslutning [' . $db->connect_error . ']');
}
$results = mysqli_query("SELECT sum(orderpris) FROM orders") or die(mysqli_error());
while ($rows = mysqli_fetch_array($results)) {
}
?>
<div>
Total: <?php echo $rows['sum(orderpris)']; ?>
</div>
<?php }
?>
<?php
sum();
?>
Try this:
<?php
function sum() {
/* Connect to database */
$db = new mysqli('localhost', 'admin2', 'password', 'myshop');
if ($db->connect_errno > 0) {
die('Fel vid anslutning [' . $db->connect_error . ']');
}
$results = mysqli_query($db, "SELECT sum(orderpris) as total FROM orders") or die(mysqli_error());
while ($rows = mysqli_fetch_array($results)) {
$iResult = 'Total:'.$rows['total'];
}
return $iResult;
}
echo sum();
1- I have changed:
$results = mysqli_query($db, "SELECT sum(orderpris) as total FROM orders") or die(mysqli_error());
Instead:
$results = mysqli_query("SELECT sum(orderpris) FROM orders") or die(mysqli_error());
As you can see, mysqli_query function needs at least two parameters:
-A link identifier, in your case it is $db
-The query string.
2- I have added an alias 'total' to the query
-It works, but try to don't use database connection into your function, suppose that you have several functions and you need to connect to database , you will be repeating the same action every time.
-Try to move sum() function to a class
-Try to create a unique way to database connection and not several connections for each function.

PHP: connected to database, but mysql_query fails

I have very strange problem with PHP which I am starting to learn .. I have created tables in MySQL database with some data, and now I want to show them in webpage.
This is my source where I have this problem:
<?php
// Here I open connection
$con = mysql_connect("localhost","root","aaaaaa");
// set the mysql database
$db = mysql_select_db("infs", $con);
// I check the connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else {
// It always goes here
echo "Connected to database!";
}
// I am testing very simple SQL query.. there should be no problem
$result = mysql_query("SELECT * FROM cathegories", $con, $db);
if (!$result) {
// but it always dies
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
mysql_close($con);
?>
What is wrong?
Thanks in advance!
You are mixing mysql and mysqli.
Try something like:
<?php
$con= new mysqli("localhost","user","passwd","database");
if ($con->connect_errno){
echo "could not connect";
}
$select = "SELECT * FROM tablename";
if($result = $con->query($select)){
while($row = $result->fetch_object()){
echo $row->rowname."<br>";
}
}
else { echo 'no result'; }
$con->close();
?>
// Here I open connection
$con = mysql_connect("localhost","root","aaaaaa");
// set the mysql database
$db = mysql_select_db("infs", $connection);
change to
// Here I open connection
$con = mysql_connect("localhost","root","aaaaaa");
// set the mysql database
$db = mysql_select_db("infs", $con);
mysql_query only takes two parameters - the actual SQL and then the link identifier (I assume in your case that's stored in $con; therefore remove $db from the third parameter).
You don't even need the second $con parameter really.
Where's the actual logic to connect to the database initially? Just because mysqli_connect_errno() doesn't return an error it doesn't mean the connection actually exists and that $con is available in the current scope.
I'd var_dump($con) before the mysql query to make sure it's a valid connection.

PHP-Linking forms Using ID

I have a database in which I have a main form that list all personnel using this code
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("datatest", $con);
$result = mysql_query("SELECT * FROM Personnel");
echo "<TABLE BORDER=2>";
echo"<TR><TD><B>Name</B><TD><B>Number</B><TD><B>View</B><TD></TR>";
while ($myrow = mysql_fetch_array($result))
{
echo "<TR><TD>".$myrow["Surname"]." ".$myrow["First Names"]."<TD>".$myrow["Number"];
echo "<TD>View";
}
echo "</TABLE>";
?>
</HTML>
As you can note I have a link to view details of the person but when I click on the VIEW link I get the following error
Parse error: syntax error, unexpected 'EmployeeID' (T_STRING) in C:\Program Files\EasyPHP-12.1\www\my portable files\dss4\childdetails.php on line 6
The childdetails.php has the following code
<HTML>
<?php
$db = mysql_connect("localhost", "root", "");
mysql_select_db("datatest",$db);
$result = mysql_query("SELECT * FROM children;
WHERE "EmployeeID="["$EmployeeID"],$db);
$myrow = mysql_fetch_array($result);
echo "Child Name: ".$myrow["ChildName"];
echo "<br>Mother: ".$myrow["Mother"];
echo "<br>Date of Birth: ".$myrow["DateOfBirth"];
?>
</HTML>
Since the first form to list the personnel works I believe the problem is in childdetails.php on line 6 as returned by the server but I simply don’t know how to fix it.
Note: a person can have more than one child as well as having more than one wife
Help please
I would say more like.
$result = mysql_query("SELECT * FROM children WHERE EmployeeID='$EmployeeID'");
// as far $EmployeeID is actualy set before running a query
//but as comment says don't use mysql better something like this
<?php
$mysqli = new mysqli('localhost', 'root', 'my_password', 'my_db');
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT * FROM children WHERE EmployeeID=?")) {
/* bind parameters for markers */
$stmt->bind_param("s", $EmployeeID);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($Employee);
/* fetch value */
$stmt->fetch();
printf($Employee);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
To begin with, your query is wrong, you're telling the sql that your script is over and that it should start executing something new. I'll show you how to do it properly here below.
Also, don't use mysql specific syntax, It's outdated and can get you into real trouble later on, especially if you decide to use sqlite or postgresql.
Also, learn to use prepared statements to avoid sql injection, you want the variables to be used as strings into a prepared query, not as a possible executing script for your sql.
Use a PDO connection, you can init one like this:
// Usage: $db = connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword);
// Pre: $dbHost is the database hostname,
// $dbName is the name of the database itself,
// $dbUsername is the username to access the database,
// $dbPassword is the password for the user of the database.
// Post: $db is an PDO connection to the database, based on the input parameters.
function connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword)
{
try
{
return new PDO("mysql:host=$dbHost;dbname=$dbName;charset=UTF-8", $dbUsername, $dbPassword);
}
catch(PDOException $PDOexception)
{
exit("<p>An error ocurred: Can't connect to database. </p><p>More preciesly: ". $PDOexception->getMessage(). "</p>");
}
}
And then init the variables:
$host = 'localhost';
$user = 'root';
$dataBaseName = 'databaseName';
$pass = '';
Now you can access your database via
$db = connectToDatabase($host , $databaseName, $user, $pass); // You can make it be a global variable if you want to access it from somewhere else.
Now you should construct a query that can be used as a prepared query, that is, it accepts prepared statements so that you prepare the query and then you execute an array of variables that are to be put executed into the query, and will avoid sql injection in the meantime:
$query = "SELECT * FROM children WHERE EmployeeID = :employeeID;"; // Construct the query, making it accept a prepared variable.
$statement = $db->prepare($query); // Prepare the query.
$statement->execute(array(':employeeID' => $EmployeeID)); // Here you insert the variable, by executing it 'into' the prepared query.
$statement->setFetchMode(PDO::FETCH_ASSOC); // Set the fetch mode.
while ($row = $statement->fetch())
{
$ChildName = $row['ChildName'];
$Mother = $row['Mother'];
$DateOfBirth = $row['DateOfBirth'];
echo "Child Name: $ChildName";
echo "<br />Mother: $Mother";
echo "<br />Date of Birth: $DateOfBirth";
}
You should use a similar approach to receive $EmployeeID but this should help you a lot.
By the way: remember to close your break tags with a whitespace ' ' and a forwardslash like I showed you.
You
Need
change your query something like this
<HTML>
<?php
$db = mysql_connect("localhost", "root", "");
mysql_select_db("datatest",$db);
$result = mysql_query("SELECT * FROM children WHERE EmployeeID=" . $EmployeeID, $db);
$myrow = mysql_fetch_array($result);
echo "Child Name: ".$myrow["ChildName"];
echo "<br>Mother: ".$myrow["Mother"];
echo "<br>Date of Birth: ".$myrow["DateOfBirth"];
?>
</HTML>

PHP not displaying MYSQL result

I created a script on a windows platform which connects to the mysql database and returns the results of a table. A very basic script which I wrote to simply test my connection worked. The script works fine on my windows machine but not on my new mac. On the mac it simply does not display any records at all.
I know that the database connection has been established because there is no error but I can not see why the result set is not being displayed on screen, as I said it worked fine on my windows machine.
The Mac has mysql (with data) and apache running for php.
Please could someone help as I have no idea what to do now?
Script below:
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
$dbname = 'test';
mysql_select_db($dbname);
mysql_select_db("test", $conn);
$result = mysql_query("SELECT * FROM new_table");
while($row = mysql_fetch_array($result))
{
echo $row['test1'] . " " . $row['test2'] . " " . $row['test3'];
echo "<br />";
}
mysql_close($con);
There are various things you could do to debug this.
Show all PHP errors.
ini_set('display_errors','On');
ini_set('error_reporting',E_ALL);
Catch all possible MySQL errors, not only the ones concerning whether you connected successfully.
mysql_select_db("test", $conn) or die(mysql_error());
mysql_select_db($dbname) or die(mysql_error());
$result = mysql_query("SELECT * FROM new_table") or die(mysql_error());
Side note: There's no reason to select which database you wish to use twice.
Its very difficult to see what is wrong ... so add some basic error checking, like changing this
$result = mysql_query("SELECT * FROM new_table");
to
$result = mysql_query("SELECT * FROM new_table") or die(mysql_error());
This will show you the error you are getting from your query (if there is one) .. you ill see in the documentation for mysql_query that it returns a boolean if there was an error
Also note that you have a mistake in the variable name for closing the MySQL Connection :
mysql_close($con);
should be
mysql_close($conn);
Check to see if the SELECT query was successful or not before fetching the rows.
<?php
$result = mysql_query("SELECT * FROM new_table");
if(!$result)
die('SQL query failed: ' . mysql_error());
The only thing i can think of is that Mac file system is case sensitive while windows isn't so it might be that you mispelled the name of the table. In any cas you should do
$result = mysql_query("SELECT * FROM new_table") or die("error:".mysql_error());
to view the error
I think you should use the improved PHP mysql driver
try
{
$db = new mysqli("localhost","root","root","test");
if ($db->connect_errno) {
throw new Exception($db->connect_error);
}
if ($result = $db->query("SELECT * FROM new_table")) {
printf("Select returned %d rows.\n", $result->num_rows);
while($row = $result->fetchAssoc())
{
echo $row['test1'] . " " . $row['test2'] . " " . $row['test3'];
echo "<br />";
}
/* free result set */
$result->close();
}
$db->close();
}
catch(Exception $e)
{
printf("Database Error: %s\n", $e->getMessage());
exit();
}

Categories