PHP populating Dropdown list - php

I need some help with populating a dropdown list, I have been searching around to find solution with some trial and errors but I must admit, I never touch PHP. I have the following code but it does not display anything, I assume my problem is with the connection, so my question is how to build such a connection:
<?php
$sql = mysql_query("SELECT ProvinceNameFR FROM Province");
while ($row1 = mysql_fetch_array($sql)) {
echo "<option value='".$row1['value']."'>".$row1['value']."
</option>";
}
?>
Where do I go from that? I am involved in a project that someone else developed.
Thanks

You've got some work ahead of you. First, use MySQLi or PDO instead of MySQL. MySQL is deprecated and will eventually be removed in future versions. http://php.net/manual/en/book.mysqli.php
Some obvious mistakes. You're query is SELECT ProvinceNameFR FROM Province but you're trying to get $row1['value'] when you should be using $row1['ProvinceNameFR'] because that's the column you selected.
You also need to wrap your <option>'s with the actual <select> tag. You may already be doing that, I just don't see it here.
so
<?php
$sql = mysql_query("SELECT ProvinceNameFR FROM Province");
echo "<select>";
while ($row1 = mysql_fetch_array($sql)) {
echo "<option value='".$row1['ProvinceNameFR']."'>".$row1['ProvinceNameFR']."
</option>";
}
echo "</select>";
?>
This is assuming everything is working database side. If not try adding var_dump(mysql_error()); at the end. That should print out the latest error and help you find out what's going wrong.

I would recommend using PDO to connect to a MySQL db as the older mysql_query, mysql_connect systems are depreciated.
A very basic way to get started would be:
$db = new PDO('mysql:host=HOST;dbname=DATABASENAME', USERNAME, PASSWORD);
$query = "SELECT * FROM Province";
$stmt = $db->query($query);
$results['data'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo '<select>';
foreach ($results['data'] as $row){
echo "<option value='".$row['ProvinceId']."'>".$row['ProvinceNameFR']."</option>";
}
echo '</select>';
You also need the <select> html wrappers around the options. And your field names need to be set to match the what is in the table. I have also assumed that there should be an ID in the value field.

Related

Return array results from db PDO

Apologies for opening what should be considered a very basic question. Please note I have coded using the mysql_query method 1000's of times thus, it is really difficult for me to make the switch but I'm finally doing it.
My 1st Problem
My 1st problem comes in simply returning a list of select statements
Example:I am trying to execute:
$sql="Select *From members";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
$name = $row['name'];
}
I have read the following SO questions, and tried to implement the answers without success,
PDO equivalent of mysql_fetch_array
translation mysql_fetch_array to PDO::FETCH_NUM
I am now working with a PHP book supposed to be "one of the best for 2015/16", the book says the following regarding the above problem
Again I have tried the recommendation from the book without success
<?php
$dsn ='mysql:localhost;dbname:myDB;';
$uname = 'root';
$pword = '';
$db = new PDO($dsn, $uname,$pword);
if($db){
echo'Success';
} else {
echo'error';
}
$sql="SELECT * from members";
$results = $db->query($sql);
foreach($results as $result) {
echo $result['name'];
}
The above code gives me the message, "success" thus, I am successfully connecting to my DB but the query returns the following error:
Invalid argument supplied for foreach()
I am finding it enormously frustrating that I have to go through such lengths just to return the results from a simple select statement and am seriously considering going back to the old way, where I would have completed my assignment by now, I am turning to the SO community for help in a last attempt to get it right. Any help greatly appreciated.
I am very ashamed of posting this, but I have found the problem. Possibly it might help someone in the future.
The code with querying the DB is fine.
The Problem is with the following in line 1:
$dsn ='mysql:localhost;dbname:myDB;';
It should read
$dsn ='mysql:host=localhost;dbname=myDB;';
The If statment will always return echo success even if you are not connected thus, use try/catch
lesson learned: Always inspect your code from line 1

Displaying records from a table with PHP

Sorry for the newbie question, but I am working on my first PHP script and I can't seem to make it work. I just want to display the records from a single MySQL table. I have been trying to do this for ages and it is not displaying anything except the first two echo statements, before it is supposed to pull out the data.
What am I doing wrong?
<?php
mysql_connect("localhost", "me", "mypass") or die(mysql_error());
echo "Connection to the server was successful!<br/>";
mysql_select_db("test") or die(mysql_error());
echo "Database was selected!<br/>";
$result = mysql_query("SELECT * FROM Customer");
while($row = mysql_fetch_assoc($result)){
echo "ID: ".$row['customer_id'].", Name:".$row['customer_name']
."<br/>";
}
?>
echo mysql_num_rows($result);
to know the number of rows returned by your query.
This error is because the table or the database you are trying to connect doesnt exits.
As #barmar suggests table names are case sensitive..
Please make sure that you are using the correct database and table ..THanx

when to close the php tags so it doesnt intefere with the html

I am trying to apply a dropdown menu which pulls usernames from my database.
I have the code for it below.
<?php
$host="******"; // Host name
$username="******"; // Mysql username
$password="*****"; // Mysql password
$db_name="*******"; // Database name
$cn=mysql_connect($host,$username,$password) or die(mysql_error());
mysql_select_db($db_name,$cn) or die(mysql_error());
$sql = "SELECT usernameSchool FROM schools";
$rs = mysql_query($sql) or die(mysql_error());
echo ?>"<select>";
<?php
while($row = mysql_fetch_array($rs)){
echo ?>" <option value= <?php'".$row["usernameSchools"]."'?> >".$row["userameSchool"]."</option>";
}mysql_free_result($rs);
echo "</select>";
?>
When i try to load the page some of the php scripts start to show when i have the php open and closing tags at the start and the finish.
I tried to put some in the middle of the code when i switched from html to php however this is now resulting in other issues such as the information from the database not coming through as well as random quotation marks.
Im not sure where my syntax has gone wrong.
If anyone could tell me when to open and close these tags it would be really helpful.
The page this data is on is a mix of html and php at the moment.
This is ludicrously UGLY code:
echo ?>"<select>";
<?php
Why not simply have
echo "<select>";
and be done with it? There is NO need to jump in/out of PHP mode the way you are. You're simply making the code extremely DIFFICULT to follow.
But it's so much prettier with alternative syntax :D
<?php
$host="******"; // Host name
$username="******"; // Mysql username
$password="*****"; // Mysql password
$db_name="*******"; // Database name
$cn=mysql_connect($host,$username,$password) or die(mysql_error());
mysql_select_db($db_name,$cn) or die(mysql_error());
$sql = "SELECT usernameSchool FROM schools";
$rs = mysql_query($sql) or die(mysql_error());
?>
<select>
<?php while($row = mysql_fetch_array($rs)):?>
<option value='<?php echo $row["usernameSchools"];?>'>
<?php echo $row["userameSchool"];?>
</option>
<?php endwhile;
mysql_free_result($rs);
?>
</select>
Also, PLEASE STOP USING THE mysql_ extension for new code!!!!!* Use MySQLi or PDO instead as the mysql_ extension is now deprecated and insecure.

tables not being created in database

Ok, I'm following a youtube guide on how to create a very simple blogging system using PHP/MySQL as I'd like to get to learn these 2 languages a bit more. I'm creating this in my localhost, permissions set-up correctly.
The problem is, when I go onto localhost/tables.php, it comes up as white screen which it's supposed to, but it's not creating the relevant tables within the database?
Here's the code I'm using:
mysql.php
<?php
mysql_connect('localhost','username','password'); //where localhost is the host, username is the relevant username and password is the relevant password.
mysql_select_db('database'); //where database is the chosen database in which to drop the tables.
?>
tables.php
<?php
include "mysql.php";
$table = "ENTRIES";
mysql_query ("CREATE TABLE IF NOT EXISTS `$table` (`ID` INT NOT NULL AUTO_INCREMENT , PRIMARY KEY ( `id` ) )");
mysql_query ("ALTER TABLE `$table` ADD `TITLE` TEXT NOT NULL");
mysql_query ("ALTER TABLE `$table` ADD `SUMMARY` TEXT NOT NULL");
mysql_query ("ALTER TABLE `$table` ADD `CONTENT` TEXT NOT NULL");
?>
Nothing is appearing in the error log which is frustrating and not helping me diagnose the problem.
Any help would be much appreciated! Thanks.
As you have no errors run this code to show if you have created created the table ENTRIES.
<?php
include "mysql.php";
$result = mysql_query("SHOW COLUMNS FROM `ENTRIES`");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
print_r($row);
}
}
?>
NOTE As you are starting with MySQL you would be advised to use PDO in place of the deprecated mysql_.
Here is a good tutorial
EDIT
Following comments the following code lists databases and tables on server(Note uses deprecated mysql_ function).
Ensure that the proper parameters replace "XXX".
<?php
$host= "localhost";
$username="XXX";
$password="XXX";
$database="XXX";
$link = mysql_connect($host,$username,$password); //where localhost is the host, username is the relevant username and password is the relevant password.
$db_list = mysql_list_dbs($link);
while ($row = mysql_fetch_object($db_list)) {
echo $row->Database . "\n";
echo "<BR>";
}
echo "<BR>";
$result = mysql_list_tables($database);
$num_rows = mysql_num_rows($result);
for ($i = 0; $i < $num_rows; $i++) {
echo "Table: ", mysql_tablename($result, $i), "\n";
echo "<BR>";
}
?>
Nothing is appearing in the error log which is frustrating and not helping me diagnose the problem
So your first poblem is to find out why it's not logging any errors. BTW it would also be a good idea to inject some echo / print statements to find out where it's failing.
Forget about the MySQL stuff and try:
<?php
trigger_error("Testing", E_USER_WARNING);
?>
Even though (once you've got the error reporting sorted out) you should get an error logged it will likely only contain a limited amount of information. Any time you call a mysql function, be via mysql_, mysqli or PDO, you should poll the return value and handle any error - even if it's just to echo the value to the screen.
It's saying that I haven't selected a database
Possibly the user account you are connecting as does not have permission to access the database.

$result = mysql_query()

I am brand new to php/mysql, so please excuse my level of knowledge here, and feel free to direct me in a better direction, if what I am doing is out of date.
I am pulling in information from a database to fill in a landing page. The layout starts with an image on the left and a headline to the right. Here, I am using the query to retrieve a page headline text:
<?php
$result = mysql_query("SELECT banner_headline FROM low_engagement WHERE thread_segment = 'a3'", $connection);
if(!$result) {
die("Database query failed: " . mysql_error());
}
while ($row = mysql_fetch_array($result)) {
echo $row["banner_headline"];
}
?>
This works great, but now I want to duplicate that headline text inside the img alt tag. What is the best way to duplicate this queries information inside the alt tag? Is there any abbreviated code I can use for this, or is it better to just copy this code inside the alt tag and run it twice?
Thanks for any insight!
You are, as the comment says, using deprecated functions, but to answer your question, you should declare a variable to hold the value once your retrieve it from the database so that you can use it whenever your want.
<?php
$result = mysql_query("SELECT banner_headline FROM low_engagement WHERE thread_segment = 'a3'", $connection);
if(!$result) {
die("Database query failed: " . mysql_error());
}
$bannerHeadline = "";
while ($row = mysql_fetch_array($result)) {
$bannerHeadline = $row["banner_headline"];
}
echo $bannerHeadline; //use this wherever you want
?>
It is hard to help without knowing more. You are pumping the results into an array, are you expecting to only return one result or many banner_headline results? If you will only ever get one result then all you need to do is something like this:
PHP:
$result = mysql_query("
SELECT `banner_headline`
FROM `low_engagement`
WHERE `thread_segment` = 'a3'", $connection) or die(mysql_error());
// This will get the zero index, meaning first result only
$alt = mysql_result($result,0,"banner_headline");
HTML:
<html>
<body>
<!--- Rest of code -->
<img src="" alt="<?php echo $alt ?>">
On a side note, you should stop using mysql-* functions, they are deprecated.
You should look into PDO or mysqli

Categories