Creating Dropdown list from sql database in PHP - 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-","","");
?>

Related

PHP sql query isn't returning anything

The following PHP code:
$dbc = mysql_connect ('localhost','root','abcde');
if (!$dbc) {
die('Not Connected:' . mysql_error ());
}
$db_selected = mysql_select_db ('db_test', $dbc);
if (!$db_selected) {
die ("Can't Connect :" .mysql_error());
}
$query="SELECT * FROM 140423 WHERE GAME='Clash of Clans'";
//add "result"
$result=mysql_query($query);
if (!$query) {
die ("Can't Connect :" .mysql_error());
}
echo $result;
Doesn't return anything.
Should I be using print instead of echo?
Also, if I change
echo $result;
To
echo 'whatever';
it returns "whatever" on my post.
Help?
From the manual:
Identifiers may begin with a digit but unless quoted may not consist solely of digits.
http://dev.mysql.com/doc/refman/5.1/en/identifiers.html
Which is exactly what you're doing, and should not be doing.
Solution:
Choose a different name for your table, one consisting of letters preferably.
Use backticks around the table name.
Plus, if you wish to view data, you need to use a loop.
I.e.:
$query="SELECT * FROM `140423` WHERE GAME='Clash of Clans'";
while ($row = mysql_fetch_assoc($query))
{
$var = $row["column"]; // the column of your choice
}
echo $var;
Rewrite:
$dbc = mysql_connect ('localhost','root','abcde');
if (!$dbc) {
die('Not Connected:' . mysql_error ());
}
$db_selected = mysql_select_db ('db_test', $dbc);
if (!$db_selected) {
die ("Can't Connect :" .mysql_error());
}
$query="SELECT * FROM `140423` WHERE GAME='Clash of Clans'";
//add "result"
$result=mysql_query($query);
// as pointed out already
if (!$result) {
die ("Can't Connect :" .mysql_error());
}
echo $result; // this is up to you
// if you want to see data from your table, loop through it.
while ($row = mysql_fetch_assoc($query))
{
$var = $row["column"]; // the column of your choice
}
echo $var;
Footnotes:
mysql_* functions deprecation notice:
http://www.php.net/manual/en/intro.mysql.php
This extension is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.
These functions allow you to access MySQL database servers. More information about MySQL can be found at » http://www.mysql.com/.
Documentation for MySQL can be found at » http://dev.mysql.com/doc/.
mysql_query returns a resource or false. You need to manipulate the resource with one of the various fetch functions.
Instead of looking if $query is false, you should be looking if $result is false.
if (!$result) {
die ("Can't Connect :" .mysql_error());
}
After that
$result=mysql_query($query);
if (!$query) {
die ("Can't Connect :" .mysql_error());
}
Use
while($row = mysql_fetch_array($result)) {
echo $row['YourTableFieldName'];
}
OR use
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
// If you want to display all results from the query at once:
print_r($row);
// If you want to display the results one by one
echo $row['YourTableFieldName1'];
echo $row['YourTableFieldName2'];
}

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.

how to Get the list of sites (domains) from MySQL database using PHP?

so I am new in StackOverflow :), I have a problem to answer a question in php5,
This is the question :
Create a PHP 5.4 script to check availability of many Sites (via Echo Protocol):
* Get the list of sites (domains) from MySQL database.
so I write this script and I want if it's the good answer :
<?php
$dbname = 'mysql_dbname';
if (!mysql_connect('mysql_host', 'mysql_user', 'mysql_password')) {
echo 'Could not connect to mysql';
exit;
}
$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql);
if (!$result) {
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
while ($row = mysql_fetch_row($result)) {
echo "Table: {$row[0]}\n";
}
mysql_free_result($result);
?>
try something like this
$con = mysqli_connect(‘hostname’, ‘username’, ‘password’, ‘database’);
$result = mysqli_query($con , "select column_name from table_name");
while($data = mysqli_fetch_array($result))
{
echo $data['column_name'];
}
this will tell you the databases that have rights to be connected to
mysql_connect('localhost') or die ("Connect error");
$res = mysql_query("SHOW DATABASES");
while ($row = mysql_fetch_row($res)) {
echo $row[0], '<br/>';
}
You need to select a database before you use mysql_query.
$connection = mysql_connect('mysql_host', 'mysql_user', 'mysql_password');
//Write code to Check the connection
mysql_select_db('database_name', $connection);
//Write code to query
But as Robin mentioned in the comment, mysql* apis are deprecated. Use Mysqli or Pdo_Mysql. details here: http://in3.php.net/mysql_select_db

Echoing MySQL query in PHP

I have been trying for the past while to echo out the result of a a MySQL query in PHP. I can't seem to get it to work so I am a bit lost. I know for a fact that the query works as I have done it in PHPMYADMIN and it is working fine, however whenever I load the webpage, nothing is outputted. For the purposes of this question I have generalized the things in the query as I obviously don't want anyone accessing my database. This is what I have tried:
<?php
$connect = mysql_connect('host', 'user', 'password', 'dbname');
if (!$connect) {
die('Could not connect: ' . mysql_error());
}
if (!mysql_select_db('dbname')) {
die('Could not select database: ' . mysql_error());
}
$result = mysql_query('SELECT SUM(row name) FROM `table`');
if (!$result) {
die('Could not query:' . mysql_error());
}
echo mysql_result($result);
mysql_close($connect);
?>
I look forward to your replies.
mysql_result need the second parameter (The row number from the result that's being retrieved).
echo mysql_result($result, 0);
you have to change
echo mysql_result($result);
by
echo mysql_result($result,0);
or you can use
print_r(mysql_fetch_assoc($result));
Try this
echo mysql_result($result,0);
For more information, please give a look on http://www.php.net/mysql_result
or you can use mysql_fetch_row instead of mysql_result.
$row = mysql_fetch_row($result);
echo $row[0];
You may use this following format:
Give your Sql command like this:
$result = mysql_query('SELECT SUM(row name) as new_column_name FROM `table`');
then use this loop
while($fetched_values = mysql_fetch_array($result)){
echo $fetched_values['new_column'];
}
In your mysql_connect you have provided 4 parameters. it accepts 3 params
host, username and password. dbname is given inside mysql_select_db
as you can see from official docs. So remove the 4th param from mysql_connect function.
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
http://php.net/function.mysql-connect
$db_selected = mysql_select_db('foo', $link);
http://www.php.net/manual/en/function.mysql-select-db.php
but these mysql_* function will be deprecated use mysqli instead.
pass a row number as second parameter in mysql_result
echo mysql_result($result, 1);
or
use print_r(mysql_fetch_array($result));
where $result is your result resource
if you have any doubt you may refer my following example program.
<?php
$connect = mysql_connect('localhost', 'user_name', 'password', 'db_name');
if (!$connect)
{
die('Could not connect: ' . mysql_error());
}
if (!mysql_select_db('db_name'))
{
die('Could not select database: ' . mysql_error());
}
$row = mysql_query('SELECT (Tamil+English+Maths) as total FROM table_name');
if (!$row)
{
die('Could not query:' . mysql_error());
}
while($fetched_row = mysql_fetch_array($row)){
echo $fetched_row['total'];
}
mysql_close($connect);
?>
here Tamil,English and Maths are the column values of my table

Extracting values from a database to populate a dropdown

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>

Categories