I'm trying to bring data from MYSQL Database called ebms_db. The table is events and the fields are Event_ID and Event_Name.
The code I'm using currently to show the Event_Name only in the dropdown list is:
<select name="mySelect">
<?php
include 'db.php';
$sql = "SELECT Event_Name FROM events";
$result = mysql_query($sql);
echo "<select name='Event_Name'>";
while ($r = mysql_fetch_array($result)) {
echo '<option value="'.$row["Event_Name"].'">'.$row["Event_Name"].'</option>';
}
echo "</select>";
?>
<input type = "submit" name="Search" value="Search">
</select>
Db.Php looks like this...
$servername = "localhost";
$username = "test";
$password = "test";
$dbname = "ebms_db";
$conn = new mysqli($servername, "test", "test", $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
echo "Error";
}
What am I doing wrong?
The output shows a combo box with
- '.$row["Events_Name"].'
inside it.
while ($row = mysql_fetch_array($result)) {
^^^^ here
echo '<option value="'.$row["Event_Name"].'">'.$row["Event_Name"].'</option>';
}
<?php
include 'db.php';
// you just fetching here (Event_Name) take all the values from the database or
$sql = "SELECT * FROM events";
$result = mysql_query($sql);
echo "<select name='Event_Name'>";
while ($row = mysql_fetch_array($result)) {
echo '<option value="'.$row["Event_Name"].'">'.$row["Event_Name"].'</option>';
}
echo "</select>";
?>
<input type = "submit" name="Search" value="Search">
Why are you taking two selects? I just removed one select just beginning above the php tags.
MYSQL is deprecated, you should really use something else, if and/or when they remove it your website will be defunct.
Related
I'm trying to make a PHP web application display the data from specific Countries from a dropdown but I can't figure it out how to use the WHERE [Column] = [Value1, Value2, Value3] on a PHP dropdown.
I'm using the "Adventure Works 2014 Full Database Backup" for test purpose.
<html>
</body>
<!-- form for tower selection -->
<form action="test20.php" method="POST">
Please select the tower you are about to work on. </br></br>
<select name="TowerSelect"><option> Choose </option>
<?php
$serverName = 'SERVERNAME';
$uid = 'USERNAME';
$pwd = 'PASSWORD';
$databaseName = 'AdWorks';
$connectionInfo = array( 'UID'=>$uid,
'PWD'=>$pwd,
'Database'=>$databaseName);
$conn = sqlsrv_connect($serverName,$connectionInfo);
if($conn){
echo '';
}else{
echo 'Connection failure<br />';
die(print_r(sqlsrv_errors(),TRUE));
}
$sql = "SELECT BusinessEntityID, FirstName FROM dbo.vKelvin WHERE CountryRegionName = 'United States'";
$result = sqlsrv_query($conn,$sql) or die("Couldn't execut query");
while ($data=sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)){
echo "<option value=";
echo $data['BusinessEntityID'];
echo ">";
echo $data['BusinessEntityID'];
echo "</option>";
}
?>
<input type="submit" value="Select Tower">
</select></br></br>
</form>
</body></html>
<?php
if(empty($_POST['TowerSelect'])){
$_SESSION['tower'] = '';
} else {
$_SESSION['tower'] = $_POST['TowerSelect'];
echo "<tr>";
echo $_SESSION['tower'];
echo " selected. </p>";
echo('<td>'.$row['BusinessEntityID'].'</td><td>'.$row['FirstName'].'</td></tr>');
}
I believe I have this fixed. There were a number of problems with the code. You were referencing a $row but there was no SQL query that would have resulted in a $row, you were trying to post data after the closing HTML tag, you were trying to create rows for a table without declaring the table, and a few other things. Some of this was probably a result of quickly creating the test case. No problem. Try this...
<?php
$serverName = 'SERVERNAME';
$uid = 'USERNAME';
$pwd = 'PASSWORD';
$databaseName = 'AdWorks';
$connectionInfo = array( 'UID'=>$uid,'PWD'=>$pwd,'Database'=>$databaseName);
$conn = sqlsrv_connect($serverName,$connectionInfo);
if($conn){echo '';}else{echo 'Connection failure<br />';die(print_r(sqlsrv_errors(),TRUE));}
?><html><body>
<!-- form for tower selection -->
<form action="test20.php" method="POST">
Please select the tower you are about to work on. </br></br>
<select name="TowerSelect"><option> Choose </option>
<?php
$sql = "SELECT BusinessEntityID, FirstName FROM dbo.vKelvin WHERE CountryRegionName = 'United States'";
$result = sqlsrv_query($conn,$sql) or die("Couldn't execut query");
while ($data=sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)){
echo '<option value="'.$data['BusinessEntityID'].'">';
echo $data['BusinessEntityID'];
echo "</option>";
}
?><input type="submit" value="Select Tower">
</select></br></br>
</form>
<table cols="3" cellpadding="0" cellspacing="0" border="0">
<?php
if(empty($_POST['TowerSelect'])){
$_SESSION['tower'] = '';
} else {
$sql = "SELECT BusinessEntityID, FirstName FROM dbo.vKelvin WHERE BusinessEntityID = '".$_POST['TowerSelect']."'";
$result = sqlsrv_query($conn,$sql) or die("Couldn't execut query");
while ($row=sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)){
$_SESSION['tower'] = $_POST['TowerSelect'];
echo '<tr><td>'.$_SESSION['tower'].' selected.</td>';
echo '<td>'.$row['BusinessEntityID'].'</td>';
echo '<td>'.$row['FirstName'].'</td></tr>';
}
}
?></table></body></html>
Note: Though not important to answer your question, it is a best practice to use PDO and bound paramters when making database calls to protect yourself against SQL injection and other nasties. I recommend you look into it to protect your database. Cheers!
Ok, I got the solution, my select was wrong
$sql = "SELECT DISTINCT CountryRegionName FROM dbo.vKelvin ORDER BY CountryRegionName";
$result = sqlsrv_query($conn,$sql) or die("Couldn't execut query");
while ($data=sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)){
echo '<option value="'.$data['CountryRegionName'].'">';
echo $data['CountryRegionName'];
echo "</option>";
if(empty($_POST['TowerSelect'])){
$_SESSION['tower'] = '';
} else {
$sql = "SELECT BusinessEntityID, FirstName FROM dbo.vKelvin WHERE BusinessEntityID = '".$_POST['TowerSelect']."'";
$result = sqlsrv_query($conn,$sql) or die("Couldn't execut query");
while ($row=sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)){
$_SESSION['tower'] = $_POST['TowerSelect'];
echo '<tr><td>'.$_SESSION['tower'].' selected.</td>';
echo '<td>'.$row['BusinessEntityID'].'</td>';
echo '<td>'.$row['FirstName'].'</td></tr>';
}
}
i am a newbie in php programming and i cant figure out where i have gone wrong as my php code wont execute.
As the title says i am trying to create check boxes in my site however the values will come from the mysql database.
I have a table named “campus” in MySQL database and it has 2 coloumns called id and room.
database
[![Database][1]][1]
http://i.imgur.com/uLP6niJ.png
current output
[![Current Output][2]][2]
http://i.imgur.com/cSOYPme.png
below is my code:
<?PHP
$hostname = "localhost";
$username = "root";
$password = "root";
$databaseName = "my computer";
$connect = mysqli_connect($hostname, $username, $password, $databaseName);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
<html>
<body>
<form name="aform">
Choose a room:
<?php
$s = '';
$j = 0;
if ($q = $connect->query("SELECT * FROM `campus`")) {
while ($line = $q->fetch_assoc()) {
$s.= '<input type="checkbox" name="car'.$j.'" value="'.$line['room'].'">';
}
}
echo $s;
?>
</form>
</body>
</html>
You're not closing the while loop properly. Close the while loop as follow.
<?php
$sql = "SELECT room FROM campus";
$result = mysqli_query($sql);
while ($line = mysqli_fetch_array($result, MYSQL_ASSOC)) {
?>
<input type="checkbox" name="car" value="<?php echo $line['room']?>" />
<?php
}
?>
Welcome to PHP!
An error is that you're missing the semicolon that's needed after any php function (such as echo)
<?php echo $line['room']; ?>
And there's the missing PHP tags around the closing }
A third error is that you're not telling mysqli which connection to run the query on it should have:
mysqli_query($dbCon, $sql);
Apart from that it looks good, personally I prefer to use a PDO connection but mysqli is still good, but there are a few formatting tricks that can help prevent problems.
For example it's always a good idea to use back-ticks (`)
So:
$sql = "SELECT `room` FROM `campus`";
However, for this it might be best to use the * query. Which selects everything from the column so:
$sql = "SELECT * FROM `campus`";
The reason is how you're getting the data, you're telling PHP to create an array using the results.. but you've only given it one piece of data for each row. So if you give it all of the data it just makes it a little easier to use.
Here's the full code:
<?php $dbCon = mysqli_connect("localhost", "root", "root", "my computer");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}?>
<html>
<body>
<form name="aform">
Choose a room:
<?php
$sql = "SELECT * FROM `campus`";
$result = mysqli_query($dbCon, $sql);
while ($line = mysqli_fetch_array($result, MYSQL_ASSOC)) { ?>
<input type="checkbox" name="car" value="<?php echo $line['room']; ?>"
<?php } ?>
</form>
</body>
</html>
Also, if you're interested, here's how it'd be done in PDO:
<?php
try{
$con = new \PDO("mysql:host=" . 'localhost' . ";dbname=" . 'My Computer', 'root', 'root');
}catch(PDOException $e){
echo "Connection Failed";
die();
} ?>
<html>
<body>
<form name="aform">
Choose a room:
<?php
$result = $con->prepare("SELECT * FROM `campus`")
$result->execute();
while ($row = $result->fetch()) { ?>
<input type="checkbox" name="car" value="<?php echo $row['room']; ?>"
<?php } ?>
</form>
</body>
</html>
Still not working? Feel free to comment and I'll see what's up :)
Thanks,
P110
Try with this
<?php
$sql = "SELECT room FROM campus";
$result = mysqli_query($sql);
$campusArray = mysqli_fetch_array($result, MYSQLI_ASSOC);
foreach ($campusArray as $campus): ?>
<input type="checkbox" name="car" value="<?php echo $campus['room'];?>" />
<?php endforeach; ?>
I hope with this you can solve your problem.
alternative syntax is excellent for improving legibility (for both PHP
and HTML!) in situations where you have a mix of them.
http://ca3.php.net/manual/en/control-structures.alternative-syntax.php
i am trying display a the rows in my database table using the array of ids gotten from another table. i want it to display the first row which is $rowsfriend. and display the second row which is rows .......... but it only displays $rowsfriend
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ochat";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM friends where friend1='".($_POST[id])."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$rowsfriend = $row["friend2"];
echo $rows;
}
}
$sqll = "SELECT * FROM users WHERE id IN ($rowssfriend)";
$resultt = $conn->query($sqll);
if ($resultt->num_rows > 0) {
while($roww = $resultt->fetch_assoc()) {
$rowsss = $row["username"];
echo $rowss;
}
}
else {
?>
<h1>Register</h1>
<form action="selectfriends.php" method="post">
id:<br />
<input type="text" name="id" value="" />
<br /><br />
<input type="submit" value="enter" />
</form>
<?php
}
?>
Instead of two queries, you can write this nested query.
$sqll = "SELECT * FROM USERS WHERE ID IN (SELECT friend2 FROM friends WHERE friend1='".$_POST[$id]."')";
$resultt = $conn->query($sqll);
if ($resultt->num_rows > 0)
{
while($roww = $resultt->fetch_assoc())
{
$rowsss = $row["username"];
echo $rowss;
}
}
Hope this solve your problem .
Please try this version of code instead, if you might:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ochat";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT users.* FROM users WHERE users.id IN (SELECT friend2 FROM friends where friend1='".($_POST[id])."')";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$rows = $row["username"];
echo $rows;
}
}
else {
?>
<h1>Register</h1>
<form action="selectfriends.php" method="post">
id:<br />
<input type="text" name="id" value="" />
<br /><br />
<input type="submit" value="enter" />
</form>
<?php
}
?>
As far as I understood the code well, the problem was with the variable name typo as #Admieus wrote but also in the fact that in each iteration of the first loop variable $rowsfriend got overriden with a new value so after the end of the loop, $rowsfriend contained the last id from the result of the first query $sql.
The above version makes only one query using subquery in it to get directly usernames who are friends of friend1 given in $_POST[$id].
I hope it helps.
There are typos in the second loop.
You assign the value to $rowsss and try to echo from $rowss notice the difference.
Also, you assign the fetch_assoc result to $roww and then try to call it again with $row.
$sqll = "SELECT * FROM users WHERE id IN ($rowsfriend)";
$resultt = $conn->query($sqll);
if ($resultt->num_rows > 0) {
while($roww = $resultt->fetch_assoc()) {
$rowsss = $roww["username"];
echo $rowsss;
}
}
Point of improvement is: check your variable names, make names that are easy to understand and hard to mix up.
For instance, the variable containing the sql query should not be named $sql and to make it worse a second query shoul not be named sqll. Instead use names that imply what you are doing.
$querySelectFriendsFrom = "SELECT * FROM users WHERE id IN ($friendId)";
Don't take this as a hard rule, it's more of a tip to prevent silly mistakes.
Update: there was also a type in the query referring to rowssfriend instead of rowsfriend. Fixed above.
i'm farly new to php and are trying to make a php script where it's suppose to connect to a mysql db and get the vaule id, then show as an option in a drop down menu.
This is the code I have so far (got help from a friend):
$username = "root";
$password = "";
$hostname = "localhost";
$database = "customers";
$id = "";
mysql_connect("$hostname", "$username", "$password") or die (mysql_error()) or die (mysql_error());
mysql_select_db("$database") or die (mysql_error());
$result = mysql_query("SELECT id FROM users WHERE id='$id'") or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$valuestring = $row['id'];
print_r($result);
echo "<option value='$valuestring'>". $valuestring ."</option>";
mysql_close();
}
print_r($id);
But when I use this code the option is returned empty :/
I have also tried to do print_r($result); and that give me Resource id #4, so I guess that works.
If anyone could help me solve this I would be one happy guy :D
the $id value in your code is empty, are you avare of that ?
and can you print the query before sending it to mysql ?
use :
"$query = "select id from table where id = '$id'";
mysql_query($query);
echo $query;
Perhaps if you showed us what output you did get it would help.
the option is returned empty
If the output includes HTML generated inside the loop then that means the query returned at least 1 row. But the only way that echo "<option value='$valuestring'>" would produce an empty string is if $valuestring was an empty string. It's populated from "SELECT id FROM users WHERE id='$id'" implying that you must have a row in your database where id is null or an empty string and $id in your php code is null/empty string - indeed that is the case ($id = "";).
NTW the mysql_close(); should be outside the loop.
Let's simplify this code:
<select name="user" id="user" width="200px" style="width: 200px">
<option value="">Select State</option>
<?php
$query_uf = "SELECT id FROM users WHERE id="'.$id.'";
$result = mysql_query($query_uf,$bd);
while ($users =mysql_fetch_assoc($result)) {
echo "<option value='".$uf['id']."'>".$uf['user']."</option>"; }
?>
</select>
Obs: It's better you use mysqli_query and connect. And, in your code it's missing the connection in mysql_query.
I've previously needed to retrieve a list of albums from a table using a similar method, maybe try this function. Create your form and call the function within the and tags leading this to work. This should list your id(s) where specified in the query.
functions.php (or wherever you'd like to put the function):
function stateList() {
$username = "username";
$password = "password";
$host = "localhost";
$dbname = "dbname";
$id = RETRIEVE VALUE HERE;
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
$query = "
SELECT
id,
FROM users
WHERE
id = $id // YOU MAY WANT TO REMOVE WHERE - $ID AS STATED ABOVE, DOESN'T MAKE SENSE.
";
try
{
$stmt = $db->prepare($query);
$stmt->execute();
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$valuestring = $row['id'];
$rows = $stmt->fetchAll();
foreach($rows as $row):
print "<option value='" . $valuestring . "'>" . $valuestring . "</option>";
endforeach;
}
?>
Selection page:
<? include 'functions.php' ?> <!-- This will allow you to call the function. -->
<form action="example.php" method="post" enctype="multipart/form-data">
<select name="album">
<? stateList(); ?> <!-- Calls the function and retrieves all options -->
</select>
<input type="submit" name="submit" value="Submit">
</form>
I am trying to populate a drop-down list via PHP embedded in HTML.
Here is what I have so far:
<select name="ChapterList" id="ChapterList" style="width:120px;">
<?php
$username = "xxxxxxxxxxx";
$password = "xxxxxxxxx";
$database = "xxxxxxxxxxxxxx";
$host = "xxxxxxxx.mydomainwebhost.com";
#mysql_connect($host, $username, $password) or die("Unable to connect to database");
#mysql_select_db($database) or die("Unable to select database");
$query = "SELECT * FROM Chapters ORDER BY Id";
$ListOptions = mysql_query($query);
while($row = mysql_fetch_array($ListOptions))
{
echo "<option value='".$row['Id']."'>".$row['ChapterName']."</option>"
}
?>
</select>
I know I am recieving the expected results because if I echo $row['ChapterName']; , the current values I have in the database are listed in the proper order, so why is it when I echo "<option value='".$row['Id']."'>".$row['ChapterName']."</option>" my list receives nothing at all?
You are missing a semi-colon at the end of your echo statement
while($row = mysql_fetch_array($ListOptions)) {
echo "<option value='".$row['Id']."'>".$row['ChapterName']."</option>";
}
?>
Note: Start using mysqli_() functions as mysql_() are no more maintained by PHP team..
try using this
<?php
$form='';
$link = odbc_connect ('databasename', 'username', 'password');
if (!$link)
{
die('Could not connect: ' . odbc_error());
}
echo 'Connected successfully .<br>';
//Query the database
$sql = "SELECT * FROM Chapters ORDER BY Id ";
$result = odbc_exec($link,$sql);
$selectbox='<select id=combox name=Chapters >';
while($bin =odbc_fetch_array($result))
{
$selectbox.= "<option value=\"$bin[Chapters]\">$bin[FChapters]</option>";
}
odbc_close($link);
$selectbox.='</select>';
echo "Select Name".$selectbox;
?>
this code is working perfectly for me
Ok... so I solved my own question in a way.
What I discovered was that my php was being commented out via <--! -->. I merely changed the file extension to .php as opposed to .html. The drop-down list worked immediately and was populated with the proper values.
But this raises another question... how can I get inline PHP to work? My site is hosted with MyDomain. Is there a setting I am missing somewhere?
try to use this
<select>
while($row = mysql_fetch_array($ListOptions))
{
$id=$row['Id'];
$cname=$row['ChapterName'];
echo "<option value='$id'>$cname</option>";
}
?></select>
I have correct them just look at once,
<?php
$username = "xxxxxxxxxxx";
$password = "xxxxxxxxx";
$database = "xxxxxxxxxxxxxx";
$host = "xxxxxxxx.mydomainwebhost.com";
$dbc=#mysqli_connect($host, $username, $password,$database) or die("Unable to connect to database");
?>
<select name="ChapterList" id="ChapterList" style="width:120px;">
<?php
$query = "SELECT * FROM Chapters ORDER BY Id";
$ListOptions = mysqli_query($dbc,$query);
while($row = mysqli_fetch_array($ListOptions,MYSQLI_ASSOC))
{
echo "<option value='".$row['Id']."'>".$row['ChapterName']."</option>";
}
?>
</select>