Pull data from Mysql Into Dropdown - php

**UPDATED
<?php
// Get select box of courses to comment on
$pID3 = filter_input(INPUT_GET, 'pID', FILTER_SANITIZE_NUMBER_INT);
$username = "###";
$password = "###";
$pdo3 = new PDO('mysql:host=localhost;dbname=###', $username, $password);
$pdo3->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sth3 = $pdo3->prepare('
SELECT C.prefix, C.code
FROM Department D, Course C
WHERE D.dID = C.dID
**AND pID = ?**
');
$sth3->execute(array(
$pID3
));
?>
<html>
<?php
echo "<form action='inc/q/prof.php' method='post'>
<select id='courseInfoDD' name='courseID' tabindex='1'>";
?>
<?php
while($row3 = $sth3->fetch(PDO::FETCH_ASSOC)) {
echo "<option>".$row3['prefix'].", ".$row3['code']."</option>";
}
?>
<?php
echo "</select>";
?>
</html>
Okay, so right now its pulled all courses regardless of the pID or (Professor ID). I added a statement in the select saying where pID = ? , since the pID is in the url of the page. But now it throws and error about pID???
Query:
SELECT C.prefix, C.code
FROM Department D, Course C, Professor P
WHERE pID = ?
AND D.dID = C.dID
AND D.dID = p.dID;
Phpmyadmin error
: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? AND D.dID = C.dID AND D.dID = p.dID LIMIT 0, 30' at line 3
Db Img: http://postimage.org/image/24gdqab8k/
and
http://postimage.org/image/24gfdtnqc/

Okay. You need to follow some basic debugging steps. Here's exactly how to fix the problem:
First, my #1 guess about what's going on.... reading over your code, an empty data set will produce an empty select box. So start with the most simple: have you tried your SQL query directly on the database (i.e. with something like phpMyAdmin or the SQL command-line tool)? Be sure it works and (just as importantly) returns data.
If that works, then move the fetch call up into the PHP at the top, and just fetch the data and echo it to the screen (in other words, remove all the HTML). This will at least show you if it's fetching data from the database and your PHP PDO calls are correct.
Finally, if that doesn't seem like anything is wrong, find out if the PDO library is throwing a SQL error. Maybe it can't connect to the database; maybe your query returns empty rows. Very simple:
print_r($sth3->errorInfo());
Have you done a "view source" on the output? Is it writing out any of the option tags? bensiu's answer is correct, in that you need double quotes, not single quotes, around your "print" statement.
I promise that if you follow these steps, your code will work ;-)

print "<option>{$row3}</option>";
or
echo "<option>$row3</option>";
double quotes and you are missing <?php and `?>' tags
<select id='courseInfoDD' name='courseID' tabindex='1'>
<?php
while($row3 = $sth3->fetch(PDO::FETCH_ASSOC)) {
echo "<option>$row3</option>";
}
?>
</select>

If that
<select id='courseInfoDD' name='courseID' tabindex='1'>
while($row3 = $sth3->fetch(PDO::FETCH_ASSOC)) {
echo "<option>$row3</option>";
}
</select>
really is all your HTML, then your problem is, that that’d HTML and not PHP. You wanted to make it PHP, right?
<select id='courseInfoDD' name='courseID' tabindex='1'>
<?php
while($row3 = $sth3->fetch(PDO::FETCH_ASSOC)) {
echo '<option>$row3</option>';
}
?>
</select>

Related

PHP MySQLi to HTML combobox

I'm trying to pass data from a MySQL database to a HTML combobox and i'm using php to do that
<form method="POST">
<select class="js_inline_input">
<?php
$servername = "localhost";
$username = "root";
$password = "";
$db = "js_milhoes";
$conn = new mysqli($servername, $username, $password, $db);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}else{
echo "<option> Connected successfully </option>";
}
$sql = "SELECT * FROM js_country";
$result = $conn->query($sql);
while($row=mysqli_fetch_assoc($result)){
//My Personal echo
echo "<option value='".$row['countryCode']."'>".$row['countryName']."</option>";
//Echo i saw on this site
echo "<option value='{$row->countryCode}'>{$row->countryName}</option>";
}
$conn->close();
?>
</select>
</form>
It should list all the countries in the combobox but what displays is:
- From first echo: ".$row['countryName']."
- From second echo: {$row->countryCode}
I already check the connection, and before i add a if that says that the query is not empty
The reason why your second <option> isn't showing is because you are using a "fetch object" syntax $row->column.
http://php.net/manual/en/mysqli-result.fetch-object.php
You need to use one or the other; not both.
Either you use
while($row=mysqli_fetch_assoc($result)){
echo "<option value='".$row['countryCode']."'>".$row['countryName']."</option>";
}
or (and escaping with double-quotes):
while($row=mysqli_fetch_object($result)){
echo "<option value=\"{$row->countryCode}\">{$row->countryCode}</option>";
}
You also need to note that column names are case-sensitive when iterating over those like that.
Meaning that, countryCode and countrycode are two different animals here, as is countryName and countryname; should it be the case.
Check for errors on your query.
Footnotes:
You state: "but what displays is: - From first echo: ".$row['countryName']." - From second echo: {$row->countryCode}"
I don't understand what you mean by that. I've tested your code and it works fine (besides the "fetch object" syntax issue). If what you mean by that is you are seeing "code" rather than being parsed, then you are either not using a webserver, or that you are accessing it as file:///file.php rather than http://localhost/file.php or as .html should this be the case as the file extension is unknown.
That is my conclusion for this question.
Ok, this was a stupid problem, when i changed from wamp 2.5 to wamp 3 i forget to delete the wwamp paste and i had 2, so i has using the wrong fill and because that one wasn't in a server with apache the browser comments the php

PHP populating Dropdown list

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.

PHP/Postgresql issue populating a dropdownlist with db content

I've taken a look at several examples although none seems to work, I intend to populate a drop down box from a table in PostgreSQL db, I've done the reverse which I though it was more complex.
Right now I have the following: (tried different ways already)
...
<ul>
<form name="display" action="" method="post">
<label>Select a terminal profile:</label>
<select name='ddlTerminalProfiles'>
<option>choose...<option/>
<?php
#DB Connection
$con_string= "host=localhost port=1234 dbname=myDB user=myUser password=myPass";
$db_con = pg_connect($con_string);
#Query for profiles
$result=pg_query($dbcon, "SELECT * FROM profiles");
while ($row = pg_fetch_array($result))
{
?>
<option value="<? echo $row['profile_name'];?>"><?echo $row['profile_name'];?></option>
<?
}
?>
</select>
<br/>
...
Connection is fine, data in database as well.
Also tried triggering with if(isset($_POST['REFRESH']))... adding a refresh button. No luck.
In this code
<?php
#DB Connection
$con_string= "host=localhost port=1234 dbname=myDB user=myUser password=myPass";
$db_con = pg_connect($con_string);
pg_connect() sets the value of $db_con. But this code
#Query for profiles
$result=pg_query($dbcon, "SELECT * FROM profiles");
doesn't use $db_con. It uses $dbcon.
PHP documentation for each function tells you what it returns should there be an error. If a function can return some kind of error status, you need to look for it.
$db_con = pg_connect($con_string);
if (!$db_con) {
echo "pg_connect failed.", PHP_EOL;
}
pg_query() and pg_fetch_array() return an error status, too.
String concatenation code is easier to build up piece by piece. Start with
echo "<option></option>", PHP_EOL;
That should be obviously right; there's no concatenation. Add quotation marks. Failing to escape quotes is a frequent source of errors.
echo "<option value=\"\"></option>", PHP_EOL;
Add row values using curly brace syntax.
echo "<option value=\"{$row['profile_name']}\">{$row['profile_name']}</option>", PHP_EOL;

Why does this SQL query not work?

I have been bugging by head over this, but couldn't get this to work. What's wrong with this?
$query="Select studentid,firstname,lastname,pts from students where collegeid=4";
$result=mysql_query($query);
$row=mysql_fetch_array($result);
$pts=$row['pts'];
$name=$row['firstname']." ".$row['lastname'];
$rank= mysql_num_rows(queryMysql("Select distinct pts from students where pts>=$pts"));
echo<<<_END
<a href="student_profile.php?studentid=$row[studentid]" style="text-decoration: none;">
<div class="apps_each your_rank">
<span style="margin-right:5px;">$rank</span>
<div class="dp_small_c"><img class="dp_small" src="upload/$row[studentid].jpg"/></div>
<span class="apps_names">$name</span>
<div style="float:right">
<img src='pts.png' /><span>$row[pts]</span>
<img src='level.png' /><span>Level 1</span>
</div>
</div>
</a>
_END;
The error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1.
Surprisingly, below one(removing the WHERE clause) works. Why?
$row=mysql_fetch_array(mysql_query("Select studentid,pts,firstname,lastname from students"));
Table structure:
Everything's fine with table and its columns, because this query works everywhere else, only not here!
You mentionned in the comments that you wanted to use PDO. Here's what you can try:
$username = "enterUsername";
$password = "enterPass";
$conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
$query = $conn->prepare("Select studentid,pts,firstname,lastname from students where collegeid=:id");
$query->execute(array(
':id' => 4
));
// get errors if there are
$errors = $query->errorInfo();
echo "<pre>";
print_r($errors);
echo "</pre>";
$results = $query->fetch(PDO::FETCH_ASSOC); // can also be fetchAll if you have more than 1 row.
// to test and check results
echo "<pre>";
print_r($results);
echo "</pre>";
if $query in the question returns an empty row, then the variable beneath it remained unassigned - i.e., $pts and $name have no entities.
However, the query below them uses the variable $pts, which presumably has to store some value - which, when not, throws the above posted MYSQL error. The use of function queryMysql() for this query further clears the issue, as it was defined as below:
function queryMysql($query)
{
$result=mysql_query($query) or die(mysql_error());
return $result;
}
Hence, the MySql error.
I would use this library for all MySQL querying - http://www.meekro.com.
Your select query becomes like this:
// Load Library
require 'meekrodb.2.2.class.php';
// Setup DB Connection
DB::$user = 'my_database_user';
DB::$password = 'my_database_password';
DB::$dbName = 'my_database_name';
DB::$host = '123.111.10.23';
// Where clause
$collegeid = 4;
// Exec Query
$row = DB::queryFirstRow("Select studentid,pts,firstname,lastname from students where collegeid = %d", $collegeid);
src: http://www.meekro.com/docs.php#anchor_queryfirstrow

PHP will not delete from MySQL

For some reason, JavaScript/PHP wont delete my data from MySQL! Here is the rundown of the problem.
I have an array that displays all my MySQL entries in a nice format, with a button to delete the entry for each one individually. It looks like this:
<?php
include("login.php");
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("<br/><h1>Unable to connect to MySQL, please contact support at support#michalkopanski.com</h1>");
//select a database to work with
$selected = mysql_select_db($dbname, $dbhandle)
or die("Could not select database.");
//execute the SQL query and return records
if (!$result = mysql_query("SELECT `id`, `url` FROM `videos`"))
echo 'mysql error: '.mysql_error();
//fetch tha data from the database
while ($row = mysql_fetch_array($result)) {
?>
<div class="video"><a class="<?php echo $row{'id'}; ?>" href="http://www.youtube.com/watch?v=<?php echo $row{'url'}; ?>">http://www.youtube.com/watch?v=<?php echo $row{'url'}; ?></a><a class="del" href="javascript:confirmation(<? echo $row['id']; ?>)">delete</a></div>
<?php }
//close the connection
mysql_close($dbhandle);
?>
The delete button has an href of javascript:confirmation(<? echo $row['id']; ?>) , so once you click on delete, it runs this:
<script type="text/javascript">
<!--
function confirmation(ID) {
var answer = confirm("Are you sure you want to delete this video?")
if (answer){
alert("Entry Deleted")
window.location = "delete.php?id="+ID;
}
else{
alert("No action taken")
}
}
//-->
</script>
The JavaScript should theoretically pass the 'ID' onto the page delete.php. That page looks like this (and I think this is where the problem is):
<?php
include ("login.php");
mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
mysql_select_db ($dbname)
or die("Unable to connect to database");
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` ='.$id.'");
echo ("Video has been deleted.");
?>
If there's anyone out there that may know the answer to this, I would greatly appreciate it. I am also opened to suggestions (for those who aren't sure).
Thanks!
In your delete.php script, you are using this line :
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` ='.$id.'");
The $id variable doesn't exists : you must initialize it from the $_GET variable, like this :
$id = $_GET['id'];
(This is because your page is called using an HTTP GET request -- ie, parameters are passed in the URL)
Also, your query feels quite strange : what about this instead :
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` = '$id' ");
ie, removing the '.' : you are inside a string already, so there is nothing to concatenate (the dot operator in PHP is for concatenation of strings)
Note :
if this works on some server, it is probably because of register_globals
For more informations, see Using Register Globals
But note that this "feature" has been deprecated, and should definitely not be used !
It causes security risks
And should disappear in PHP 6 -- that'll be a nice change, even if it breaks a couple of old applications
your code has a big SQL injection hole : you should sanitize/filter/escape the $id before using it in a query !
If you video.id is a string, this means using mysql_real_escape_string
If you where using the mysqli or PDO extensions, you could also take a look at prepared statements
with an integer, you might call intval to make sure you actually get an integer.
So, in the end, I would say you should use something that looks like this :
$id = $_GET['id'];
$escaped_id = mysql_real_escape_string($id);
$query = "DELETE FROM `videos` WHERE `videos`.`id` = '$escaped_id'";
// Here, if needed, you can output the $query, for debugging purposes
mysql_query($query);
You're trying to delimit your query string very strangely... this is what you want:
mysql_query('DELETE FROM `videos` WHERE `videos`.`id` ='.$id);
But make sure you sanitize/validate $id before you query!
Edit: And as Pascal said, you need to assign $id = $_GET['id'];. I overlooked that.
In your delete.php you never set $id.
You need to check the value in $_REQUEST['id'] (or other global variable) and ONLY if it's an integer, set $id to that.
EDIT: Oh, also you need to remove the periods before and after $id in the query. You should print out your query so you can see what you're sending to the sql server. Also, you can get the SQL server's error message.
You add extra dots in the string.
Use
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` ='$id'");
instead of
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` ='.$id.'");
Also check how do you get the value of $id.
Thanks everyone. I used Pascal MARTIN's answer, and it comes to show that I was missing the request ($_GET) to get the 'id' from the precious page, and that some of my query was incorrect.
Here is the working copy:
<?php
include ("login.php");
$id = $_GET['id'];
mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
mysql_select_db ($dbname)
or die("Unable to connect to database");
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` = $id ");
echo ("Video ".$id." has been deleted.");
?>
Thanks again!

Categories