Populate HTML SELECT using mysql and php - php

what is the best, tidiest way to populate a html select tag with items from the database?
For example, if I have the following php:
$sql="SELECT a.athleteId, a.fName, a.lName FROM Athletes a, SupportStaff s, StaffAthletes sa WHERE sa.staffId = $id AND a.athleteId = sa.athleteId";
$result=mysql_query($sql);
Then:
How do I populate the drop down menu with the list of tuples retrieved from the relation?
How should the php, html and jQuery be integrated?
I have the following, but it doesn't work- It just displays a blank page:
<?php
error_reporting(E_ALL)
session_start();
//connect to database
function connect() {
$dbh = mysql_connect ("localhost", "d", "a") or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db("PDS", $dbh);
return $dbh;
}
if(isset($_SESSION['username'])){
$dbh = connect();
$id = $_SESSION['id'];
$sql="SELECT a.athleteId, a.fName, a.lName FROM Athletes a, SupportStaff s, StaffAthletes sa WHERE sa.staffId = $id AND a.athleteId = sa.athleteId";
$result=mysql_query($sql);
$options="";
$i = 1;
while ($row=mysql_fetch_array($result)) {
$f=$row["fName"];
$l=$row["lName"];
$options.="<OPTION VALUE=\"$i\">".$f.' '.$l."</OPTION>";
$i++;
}
?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script src = "jQuery.js"></script>
<script>
$(document).ready(function(){
$("#go").click(function(e){
if($("#selectathlete option:selected").val() == "0"){
alert("Please Select An Athlete");
}else{
//set hidden textfield
$("form#profile").submit();
}
});
});
</script>
<title>Personal Diary System - Home Page</title>
</head>
<body>
<h1>Home Page</h1>
<p>Select An Athlete:
<SELECT ID ="selectathlete" NAME="athletes">
<OPTION VALUE="0">Choose</OPTION>
<?php echo($options);?>
</SELECT>
</p>
<form id = "profile" name="input" action="viewathleteprofile.php" method="post">
<input type = "hidden" id = "athleteId">
<input type = "button" name = "go" id = "go" value = "Go">
</form>
</body>
</html>
I've been debugging for hours and it just doesn't work...

You should try to error_reporting(E_ALL) your page, so that you can see any and all errors your page comes across.
What's connect()? did you mean mysql_connect()?
(Kinda unrelated) You shouldn't use mysql_* functions, use MySQLi (Good) or PDO (Awesome).

when i get stuck on server 500 errors i go over to http://phpcodechecker.com/ and paste in the page. when i did that on what code you have now, it complained about a missing ; on line 2.
another tip: you can use this syntax style for slightly less complex output:
$out = "text {$var} {$var2} {$array['index']}".DEFINITION_ONE
surprisingly this works for html attributes which we expect to output as "value" e.g.
$options .= "{$i} {$f}

make sure your file is a .php, not .html
don't forget "<?php" at the top of page.
try to write "echo 'hello';" at the top your page to see if it prints.
this seems trivial, but as you seem to have pasted the full code, i just wanted to make sure.

Perhaps $_SESSION['username'] isn't set? You don't have a closing brace on that if statement, so if isset($_SESSION['username']) returns false, the whole page never gets displayed.

Related

$.get can't pass the data to the php file

When I used page=1 ,everything is OK.BUT if I changed
$.get("getajax.php","page=1" ,function(data){ }
to
$.get("getajax.php","page="+pageno ,function(data){ }
then the program return a false and "fatal error: Call to a member function fetch_assoc() on a non-object", I think this means the $result has problems.Thus , the $query has a problem?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="jquery.js" type="text/javascript"></script>
<title></title>
</head>
<body>
<div id="showdata"></div>
<input type="hidden" id="currentresult" value="1" />
<button id="show">Load</button>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click','#show',function(e){
var pageno = $('#currentresult').val();
$.get("getajax.php","page="+pageno ,function(data){
pageno++;
$('#currentresult').val(pageno);
$('#showdata').append(data);
});
});
});
</script>
</body>
</html>
And the getajax.php
<!-- This is ajax data. -->
<?php
$con = mysqli_connect("localhost", "root", "", "maroon5");
$page=isset($_GET["page"])?$_GET["page"]:0;
$pageNo = $page;
$startLimit = ($pageNo-1)*2;
$query = "SELECT * from tour LIMIT $startLimit,2 ";
$result = mysqli_query($con,$query);
var_dump($result);
while($row = $result -> fetch_assoc()){
?>
<div>
<h4>
month:<?php echo $row["month"]; ?>day:<?php echo $row["day"]; ?>
</h4>
</div>
<?php
}
?>
The reason why $.get("getajax.php","page=1" ,function(data){ works is because it always sends 1 to your php, thus creating the sql query of SELECT * from tour LIMIT 0,2
However if you were to change to $.get("getajax.php","page="+pageno ,function(data){, page will get assigned pageno which increases dynamically every time the button is clicked thus creating different queries to the DB like:
first click: "SELECT * from tour LIMIT 0,2"
second click: "SELECT * from tour LIMIT 2,2"
third click: "SELECT * from tour LIMIT 4,2"
As you can see the second, or third click would be different. Not completely sure but this is most likely your case. One of these queries is not finding any results, thus throwing the error at fetch_assoc()
Try mysqli_error function to get real error
$result = mysqli_query($con,$query)or die (mysqli_error($con));
If your page if 0 then startLimit would be -2
Add a bit of logic here
$startLimit = ($pageNo-1)*2;
if($startLimit < 0)
{
$startLimit = 0;
}
Should work! Though not the perfect solution but would work

Data retrieved from database to Dropdown list. User selects option and then send that value to Database?

Now I have been trying to figure out a way to insert a dropdown menu selection by a user on the web-interface into MySQL database table_2 using PHP. The problem is that the dropdown list items are retrieved from the MySQL database from another table_2. Can someone please help me? Thank you in advance! Below shows the code I am using.
<?php
$con = mysqli_connect("localhost","root","");
$myDB = mysqli_select_db($con, "database");
$sqlSELECT = mysqli_query($con, 'SELECT disastergroup FROM disastergroups');
if (isset($_POST['group']))
{
$group = $_POST['group'];
$test = "SELECT disastergroupid FROM disastergroups WHERE disastergroup = '$group'";
mysqli_query($con, $test);
$test_store = "INSERT INTO events (groupid_FK) VALUES ($test);"
mysqli_query($con,$test_store);
}
else
{
echo "An option must be selected!";
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Title of Page</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
</head>
<body>
<form action = "detailslog.php" method = "POST">
<label for="groups">Disasters:</label>
<select name = "groups">
<option value = "">Select...</option>
<?php while($row = mysqli_fetch_assoc($sqlSELECT)):;?>
<option><?php $row1['disastergroup'];?></option>
<?php endwhile;?>
</select>
<input type="submit" value="Submit Data">
</form>
</body>
</html>
So what I want to do is take the user's selection from the options "groups" and use that value to get the ID of that value from the table disastergroups and then store that ID into the table "events" as a Foreign Key. This have been giving me hell to figure out. Any help would be greatly appreciated! Thank you!
$sql_quer = mysqli_query($con, $test);
$FK_id = mysqli_fetch_assoc($sql_quer);
$test_store = "INSERT INTO events (groupid_FK) VALUES ($FK_id[disastergroupid]);"
mysqli_query($con,$test_store);
This fixed my problem for anyone viewing this post!

getting values from database as an option value using php

So i was doing our thesis and i need to transfer some values from my sql database to my
here's the sample code:
<tr>
<td id="t" align="center">Subject: <select name="subj">
<?php
$con = mysql_connect("localhost","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db("sps_ccp",$con);
$college=$_SESSION['college1'];
$sql="SELECT * FROM subject_db WHERE crs='$college'";
$result=mysql_query($sql,$con);
$count=mysql_num_rows($result);
//echo $count;
for($ctr=0;$ctr<$count;$ctr++)
{
$sql1="SELECT subject FROM subject_db WHERE crs='$college'";
$subj=mysql_query($sql1,$con);
$subj1=mysql_result($subj,$ctr);
echo "<option value=".$subj1.">".$subj1."</option>";
}
?>
</select>
</td>
And also i have this option where i have to get that option value then it'll search through my database and get that value and put it in another option.
here's the sample code:
<tr>
<td id="t">Building: <select name="build">
<option value="hr">HR Building</option>
<option value="pr">PR Building</option>
<option value="gv">GV Building</option>
</select>
</td>
<td id="t">Room: <select name="room">
<?php
if(isset($_POST['build'])){
if($_POST['build']=='hr')
{
$hr = mysql_query("SELECT * FROM hrbuilding");
$h1 = mysql_num_rows($hr);
while(mysql_fetch_array($hr)){
if(h1>0)
{
echo "<option value=".$hr.">".$hr."</option>";
}
}
}
}
?>
</td>
Both didn't worked. It didn't have values on the option box. I did checked my database and I don't think that there are any problems with it. I asked someone on how to work on this but he suggested to use javascript which i really couldn't understand how it works.
Hoping you could help me :) thanks!
hope this may help you
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<select name="sample_s">
<?php
mysql_connect("localhost","root","your_password");
mysql_select_db("db_name");
if(mysql_errno())
die("Database Server is Offline");
$q=mysql_query("SELECT `id`, `opt` FROM `sample`");
if(mysql_num_rows($q)){
while($m=mysql_fetch_assoc($q))
{
echo '<option value="'.$m["opt"].'">'.$m["opt"].'</option>';
}
}
?>
</select>
</body>
</html>
I think you have an error here:
You get the results from query, yet you're calling again the same query but without actually getting the fields (merely the query's resource). There's also a missing quote from value attribute.
To fix:
$db_selected = mysql_select_db("sps_ccp",$con);
$college=$_SESSION['college1'];
$sql="SELECT * FROM subject_db WHERE crs='$college'";
$result=mysql_query($sql,$con);
$count=mysql_num_rows($result);
//echo $count;
while($row=mysql_fetch_assoc($result)) {
echo '<option value="'.$row["subject"].'">'.$row["subject"].'</option>';
}
Also when using sessions in a file, make sure that you're calling session_start and this must be the top position of your file, since it is a header-send call.
Also in your second code block you forgot to put a dollar in front of h1 variable.
EDIT
// very top of file
ini_set("display_errors",1);
error_reporting(E_ALL);
// now, just call your PHP code but in between 2 calls
ob_start();
...call your PHP code here
$buffer = ob_get_clean();
echo $buffer; // what is here? place it so you can see on screen what it says
The first body of code may not have worked because of the missing session_start(); which is required when using sessions. Since it's required to be at the top, you stand at getting an error stating that headers already sent... therefore you will need to either seperate your HTML from PHP, having PHP on top, or placing ob_start(); on top of session_start();
Your second body of code is most likely failing because of this if(h1>0) which should read as if($h1 > 0) you left out the $ sign.
Plus, in your first body of code, you are missing the password parameter in: (if it's not a typo)
$con = mysql_connect("localhost","root");
which should read as:
$con = mysql_connect("localhost","root","password");
Example taken from http://www.php.net/mysql_connect
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>
N.B.: Do consider switching to mysqli_* functions. mysql_* functions are deprecated and will be removed from future releases.

PHP and secure forms

I am doing an exercise from the book PHP & MYSQL in easy steps. It involves an HTML form to update a row in a database then various PHP scripts to check the the input data for HTML code and make it into a secure format. However, the code just does not work the way the book says. I went to the publisher's website and downloaded the code example, but no joy.
Instead of a form with the name of the row below it, instead I get the form, then below that "No valid new name submitted". Then below that the current name of row in the table which I want to change. When I try to enter and submit data into the form it makes no difference. It displays exactly the same page. The code is below.
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ensuring security
</title>
</head>
<body>
<form action="secure.php" method="POST">
<p>New Name : <input type="text" name="name">
<input type="submit"></p></form>
<?php
require('../connect_db.php');
if (!empty($POST['name']) && !is_numeric($_POST['name'])) {
$name = $POST['name'];
$name = mysqli_real_escape_string($dbc, $name);
$name = strip_tags($name);
$q = 'UPDATE towels SET name "' . $name . '" WHERE id= 1';
mysqli_query($dbc, $q);
} else {
echo 'No valid new name submitted';
}
$q = 'SELECT * FROM towels WHERE id = 1 ';
$r = mysqli_query($dbc, $q);
while ($row = mysqli_fetch_array($r, MYSQLI_NUM)) {
echo "<p>Name : $row[1] </p>";
}
mysqli_close($dbc);
I'd appreciate any ideas on this. I have spent about 3 hours and been on the publishers website, but I am still at square one.
There is no superglobal array $POST so you have to change $POST['name'] to $_POST['name'].
PHP can't see that array so it evaluates !empty($POST['name']) as false and never executes code with update query.
And, like #BartFriederichs said, buy better book. I don't think you'll learn something valuable from current one.

Creating an onChange select drop down with javascript and php but it's not working

What I am trying to do is create a drop down container of 32 different locations in Scotland and when one of the selections is selected, for example, Glasgow it should go to a URL which displays content such as heading, text, for each article in a div WHERE location = Glasgow.
I have no error messages or any sort of recognition that my code has worked as when I select one of the four on the drop down it does absolutely nothing.
Can come clean up and put right what I've done so far? I would be extremely greatful!
Here is my files which are being used:
header.php
<html>
<head>
<script src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#location').change(function(){
//Retrieve Content from the back-end PHP page, and pass the ID selected
var url = 'location.php?location=' + $(this).val();
$('#txtHint').load(url);
});
});
</script>
</head>
<body>
<div id="header">
<div class="headerLeftContent">
<select id='location'>
<option href="Link to a dynamic page with all the content from glasgow" value="Glasgow">Glasgow</option>
<option href="Link to a dynamic page with all the content from x" value="x">x</option>
<option href="Link to a dynamic page with all the content from test" value="test">test</option>
<option href="Link to a dynamic page with all the content from edinburgh" value="Edinburgh">Edinburgh</option>
</select>
<div id='txtHint'></div>
</div>
</div>
</body>
</html>
location.php
<?php
$connect = mysql_connect('xxxxxx', 'xxxxxx', 'xxxxxx');
$select_db = mysql_select_db('xxxxxx');
$location = $_REQUEST['location'];
$query = "SELECT * FROM podContent WHERE location = '.$location.'";
while($row = mysql_fetch_array($query))
{
echo $row['text'];
}
mysql_close($connect);
?>
And please any comments regarding 'SQL injection' or how 'mysql' should be 'PDO' are unwanted as I do understand this but I am simply testing at the moment and will amend this.
Thanks.
You seem to have a mistake concatenating your location name inside your MySQL query, and it's not matching anything (so nothing is echoed back). Change this:
$query = "SELECT * FROM podContent WHERE location = '.$location.'";
to
$query = "SELECT * FROM podContent WHERE location = '$location'";
(Unless you have stuff like .Glasgow. in your database...)
Then you have to call mysql_query($query) as Alon suggested.
You need to use mysql_query and pass the resource to the mysql_fetch_array function:
$query = "SELECT * FROM podContent WHERE location = '.$location.'";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
echo $row['text'];
}

Categories