PHP/Postgresql issue populating a dropdownlist with db content - php

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;

Related

How would I code a PHP search form to search my database table that contains a JSON array?

I've been working at this most of the day, I've finally learned a little bit about json_decode - now I can successfully fetch specific data to the logged a logged in user.
Now I want to have the ability for people to use a PHP search from that can search my database that has the JSON Array - I want it so it searched for the $charinfo['firstname'] and $charinfo['lastname']. I hope my question makes sense. I've been researching and I haven't come across any solutions that help me (I've tried them all).
Here's the code that I have so far.... (I know, I just learned procedural PHP so that's what I am most comfortable with at the moment)
<form method="GET" action="person-lookup.php">
<input type="text" name="search"/>
<input type="submit" value="search">
</form>
<?php
if(isset($_GET['search'])){
$key = $_GET["search"];
$chars = "SELECT * FROM players WHERE 'charinfo' LIKE '%key%'";
while($row=mysqli_fetch_assoc($chars)) {
$charinfo_json = $row['charinfo'];
$charinfo = json_decode($charinfo_json, true);
echo $charinfo['firstname'];
}
}
?>
and the error I get when searching the form is;
Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, string given.
Try this , the problem is you did not use mysqli_query function
$con = mysqli_connect("localhost","my_user","my_password","my_db");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
....
$query = mysqli_query($con,$chars);
while($row=mysqli_fetch_assoc($query)) {
$charinfo_json = $row['charinfo'];
$charinfo = json_decode($charinfo_json, true);
echo $charinfo['firstname'];
}

How to create a simple dropdown list with php linking to mysql database

Hi there Im very new to PHP and Im having issues trying to make drop-down list with php connecting to my mysql db. I am able to connect to the database no problem as no error message is showing up when I load up the php document online.
However from my research I just cant seem to find what Im looking for. I have made a table in mysql with the necessary ids and values. Below is my code within select tags if even thats a good way to do it? if anyone can help much appreciated.
<select>
<?php
$db = mysqli_connect ("host", "username", "password");
if (!$db)
{
echo "Sorry! Can't connect to database";
exit();
}
//table name on mysql db = users3
?>
</select>
It looks like you're trying to run PHP inside of an HTML select tag. PHP runs server side (in the background).
You'll need to create your dropdown menu using Javascript and HTML, then have have your javascript code call your PHP via AJAX. There are a number of ways doing this, but the basic idea is to have an event bound to each item in your dropdown list. When you click one of your list items, your javascript uses AJAX to call your PHP which queries the database.
That's a pretty high level description of it but hopefully it gives you a sense of where you need to go from here.
Regards,
--Drew
Your code is obviously missing any SQL select query.
The following code was adapted from W3Schools, I suggest you have a read over some examples using mysqli here Mysql select query example
Included is a select list that is also courtesy of W3Schools, HTML form elements
I implore you to read some examples at W3Schools.
HTML
<select name="items"><?php echo getSelectItems(); ?></select>
PHP
<?php
function getSelectItems() {
$servername = "host";
$username = "username";
$password = "password";
$dbname = "itemDB";
$output = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT itemName FROM items";
$result = mysqli_query($conn, $sql);
if ($result->num_rows > 0) {
// output data of each row
$i = 0;
while($row = mysqli_fetch_assoc($result)) {
$output .= '<option value="' . $i . '">' . $row["itemName"] . '</option>';
$i++;
}
}
$conn->close();
return $output;
}

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

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.

Pull data from Mysql Into Dropdown

**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>

Categories