I want to pick up peoples names from a phpmyadmin database and place them in a HTML select box, when the user picks a name from the select box it should display the detail from the database for that person in a table. I can't seem to get this to work, I can get the names to pick up from the database and display in a select box but when you click on the name it seems to bring up every record in the database rather than just the one for that person. I am using mysql rather than mysql. Here is my code
This is my back end stuff
<?php
$conn = mysqli_connect("localhost", "root", "root") or die ("No connection");
mysqli_select_db($conn, "flat") or die("db will not open");
$query = "select FlatCode, Address from FLAT";
$result = mysqli_query($conn, $query) or die("Invalid query");
echo "<table border='1'><tr><th>modulecode</th><th>studentnum</th></tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr><td>" . $row[0] . "</td><td>" . $row[1] . "</td></tr>";
}
echo "</table>";
mysqli_close($conn);
?>
this is my front end stuff
<font size="4"> Choose an Owner Name</font><br><br>
<form action="flat.php" method="post">
<select name="name">
<?php
$con = mysqli_connect("localhost", "root", "root") or die ("No connection");
mysqli_select_db($con , "flat") or die ("db will not open");
$query = "SELECT distinct OwnerName, FlatCode, Address from FLAT";
/*$query= $_POST ("name")
function change_guery($query)
mysqli_use_result*/
$result = mysqli_query($con, $query) or die("Invalid query");
while($rows = mysqli_fetch_array($result))
{
echo "<option value=\"" . $rows[0] . "\">" . $rows[0] . "</option>";
}
echo "</select>";
mysqli_close($con);
?>
<input type="submit" value="Submit Value">
</form></body></html>
There is a problem in your flat.php code. You are posting the the info correctly via form but you forgot to receive it via $_POST in flat.php.
See the following code and comments in it, it should work -
<?php
$n = $_POST["name"];//we receive the name passed by the form
$conn = mysqli_connect("localhost", "root", "root") or die ("No connection");
mysqli_select_db($conn, "flat") or die("db will not open");
$query = "select FlatCode, Address from FLAT WHERE `OwnerName` = '$n' LIMIT 1";//see the changes here
$result = mysqli_query($conn, $query) or die("Invalid query");
echo "<table border='1'><tr><th>modulecode</th><th>studentnum</th></tr>";
$row = mysqli_fetch_array($result);
//as the result will return 1 row only so we dont need while loop here
echo "<tr><td>" . $row[0] . "</td><td>" . $row[1] . "</td></tr>";
echo "</table>";
mysqli_free_result($result);//dont forget to free result
mysqli_close($conn);
?>
Related
I want to populate a drop down list with data from a specific field in the database. Here is my sample code
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("disertation ", $con);
$results = mysql_query("SELECT name FROM user_parent;");
?>
<select name="name">
<option value="name">Select one</option>
<?php
while($row=mysql_fetch_array($results))
{ echo '<option value=" ' . $row['name'] . ' ">' . $row['name'] . '</option>'; }
?>
</select>
It's currently displaying nothing from db, any help?
Try this, some white space in your code mysql_select_db("disertation", $con);
mysql_select_db("disertation", $con);
$results = mysql_query("SELECT name FROM user_parent") or die (mysql_error());
Make your mysql_fetch_array call read:
mysql_fetch_array($results, MYSQL_ASSOC)
Without MYSQL_ASSOC you can't refer to column names in $row.
Also, consider using MYSQLI or PDO. MYSQL is considerably outdated.
I would recommend you to use mysqli instead of mysql
<?php
$con=mysqli_connect("localhost","root","","disertation ");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$resource= mysqli_query($con,"SELECT * FROM user_parent");
echo "<select class="name"><option value="name">Select one</option>";
while($result = mysqli_fetch_array($resource)){
echo '<option value="'.$result["name"].'">'.$result["name"].'</option>';
}
echo "</select>";
mysqli_close($con);
?>
To answer your question, directly, you should be first checking if there are any errors (mysql_error()) and then checking there are some results (mysql_num_rows) - these make for easier debugging of your code, since it will tell you what is wrong.
Try this;
<?php
// Connect with user
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// Select database
mysql_select_db("disertation", $con);
// Run query
$results = mysql_query("SELECT `name` FROM `user_parent`;") or die (mysql_error());
// Check for no results
if (mysql_num_rows($results) == 0)
{
echo 'There are no options for you to select.';
}
else
{
// If results, loop them.
// If the names are user input, make sure they're displayed in non-raw form
echo '<select name="name">
<option value="name">Select one</option>';
while($row = mysql_fetch_assoc($results))
{
$name = htmlentities($row['name'], ENT_QUOTES, "UTF-8");
echo '<option value=" ' . $name . ' ">' . $name . '</option>';
}
echo '</select>';
}
Will edit with a mysqli_ solution, if that is an option for you, since mysql_ is deprecated and will be dropped from PHP support, sooner or later.
MySQLi solution;
<?php
// Connect to database;
$mysqli = new mysqli("localhost", "my_user", "my_password", "data_base");
if (mysqli_connect_errno())
{
die("Connect failed: " . mysqli_connect_error());
}
$result = $mysqli->query("SELECT `name` FROM `user_parent`");
if ($result->num_rows > 0)
{
echo '<select name="name">
<option value="name">Select one</option>';
while($row = $result->fetch_assoc)
{
$name = htmlentities($row['name'], ENT_QUOTES, "UTF-8");
echo '<option value=" ' . $name . ' ">' . $name . '</option>';
}
echo '</select>';
$result->close();
}
else
{
echo 'There are no options for you to select.';
}
I am trying to access image for each company, when the company details is got through search. This is part of my coding.
<?php
$result = mysql_query("SELECT * FROM enquiry where product like '%$title%' ") or die("error");
$found = mysql_num_rows($result);
if ($found > 0) {
while ($row = mysql_fetch_array($result)) {
echo ("<img src='try5.php?id=" . $row['id'] . "' height='100' width='100'><br>");
echo ("$row[mainproduct]$row[Companyname],$row[District]<br><br>$row[description].<a href=$row[Website]>Read more...</a><br><brContact Person:$row[ContactPerson]<br>Mobile no :$row[Mobile]<br>Website:<a href=$row[Website]>$row[Website]</a><br><br><hr><br><br>");
}
} else {
echo "<li>No results Found<li>";
}
//Coding of try5.php
$link = mysql_connect("localhost", "root", "") or die("Could not connect: " . mysql_error());
mysql_select_db("test") or die(mysql_error());
$sql = "SELECT image FROM imtest";
$result = mysql_query("$sql") or die("Invalid query: " . mysql_error());
header("Content-type: image/jpeg");
echo mysql_result($result, 0);
?>
I am getting same image for all company details. For each company I need a different image. I have stored the images in different tables not along with data, is it right? How shall I do it using php?
Your SQL statment will always return the same result. You forgot to include WHERE, like:
$sql = "SELECT image FROM imtest WHERE id=" . $_GET['id'];
I have write some php code to retrieve some records from a mysql database in the form of table. the table have three columns where first two were filled up from the database and the third is a drop down list for each row. Now I want to select the drop down list from the populated rows and store the information of each rows in a new database.
Please view the codes and reply for your suggestions.
<html>
<?
// data from the "recordentry.php";
$date = $_POST['date'];
$course = $_POST['course'];
$period = $_POST['period'];
$batch = $_POST['batch'];
$subject = $_POST['subject'];
$faculty = $_POST['faculty'];
?>
<p> Current Date&Time:<? echo $date ?></p>
<form enctype="multipart/form-data" name="f1" method="POST" ACTION="<?=$self ?>"">
<?
$db = "contact";
//mysql_connect(localhost,$_POST['username'],$_POST['pass']);
$link = mysql_connect("localhost", "root", "");
if (!$link)
die("Couldn't connect to MySQL");
mysql_select_db($db, $link) or die("Couldn't open $db: " . mysql_error());
$result = mysql_query("SELECT name,uic FROM student where batch='$batch' AND course='$course' order by name") or die("SELECT ERROR: " . mysql_error());
$num_rows = mysql_num_rows($result);
echo "<table border='1' align='center'><tr><th>Name</th><th>Unique Identification Code</th>
<th>Attendance</th></tr>";
while ($row = mysql_fetch_array($result))
{
//Display the results in different cells
echo "<tr><td align=center>" . $row['name'] . "</td><td align=center>" . $row['uic'] . "</td><td align=center><select name='attendance' style='background-color:#FFC'>
<option>Present
<option>Absent
</select></td></tr>";
$data[] = array(
'name' => $row['name'],
'uic' => $row['uic'],
'attendance' => $row['attendance']
);
}
echo "<tr><td><input type='submit' value='Submit' name='submit_button' />";
echo "</table>";
foreach ($data as $value)
{
$name = mysql_result($value['name']);
$uic = mysql_result($value['uic']);
$a_status = mysql_result($value['attendance']);
$db = "contact";
$link = mysql_connect("localhost", "root", "");
//$link = mysql_connect("localhost",$_POST['username'],$_POST['password']);
if (!$link)
die("Couldn't connect to MySQL");
mysql_select_db($db, $link) or die("Select Error: " . mysql_error());
$result = mysql_query("INSERT INTO attendance(date, course, period, batch, subject, faculty,name, uic, attendance) VALUES ('$date', '$course', '$period', '$batch', '$subject', '$faculty', '$name', '$uic', '$a_status')") or die("Insert Error: " . mysql_error());
mysql_close($link);
}
?>
</form>
</html>
the above code can populate the table off all the retrieved data from the database. but after submit it can not store the last three fields $name, $uic and $attendance. so, please help me.
Try this:
$name = mysql_result($result, $value['name']);
$uic = mysql_result($result, $value['uic']);
$a_status = mysql_result($result, $value['attendance']);
This will get the values once - but you reuse $result in that query (when you insert) so it will get overwritten. Change either the first call or the second.
form1.php
<?php
$connection = mysql_connect("localhost","root","")
or die ("Couldn't Connect To Server");
$query = "CREATE DATABASE IF NOT EXISTS db1";
$result = mysql_query($query)
or die ("Query Failed: " . mysql_error());
$db = mysql_select_db("db1", $connection)
or die ("Couldn't Select Database");
$query = "CREATE TABLE IF NOT EXISTS table1 (fname VARCHAR(20), lname VARCHAR(20), mail VARCHAR(20))";
$result = mysql_query($query)
or die ("Query Failed: " . mysql_error());
function insertvalues (){if ( isset ($_POST['fname']{0}, $_POST['lname']{0}, $_POST['mail']{0}) ){
$query = "INSERT INTO table1 (fname, lname, mail) VALUES ('".$_POST[fname]."', '".$_POST[lname]."', '".$_POST[mail]."')";
$result = mysql_query($query)
or die ("Query Failed: " . mysql_error());
}
else{
echo "No Values Entered. Please Press Back In Your Browser And Enter Some Values.";
}}
$value1 = "";
if isset($value1) {$query = "SELECT * FROM table1";
$result = mysql_query($query)
or die ("Query Failed: " . mysql_error());
echo "<TABLE BORDER = '1'>";
echo "<TR>";
echo "<TH>First Name</TH><TH>Last Name</TH><TH>Mail</TH>";
echo "</TR>";
while ($row = mysql_fetch_array($result))
{
echo "<TR>";
echo "<TD>", $row['fname'], "</TD><TD>",
$row['lname'], "</TD><TD>",
$row['mail'], "</TD>";
echo "</TR>";
}
echo "</TABLE>";}
else {
echo "<BR>No Table".
}
mysql_close($connection);
?>
I'm contemplating on what to put inside $value1. How do I check if"No Values Entered. Please Press Back In Your Browser And Enter Some Values." error was shown, and if it was, do not display the table?
is this what you asked for?
<?php
$connection = mysql_connect("localhost","root","")
or die ("Couldn't Connect To Server");
$query = "CREATE DATABASE IF NOT EXISTS db1";
$result = mysql_query($query)
or die ("Query Failed: " . mysql_error());
$db = mysql_select_db("db1", $connection)
or die ("Couldn't Select Database");
$query = "CREATE TABLE IF NOT EXISTS table1 (fname VARCHAR(20), lname VARCHAR(20), mail VARCHAR(20))";
$result = mysql_query($query)
or die ("Query Failed: " . mysql_error());
function insertvalues (){if ( isset ($_POST['fname']{0}, $_POST['lname']{0}, $_POST['mail']{0}) ){
$query = "INSERT INTO table1 (fname, lname, mail) VALUES ('".$_POST[fname]."', '".$_POST[lname]."', '".$_POST[mail]."')";
$result = mysql_query($query)
or die ("Query Failed: " . mysql_error());
return true;
}
else{
echo "No Values Entered. Please Press Back In Your Browser And Enter Some Values.";
return false;
}}
$value1 = insertvalues();
if isset($value1) {$query = "SELECT * FROM table1";
$result = mysql_query($query)
or die ("Query Failed: " . mysql_error());
echo "<TABLE BORDER = '1'>";
echo "<TR>";
echo "<TH>First Name</TH><TH>Last Name</TH><TH>Mail</TH>";
echo "</TR>";
while ($row = mysql_fetch_array($result))
{
echo "<TR>";
echo "<TD>", $row['fname'], "</TD><TD>",
$row['lname'], "</TD><TD>",
$row['mail'], "</TD>";
echo "</TR>";
}
echo "</TABLE>";}
else {
echo "<BR>No Table".
}
mysql_close($connection);
?>
the diffrence from your code is i added a return value of true if its successfully inserted and false if not. and gave that value into $value1.
And if i may .. this code have some serious performace and other problems starting with email often needs more than 20 charaters, and running a create db, create table queries on every run .. etc.
$sqlQuery = "SELECT * FROM allowedUsers WHERE UserID = '" . $kUserID . "'";
$result=mysql_query($sqlQuery, $db);
if(!result)
{
echo "Error running query <br>" . mysql_error();
exit;
}
while($row = mysql_fetch_array($result))
{
echo $row[2];
}
I run the SQLQuery in phpMyAdmin and I am getting a valid result (1 row)
the table (allowedUsers) has 6 fields
I can't get anything out of the DB.
Any help is appreciated.
if(!result) should be if(!$result)
According to PHP.net's documentation, you don't need to pass $db to mysql_query(). Take a look at the example code:
<?php
mysql_connect("localhost", "mysql_user", "mysql_password") or
die("Could not connect: " . mysql_error());
mysql_select_db("mydb");
$result = mysql_query("SELECT id, name FROM mytable");
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
printf("ID: %s Name: %s", $row[0], $row[1]);
}
mysql_free_result($result);
?>
It may be helpful to see your connection code, ensure you've selected a database, etc.