populate a select box with php mysql - php

I'm having difficulty populating a select box within a form to display existing "forenames" of nurses from the "Nurses" table. Could anyone tell me what Im doing wrong? Thanks in advance!
Here is the form
<form method="post" action="insert.php">
<br>
<tr><td align="left"><strong>Nurse Information</strong></td>
</td>
<tr>
<td>nurse_name</td>
<td><select name="valuelist">
<option value="valuelist" name="nurse_name" value='<?php echo $nurse_name; ?>'></option>
</select></td>
<tr>
The QUERY which should populate the nurse_forename:
<html><head><title>Connect to Database</title></head><body>
<font size="4">Query gets Forename of nurse</font>
<br><br><font size="4">Choose a name</font><br><br>
<form action="insert.php" method="post">
<select name="valuelist">;
<?php
$value=$_POST ["valuelist"];
$con = mysql_connect("localhost","root","") or die('Could not connect: ' . mysql_error());
mysql_select_db("a&e", $con) or die('Could not select database.');
$fetch_nurse_name = mysql_query("SELECT DISTINCT $nurse_name FROM nurse");
$result = mysqli_query($con, $query) or die("Invalid query");
while($throw_nurse_name = mysqli_fetch_array($fetch_nurse_name)) {
echo '<option value=\"'.$nurse_name['nurse_name'].'">'.$throw_nurse_name['nurse_name'].'</option>';
}
echo "</select>";
mysqli_close($con);
?>
<input type="submit" value="Submit">
</form></body></html>

Try this:
<html><head><title>Connect to Database</title></head><body>
<font size="4">Query gets Forename of nurse</font>
<br><br><font size="4">Choose a name</font><br><br>
<form action="insert.php" method="post">
<select name="valuelist">;
<?php
$value=$_POST ["valuelist"];
$con = mysql_connect("localhost","root","") or die('Could not connect:'.mysql_error());
mysql_select_db("a&e", $con) or die('Could not select database.');
$fetch_nurse_name = mysql_query("SELECT DISTINCT Forename FROM nurse");
while($throw_nurse_name = mysql_fetch_array($fetch_nurse_name)) {
echo '<option value=\"'.$throw_nurse_name[0].'">'.$throw_nurse_name[0].'</option>';
}
echo "</select>";
?>
<input type="submit" value="Submit">
</form></body></html>
Dont use mysql and mysqli together....you should use mysqli or PDO, but not a mix of both ;)
PS: Edited ;)
Saludos.

Apologies if this duplicates other answers, Here's an answer using mysql_ syntax although you should of course be using mysqli_ or PDO for this...
<form action="insert.php" method="post">
<select name="valuelist">;
<?php
//path to connection statements
include('path/to/connection/stateme.nts');
//fetch nurse name
$query = "SELECT nurse_name FROM nurse;";
$result = mysql_query($query) or die(mysql_error()); //note: use mysql_error() for development only
//print results
while($row = mysql_fetch_assoc($result)) {
echo '<option value=\"'.$row['nurse_name'].'">'.$row['nurse_name'].'</option>';
}
echo "</select>";
?>
<input type="submit" value="Submit">
</form>

Check your MySQL table and column name that you using. Sometimes it does not work if you don't write those names exactly which in your MySQL table. suppose,
$query = "SELECT nurse_name FROM nurse";
in above SQL if MySQL table name is 'NURSE' and column name is 'NURSE_NAME' then write exactly like this.
$query = "SELECT NURSE_NAME FROM NURSE";
So, you look that sometime MySQL table, column name work in case sensitive.

Related

How to display postgresql search results using PHP

The Problem
Hello, I am creating a search function that will allow users to search for a specific E-Number and see whether it is derived from animals or not, basically seeing if it's vegan. I have successflly connected to the database using PHP on my website.
The Code
At the top of the page:
<?php
// Connecting, selecting database
$dbconn = pg_connect("host=***** port=*****
dbname=**** user=**** password=*****")
or die('Could not connect: ' . pg_last_error());
//collect
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
// Performing SQL query
$query = 'SELECT vegan FROM enumbers WHERE code = searchq';
}
?>
The search bar:
<div id="tablebox">
<!-- Search bar -->
<p>Is It Vegan?</p>
<form name="form1" method="post" action="searchEnumbers.php">
<input name="search" type="text" size="30" maxlength="5" />
<input name="submit" type="submit" value="Search" />
</form>
</div>
How will I now display the 'vegan' result that has been searched? I am unsure how to print the results.
Update
The column names in the enumbers table are: 'code', 'name', 'type', and 'vegan'.
<?php
// Connecting, selecting database
$dbconn = pg_connect("host=db.dcs.aber.ac.uk port=5432
dbname=cs399030_16_17 user=sec17 password=Liverpool2112")
or die('Could not connect: ' . pg_last_error());
//collect
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
// Performing SQL query
$pg_query = 'SELECT vegan FROM enumbers WHERE code = '.$searchq;
$result = pg_query($query);
foreach($result as $r){ //If you have multiple records or $result
echo "<p> Your ".$r->params." or ".$r['params']." here </p>"; //for instance
}
}
?>
You should have something like:
<?php
// Connecting, selecting database
$dbconn = pg_connect("host=**** port=****
dbname=**** user=**** password=****")
or die('Could not connect: ' . pg_last_error());
//collect
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
// Performing SQL query
$query = 'SELECT vegan FROM enumbers WHERE code = '.$searchq;
// make the query with: pg_query
// $result = pg_query($query);
foreach($result as $r){ //If you have multiple records or $result
echo "<p> Your ".$r->params." or ".$r['params']." here </p>"; //for instance
}
//you could use: var_dump(pg_fetch_all($result));
}
?>
<!-- If you want to show always the form. If not, put inside the else -->
<div id="tablebox">
<!-- Search bar -->
<p>Is It Vegan?</p>
<form name="form1" method="post" action="searchEnumbers.php">
<input name="search" type="text" size="30" maxlength="5" />
<input name="submit" type="submit" value="Search" />
</form>
</div>
Note this is not the best way to do it (you could use AJAX, and differents pages in order to now refresh the page), or others ways. But this could work as the way you want.
Check official documentation from PHP: http://php.net/manual/kr/function.pg-connect.php
Hope it helps!

How to get a value of a select input tag with options taken from a database using POST method?

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<select name="doctor">
<?php
$con = mysqli_connect("---","---","---","---") or die("Can't Connect to the Database.");
$sql = mysqli_query($con, "SELECT Title, Name, LastName FROM physician");
while ($row = $sql->fetch_assoc()){
echo "<option value=\"doctor1\">" . $row['Title'].' '.$row['Name'].' '.$row['LastName'] . "</option>";
}
?>
</select>
<input type='submit' value="Filter"><br>
</form>
Above is a form I created. I used POST method. This form has a select input tag and it's options are taken from my database. When form is submitted I need to access the value selected by user using $_POST['doctor'] function. But it doesn't give me any value. Can anyone help me?
If the ID for each entry in the "physician" table is stored in a column "PhysicianID", you should try the following code snippet:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<select name="doctor">
<?php
$con = mysqli_connect("---","---","---","---") or die("Can't Connect to the Database.");
$sql = mysqli_query($con, "SELECT PhysicianID, Title, Name, LastName FROM physician");
while ($row = $sql->fetch_assoc()){
echo '<option value="'.$row['PhysicianID'].'">'.$row['Title'].' '.$row['Name'].' '.$row['LastName'].'</option>';
}
?>
</select>
<input type='submit' value="Filter"><br>
</form>

call to undefined function php mysql

I am new to coding and keep getting this error and I am not sure what the reason is... I am trying to search/retrieve data from a Mysql database... Idea is that someone selects a category of search (such as first name) and inputs a first name and then code retrieves all relevant matches from database table Customers.
I am getting the following error:
Fatal error: Call to undefined function query() in ..../search.php on line 36
Can anyone help.
<html>
<head>
<title>pageName</title>
<style type="text/css">
table {
background-color: #ADD8E6;
border: 1px solid black;
font-family: Arial; font-size: 14px;
}
th {
text-align: left;
}
</style>
</head>
<body>
<h1>MEMBERS SEARCH</h1>
<form method="post" action="search.php">
<input type="hidden" name="submitted" value="true"/>
<label> Search Category:
<select name="category">
<option value="firstname">First NAME</option>
<option value="lastname">Last NAME</option>
</select>
</label>
<label> Search Criteria:<input type="text" name="criteria" /></label>
<input type="submit" />
</form>
<?php
if (isset($_POST['submitted'])){
// connect to the DB
include('connect.php');
$category = $_POST['category'];
$criteria = $_POST['criteria'];
$query = "SELECT * FROM Customers WHERE $firstname LIKE '%" . $criteria ."%'";
$result = $query ($con, $query) or die ('error getting data from database');
$num_rows = mysql_num_rows ($result);
echo "$num_rows results found";
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
?>
<table>
<tr>
<td width="300" ><font face="Arial Black" size="2"><?php echo $row['firstname']?> <?php echo $row['lastname']?></font></td>
</tr>
</table>
<table>
<tr>
?>
</body>
</html>
Try changing your code to look like this.
<form method="post" action="search.php">
<input type="hidden" name="submitted" value="true"/>
<label> Search Category:
<select name="category">
<option value="firstname">First NAME</option>
<option value="lastname">Last NAME</option>
</select>
</label>
<label> Search Criteria:<input type="text" name="criteria" /></label>
<input type="submit" />
</form>
<?php
if (isset($_POST['submitted'])){
// connect to the DB
include('connect.php');
$category = mysqli_real_escape_string($con, $_POST['category']);
$criteria = mysqli_real_escape_string($con, $_POST['criteria']);
$query = "SELECT * FROM Customers WHERE firstname LIKE '%" . $criteria ."%'";
$result = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($result);
echo "$num_rows results found";
Brief explanation of changes:
Added 'real_escape_string' function to your user submitted variables
to help prevent sql injection
Changed '$firstname' in your query to 'firstname'
Took out 'or die()' part after query and used mysqli_ functions to
handle the data.
You have $query instead of query, it should be a function not a variable. That may fix your problem, if there is more let me know.
$result = $query ($con, $query) or die ('error getting data from database');
should be:
$result = query($con, $query) or die('error getting data from database');
Also you have query mistake:
$query = "SELECT * FROM Customers WHERE $firstname LIKE '%" . $criteria ."%'";
Should be:
$query = "SELECT * FROM Customers WHERE firstname LIKE '%" . $criteria ."%'";
Should be firstname and not $firstname.
Also
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
While loop doesnt have a closing brackets
It should be like:
<table>
<?php
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
?>
<tr>
<td width="300" ><font face="Arial Black" size="2"><?php echo $row['firstname']?> <?php echo $row['lastname']?></font></td>
</tr>
<table> <---- This is html mistake also remove it
<tr> <----- This is html mistake also remove it
<?php
}
?>
</table>
I moved your table tag around loop because this is logical way to every row from loop generates row in table, but in some examples you can loop also whole tables just you will get lots of tables in your html code.
I think what you are looking for is mysqli_query($con, $query).
Try replacing your query() function call with mysqli_query()
Note that mysql_query() is depricated in favor of mysqli_query() for security reasons.
See the documentation for it here:
http://php.net/manual/en/mysqli.query.php
If that doesn't help then I'd suggest examining the code in your 'connect.php' that you are including. Also it would be helpful to get the exact text of the error, it would help us debug your code.
The line
$result = $query ($con, $query) or die ('error getting data from database');
doesn't make sense at all. $query is a variable containing the SQL instructions, not a function. And the variable $con has not been defined, at least not in the code you've shown.
Also, you should use the function mysqli_query() - http://php.net/manual/en/mysqli.query.php
So the line should be:
$result = mysqli_query($query) or die ('error getting data from database');
If you are using procedural style and $con is the link identifier returned by mysqli_connect() or mysqli_init(), use:
$result = mysqli_query($con,$query) or die ('error getting data from database');
Assuming you are using php mysql extension, below is the corrected solution to your problem.
<?php
if (isset($_POST['submitted'])){
include('connect.php');
$category = $_POST['category'];//I guess it is search category(e.g. firstname)
$criteria = strtolower($_POST['criteria']);
$query = "SELECT * FROM Customers WHERE LOWER({$category}) LIKE '%{$criteria}%'";
$result = mysql_query($query) or die (mysql_error());
$num_rows = mysql_num_rows($result);
echo "{$num_rows} results found";
echo '<table>';
while ($row = mysql_fetch_assoc($result)) {
?>
<tr>
<td width="300" >
<font face="Arial Black" size="2"><?php echo "{$row['firstname']} {$row['lastname']}"?></font>
</td>
</tr>
<?php } echo '</table>'; ?>

Delete from database php

I have a problem with a delete from database..So, I have:
<?php
include('createdb.php');
if(!empty ($_POST['tribuna']))
{
$delete = mysql_query("DELETE FROM tb_tribuna WHERE id = '".$_POST['tribuna']."';");
header("Location:index.php?a=buy"); //redirect
exit;
}
?>
<form id="formid" action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<label>Tribuna :</label> <select name="tribuna" class="tribuna">
<option selected="selected">-Select-</option>
<?php
$sql=mysql_query("select id,tribune_number from tb_tribuna ");
while($row=mysql_fetch_array($sql))
{
$id=$row['id'];
$tribune_number=$row['tribune_number'];
echo '<option value="'.$id.'">'.$tribune_number.'</option>';
} ?>
</select><br/><br/>
<input name="delete" type="submit" id="delete" value="Delete">
</form>
When I push on submit nothing happens...
I want that when I select an option and when I press delete to delete from the database row...
Help plizzz friends..
Assuming that "createdb.php" has the correct database connection information:
$conn = mysql_connect("$host","$db_uid","$db_pwd");
mysql_select_db("$db", $conn);
make your delete function look like this:
$sql = "DELETE FROM tb_tribuna WHERE id = '$_POST[tribuna]' ";
$result = mysql_query($sql, $conn) or die(mysql_error());
You need to pass the db connection to mysql_query.
And add "or die mysql_error()" to your mysql statements so that when something doesn't work, you get an error message that helps point you to where the problem is.

select items from mysql

making a simple movie review site to practice PHP. on one page ( a form) i write a title and review and submit, it then adds the info to mysql. i'm trying to create a page where i can delete reviews i've written. i'm going about this by returning all titles into a form tag, where i can select on and then submit that form to a process page and delete the item.
having issues with the WHILE statement and SQL statement.
$conn = mysql_connect($host, $user, $password)
or die("couldn't make connection");
mysql_select_db('cms', $conn)
or die("couldn't select database");
$sql = "SELECT * FROM frontPage";
$sql_result = mysql_query($sql, $conn)
or die("couldn't execute query");
while($row = mysql_fetch_array($sql_result)) {
$movieTitle = $row['title'];
}
?>
<form method="post" action="deleteReview_process.php">
<select name="title">
<option><?php echo $movieTitle; ?>
</select>
<input type="submit" name="delete" id="delete" value="delete" />
</form>
Try this, the fixes include closing your option tag, and including the option tag inside the MySQL loop so the option tag gets outputted each time there is a new item.
<?
$conn = mysql_connect($host, $user, $password)
or die("couldn't make connection");
mysql_select_db('cms', $conn)
or die("couldn't select database");
$sql = "SELECT * FROM frontPage";
$sql_result = mysql_query($sql, $conn)
or die("couldn't execute query");
?>
<form method="post" action="deleteReview_process.php">
<select name="title">
<?
while($row = mysql_fetch_array($sql_result)) {
$movieTitle = $row['title'];
?>
<option><?php echo $movieTitle; ?></option>
<?
}
?>
</select>
<input type="submit" name="delete" id="delete" value="delete" />
</form>
Well for one thing, you're overwriting $movieTitle each time your loop repeats...don't you want to display all movie titles in your select list?
If you want to display all the movie titles, you need to read the results in and store them all. Currently you are overwriting $movieTitle every time you pull a record from your result. Try something like this:
$titles = array();
while($row = mysql_fetch_array($sql_result)) {
$titles[] = $row['title'];
}
//...
<select name="title">
<option><?php echo implode("</option>\n<option>",$titles); ?></option>
</select>

Categories