getting values from database as an option value using php - 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.

Related

Empty Select HTML (Dropdown Box) using PHP to fill from a MySQL Database

I am apologizing ahead, this is my first question here and I am still a student.
No time to waste.
I am making a website where you are given drop down boxes to choose CPU, Motherboard, Memory and the rest of your computer parts and sent via email or printed out or generate a code unique to you and your build, so the build is stored in the code. That all comes later.
My problem is that the computer parts listed in tables in database wont load in the box (or dropdown box) as using PHP to generate it from the DB. I've already searched many questions and answers on Stackoverflow but to no avail and I want to kill myself (not really, I am not suicidal at all, it's a figure of speech)
Here is what I got. Then I will explain all the problems that have been popping up.
index.php
<?php
include_once 'func.inc.php';
connectDB();
testDB();
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>PC Builder</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body background="background.jpg">
<header>
<h1>PC Builder</h1>
</header>
<section>
<table>
<tr>
<td class="titlecolomn">CPU</td>
<td><?php queryCPU(); ?></td>
</tr>
</table>
</section>
</body>
</html>
<?php closeDB(); ?>
func.inc.php
<?php
include_once 'db.inc.php';
function connectDB(){
$conn = new mysqli($servername, $username, $password, $dbname);
}
function testDB(){
if ($conn->connect_error) {
die("Debug: Connection Failed: " . $conn->connect_error);
}
echo "Debug: Connection Successful.";
}
function closeDB(){
mysqli_close();
}
function queryCPU(){
$queryCPU = "SELECT * FROM CPU";
$db = mysqli_query($db, $queryCPU);
echo '<select name="selectCPU">';
echo '<option value = "SelectCPU"> Select CPU </option>';
while ( $db=mysqli_fetch_assoc($db)) {
echo '<option value="{'.$db[ID].'}">'.$db[Name].'</option>';
}
echo '</select>';
}
db.inc.php
<?php
$servername = "localhost";
$username = "theUsername";
$password = "thePassword";
$dbname = "tableName";
?>
MySQL DB structure.
WebsiteName_PCBuilder
CPU (Table)
ID (Int, AUTO_INC)
Name (Varchar, 30)
ClockSpeed (Decimal 10,2)
Cores (Int)
Price (Decimal 10,2)
Here are the problems.
Whatever kind of password or username or database name or localhost name I put ConnectDB(); always returns
Debug: Connection Successful.
As such the <Select> </Select> is loaded with nothing in it but
'<option value = "SelectCPU"> Select CPU </option>'.
Also, if you know a better or alternative way of doing this, please do recommend it. I am quite flexible changing the entire thing if it it can work.
Here is the website. http://pcbuilder.tariqsendi.ml/
In above provided code, I snipped out the unimportant parts.
Ignore the Main Domain.
Thank you so much, in advance.
That's because you overwriting the same var.
Change
while ( $db=mysqli_fetch_assoc($db)) {
echo '<option value="{'.$db[ID].'}">'.$db[Name].'</option>';
}
With
while ($row = mysqli_fetch_assoc($db)) {
echo '<option value="{'.$row['ID'].'}">'.$row['Name'].'</option>';
}
while ( $row=mysqli_fetch_assoc($db)) {
echo '<option value="'.$row['ID'].'>'.$row['Name'].'</option>';
}

having trouble getting selected value from php dynamic selection option

I want to show options from my database for users to check, but having trouble getting user's choice.
So, I write two php files,
the first one doing things like: getting data from database, displaying in select option, then submit value by post to and the second php file.
And the second php file just display the recieved value.
Here's the first php file:
<html>
<body>
<form method="post" action="second.php">
<Select name=”select_value”>
<?
//connect to server
$con = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE) or die("Error " . mysqli_error($con));
$query = "SELECT * FROM MYTABLE" or die("Error in the consult.." . mysqli_error($con));
$result = $con->query($query);
//display result in select option
while ($row = mysqli_fetch_array($result)) {
echo "<Option value=".$row['ENTRY_ID']."> ".$row['ENTRY_NAME']."</Option><br>";
}
mysqli_close($con);
?>
</Select>
</form>
</body>
</html>
And the second php file:
<?
$option = isset($_POST['select_value']) ? $_POST['select_value'] : false;
if($option) {
echo $_POST['select_value'];
} else {
echo "not getting value of select option";
exit;
}
?>
If this works fine, I should see the selected value by the second php file, but I keep recieving my echo "not getting value of select option".
There must be something wrong between select option and my recieving file.
Can someone help?
try this double quotes
<Select name="select_value">
instead of <Select name=”select_value”>

Get email addresses from database and send it to all addresses

I am new at PhP and trying to write a code that will get all emails from table in db and wrtie them into BCC field in email client(I am using Outlook).
Fisrt I have created HTML code. For ex, If selected value is Partneri, then I want do get all emails from table where category is Partner.
<select name="email">
<option value="Uposlenik"> Uposlenici <br/>
<option value="Partner"> Partneri <br/>
<option value="Limari Montazeri"> Limari montažeri <br/>
<option value="Gradjevinske firme"> Građevinske firme <br/>
<option value="Krovopokrivacke firme"> Krovopokrivačke firme <br/>
<option value="Preradzivaci lima"> Preradživači lima <br/>
<option value="Limarske radionice"> Limarske radionice <br/>
<option value="Stovarista-Trgovci"> Stovarišta-Trgovci
</select>
After that I have created php file, and I got no errors. The result I got is only selected value nothnig else shows up.
<?php
$host="localhost"; // Host name
$username="***"; // username
$password="***"; // password
$database="***"; // Database name
$tbl_name="clanovi"; // Table name
$link=mysql_connect("$host", "$username", "$password");
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db("$database");
if (!$db_selected) {
die ('db is not selected : ' . mysql_error());
}
$kategorija=$_POST['email'];
//check post
echo $kategorija;
$query= "SELECT `EMAIL` FROM `clanovi` WHERE `KATEGORIJA`='$kategorija'";
$result=mysql_query($query) or die ("Error, query failed!");
mysql_close($link);
$row=1;
$numrows=mysql_num_rows($result);
$bccfield="Bcc:".mysql_result($result,0,"email");
while($row<$numrows)
{
$email=mysql_result($result, $row,"email");
$bccfiled="," .$email;
$row++;
Print "<a href=mailto:test#test.com?bcc=".$bccfield." /> " ;
}
$bccfield .="\r\n";
?>
Any help would be appreciated. Thanks in advance!
You have a small glitch in your code. It should be $bccfiled.="," .$email;, note the . before the =, otherwise you overwrite the variable content in every iteration of the loop. But even better style would be to store the addresses in an array and implode() them afterwards like this: implode(',',$bccfields).
So the lower part of your script should go something like this:
<?php
// ...
$query= "SELECT `EMAIL` FROM `clanovi` WHERE `KATEGORIJA`='$kategorija'";
$result=mysql_query($query) or die ("Error, query failed!");
while(FALSE!==($row=mysql_fetch_assoc($result))) {
$bccfields[] = $row['EMAIL'];
}
echo sprintf("<a href=mailto:test#test.com?bcc=%s />\n",
urlencode(implode(',',$bccfields)));
?>
Note that I have not tested this, just typed it down. But you should get the idea when you study it.
Try this,
mysql_result($result,0,"EMAIL");
.....^
instead of
mysql_result($result,0,"email");
You should start from $row=0; instead of $row=1;. Otherwise you will ignore the last row retrieved from DB.

Using PHP/MYSQL book but get no output from PHP when trying to access the database

I'm currently working my way through "PHP and MySQL Web Development." I've successfully created databases and been able to make tables and use the database. I've also successfully completed all the chapters on PHP and have had no problems with PHP not working up to this point. The goal of this page is return search results from a database. It's a pretty simple thing to do but for some reason nothing is being output from the script to the page. I'm getting no errors or anything. It's just blank with the title at the top. Can anyone please help me out with this? Thank you.
Here is the PHP code:
<html>
<head>
<title>Book-O-Rama Search Results</title>
</head>
<body>
<h1>Book-O-Rama Search Results</h1>
<?php
// create short variable names
$searchtype=$_POST['searchtype'];
$searchterm=trim($_POST['searchterm']);
if (!$searchtype || !$searchterm) {
echo 'You have not entered search details. Please go back and try again.';
exit;
}
if (!get_magic_quotes_gpc()){
$searchtype = addslashes($searchtype);
$searchterm = addslashes($searchterm);
}
# $db = new mysqli('localhost', 'bookorama', 'bookorama123', 'books');
if (mysqli_connect_errno()) {
echo 'Error: Could not connect to database. Please try again later.';
exit;
}
$query = "select * from books where ".$searchtype." like '%".$searchterm."%'";
$result = $db->query($query);
$num_results = $result->num_rows;
echo "<p>Number of books found: ".$num_results."</p>";
for ($i=0; $i <$num_results; $i++) {
$row = $result->fetch_assoc();
echo "<p><strong>".($i+1).". Title: ";
echo htmlspecialchars(stripslashes($row['title']));
echo "</strong><br />Author: ";
echo stripslashes($row['author']);
echo "<br />ISBN: ";
echo stripslashes($row['isbn']);
echo "<br />Price: ";
echo stripslashes($row['price']);
echo "</p>";
}
$result->free();
$db->close();
?>
</body>
</html>
You're supressing the errors from the line:
# $db = new mysqli('localhost', 'bookorama', 'bookorama123', 'books');
Thats what the # sign does, remove the # sign and verify that the connection works properly, it might be that your script fails there.
You shouldn't use that, it's not considered good practice as far as I know.
It worked for me! no white page! If you work with a editor including ftp sometimes saving the file failes. than you get a blank file. in that case safe your code and reopen the file.
as for the sql injection try this:
$searchtypes = array('type1','type2');
if (!in_array($searchtype,$searchtypes) || $searchterm=='') {
echo 'You have not entered search details. Please go back and try again.';
exit;
}
You need to create another php page that sends a post request. Here is a sample one:
Take a look at the fiddle:
<html>
<head>
<title>Book-O-Rama Search </title>
</head>
<body>
<h1>Book-O-Rama Search</h1>
<form id='uploadform' method='post' enctype='multipart/form-data' action='link to your search action php page'>
<legend>Submit form</legend><br/>
<div class='form-inputs'>
SearchType <input name='searchtype' id='searchtype'/><br>
SearchTerm <input name='searchterm' id='searchterm'/><br>
<input type="submit" value= "Search" />
</div>
</form>
</body>
</html>

Populate HTML SELECT using mysql and 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.

Categories