I have a <datalist> element that gets a list of names from a table in a MySQL database. The list suggests names when you start typing, however there are some double Barrelled names in the Database, which it does not list.
Here is the code, showing the while loop etc.
<?php
$sql="SELECT * FROM students";
$result=mysql_query($sql);
echo '<input id="ChildName" name="ChildName" list="names" style=" width:450px; height:45px;font-size:20pt;" maxlength="15" size="6" > <datalist id="names">';
while($rows=mysql_fetch_array($result)){
?>
<option value="<?php echo $rows[Name]; ?>">
<?php
}
?>
</datalist>
I am a Network / System Administrator but I have write code while selecting my own available Database, Please change columns accordingly, here is the solution and hope this will work for you as well
<?php
$dbHost = 'localhost';
$dbUser = 'root';
$dbPass = '';
$dbName = 'rizwanranjha';
$dbConn = mysqli_connect ($dbHost, $dbUser, $dbPass) or die ('mysqli connect failed. ' . mysqli_error());
mysqli_select_db($dbConn, $dbName) or die('Cannot select database. ' . mysqli_error());
$sql = mysqli_query($dbConn, "SELECT * FROM iph_country");
echo '<input id="ChildName" name="ChildName" list="names" style=" width:450px; height:45px;font-size:20pt;" maxlength="15" size="6" >';
echo '<datalist id="names">';
while ($row = mysqli_fetch_array($sql)) {
echo "<option value='". $row['country_id']. "'>" . $row['country_name'] ."</option>";
}
echo '</datalist>';
?>
<?php
$sql="SELECT * FROM students";
$result=mysql_query($sql);
echo '<input id="ChildName" name="ChildName" list="names" style=" width:450px; height:45px;font-size:20pt;" maxlength="15" size="6" > <datalist id="names">';
while($rows=mysql_fetch_assoc($result)){
?>
<option value="<?php echo $rows["Name"]; ?>">
<?php
}
?>
</datalist>
either you use mysql_fetch_assoc($result) and then use $row['columnname']
OR
you use mysql_fetch_array($result) and then use $row[1];
Related
I want to create the PHP page that can retrieve data from database but for example when the user put 15 for age and selects the Categories "Male" then the data show for both male and female. How can I make it more specific just male for male, female for female Male & Child for Male & Child and so on? `
<?php
// check if the form has been submitted and display the results
if(isset($_POST["Age"]) && isset($_POST["Categories"])){
define('DB_NAME', 'test');
define('DB_USER', 'test');
define('DB_PASSWORD', 'test');
define('DB_HOST', 'localhost');
$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (!$conn){die('Could not connect: ' . mysqli_connect_error());}
// escape the post data to prevent injection attacks
$Age = mysqli_real_escape_string($conn, $_POST['Age']);
$Categories = mysqli_real_escape_string($conn, $_POST['Categories']);
$sql = "SELECT * FROM `Medic Rate` WHERE `Age` LIKE '%$Age%' AND `Categories` LIKE '%$Categories%'";
$result=mysqli_query($conn, $sql);
// check if the query returned a result
if(!$result){echo 'There are no results for your search';}
else{
// result to output the table
echo '<table class="table table-striped table-bordered table-hover">';
echo "<tr>
<th>Medic_Id</th>
<th>Age</th>
<th>Categories</th>
<th>Plan</th>
<th>Rate</th>
</tr>";
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
echo "<tr><td>";
echo $row['Medic_Id'];
echo "</td><td>";
echo $row['Age'];
echo "</td><td>";
echo $row['Categories'];
echo "</td><td>";
echo $row['Plan'];
echo "</td><td>";
echo $row['Rate'];
echo "</td></tr>";
}
echo "</table>";
}
mysqli_close($conn);
} // end submitted
else{// not submitted to output the form
?>
<form action=" " method="post">
<label>Enter Age:</label>
<input name="Age" type="number" placeholder="Type Here"><br><br>
<label>Enter Categories:</label>
<select name="Categories" />
<option value="Male">Male</option>
<option value="Female">Female</option>
<option value="Male & Child">Male & Child</option>
<option value="Female & Child">Female & Child</option>
<option value="Insured & Spouse">Insured & Spouse</option>
<option value="Insured & Family">Insured & Family</option>
</select><br><br>
<input type="submit" value="Enter">
</form>
<?php } // end not submitted?>`
try to change <select name="Categories" /> to <select name="Categories"> remove the backslash and remove the back tick at the end of script.
I create a dropdown list to select values:
<form action="." method="post" id="aligned">
<input type="hidden" name="action" value="update_customer">
<input type="hidden" name="customer_id"
value="<?php echo htmlspecialchars($customer['customerID']); ?>">
<label>Country:</label>
<select name="selected">
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass ='';
$db = 'tech_support';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(!$conn)
die('Could not connect: '. mysql_error());
mysql_select_db($db);
$selected= mysql_query("select * from countries where countryCode = '" .$customer['countryCode']. "'");
$sql = mysql_query("select * from countries order by countryName");
if($selectedrow = mysql_fetch_array($selected)){
echo "<option selected value=\"VALUE\">" . $selectedrow['countryName']."</option>";
}
//echo "<select>";
while ($row = mysql_fetch_array($sql)) {
echo "<option value =\"VALUE\">". $row['countryName']."</option>";
}
//echo "</select>";
?>
</select><br>
In another php file as below, I was trying to store the selected value for Country, but nothing is stored, why?
<?php $country_name = $_POST["selected"];
echo $country_name;//it always print out 'VALUE'-I guess it means null.
?>
You should use
echo "<option value ='".$row['countryName']."'>". $row['countryName']."</option>";
And I want to add something, MySQL is deprecated in PHP5 and removed from PHP7. what is your PHP version. If you use PHP 5 or later use mysqli.
I have a form designed with bootstrap style and I want to retrieve data from a database into a drop-down list. I tried this code, but I get a list with no text.
<div class="form-group"><label class="col-sm-2 control-label">Location</label>
<div class="col-sm-8"><select class="form-control m-b" name=Location>
<?php
$mysqli = new mysqli( 'localhost', 'cshrnaf_user2', '=cXlIBsdMkdr', 'cshrnaf_mis_db' );
/* check connection */
if (mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT * FROM adhoc";
$result = mysqli_query($mysqli,$query);
while($rows = mysqli_fetch_assoc($result))
{
echo "<option value=" . $rows['Aim'] . "></option>";
echo "<option value='{".$d['Aim']."}'>".$d['Aim']."</option>";
}
?>
$d is never mentioned before you try to echo it, so what is it's content?
echo "<option value=" . $rows['Aim'] . "></option>"; has two issues: firstly, the value is not encased in quotes, and secondly, there is no content in the tag, so no text will output.
Try changing your while to:
while($rows = mysqli_fetch_assoc($result)){
echo "<option value='{$rows['Aim']}'>{$rows['Aim']}</option>";
}
As long as $rows['Aim'] contains the content you wish to output, this should work.
// cat is array fetch from database
<select name="cat" id="cat_id" style="width:170px" value="<?php echo $_POST['cat']; ?>">
<option value="0"></option>
<?php
foreach ($cat as $row) {
?>
<option value="<?php echo $row->tag_cat_id ?>" ><?php echo $row->tag_cat_name ?></option>
<?php }
?>
</select>
</select>
You should select database in your file.Above you only connect to your localhost.And you should use variable name $rows for all fetch values
if (!mysqli_select_db("mydbname")) {
echo "Unable to select database: " . mysqli_error();
exit;
}
I'm using a form to input new projects into my database. One of the fields is Lead Writer. I want to add a drop down menu to that field that will display the names of the lead writers from my database that the user can then select to populate that field. I've managed to get the drop down to appear in the field, but my code isn't generating any names. I tried setting up a function that would call those results, but it's obviously not working. The form worked well prior to my changes, so it's not an issue connecting to the database. Any help would be greatly appreciated.
function query(){
$myNames = "SElECT LastName FROM Projects";
$result = $mysqli->query($myNames);
while($result = mysqli_fetch_array($myNames)){
echo '<option value=' . $record['LastName'] . '>' . $record['LastName'] . '</option>';
}
}
?>
<?php
$connection->close();
?>
<form action="http://www.oldgamer60.com/Project/NewProject.php" method="post">
<div class="fieldset">
<fieldset>
Project: <input type="text" name="Project value="<?php if(isset($Project)){ echo $Project; } ?>">
<span class="error">* <?php if(isset($ProjectErr)){ echo $ProjectErr; } ?></span>
<br><br>
Client: <input type="text" name="Client" value="<?php if(isset($Client)){ echo $Client; } ?>">
<span class="error">* <?php if(isset($ClientErr)){ echo $ClientErr; } ?></span>
<br><br>
Lead Writer: <select name="dropdown">
<?php query() ?>
</select>
<br><br>
Date Received: <input type="text" name="DateReceived" value="<?php if(isset($DateReceived)){ echo $DateReceived; } ?>">
<span class="error">* <?php if(isset($DateReceivedErr)){ echo $DateReceivedErr; } ?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</fieldset>
</div>
</form>
Edited Code:
<html>
<head>
</head>
<body>
<?php
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "oldga740_SeniorProject";
// create connection
$connection = new mysqli($servername, $username, $password, $dbname);
function query($mysqli){
$myNames = "SELECT LastName FROM Projects";
if(!$result = $mysqli->query($myNames)) {die($mysqli->error);} // check for error message
if($result->num_rows > 0){ // if there is rows
while($record = $result->fetch_array()){
echo '<option value="' . $record['LastName'] . '">' . $record['LastName'] . '</option>';
}
} else { // if there is no rows
echo '<option value="">No Rows</option>';
}
}
?>
<form>
Lead Writer: <select name="dropdown">
<?php query($mysqli); ?>
</select>
</form>
<?php
$connection->close();
?>
</body>
</html>
2nd Edit:
// create connection
$connection = new mysqli($servername, $username, $password, $dbname);
function query($connection){
$myNames = "SELECT LastName FROM Projects";
if(!$result = $connection->query($myNames)) {die($mysqliconnection->error);} // check for error message
if($result->num_rows > 0){ // if there is rows
while($record = $result->fetch_array()){
echo '<option value="' . $record['LastName'] . '">' . $record['LastName'] . '</option>';
}
} else { // if there is no rows
echo '<option value="">No Rows</option>';
}
}?>
<?php
$connection->close();
?>
<form>
Lead Writer: <select name="dropdown">
<?php query($connection); ?>
</select>
</form>
</body>
</html>
You have a variable scope issue - http://php.net/manual/en/language.variables.scope.php. $mysqli is undefined in your function query(). You need to pass it as a param. Also, you were trying to do mysqli_fetch_array() on the query string, instead of the mysqli result. I have updated it to the OO ->fetch_array().
function query($mysqli){
$myNames = "SELECT LastName FROM Projects";
$result = $mysqli->query($myNames);
while($record = $result->fetch_array()){
echo '<option value=' . $record['LastName'] . '>' . $record['LastName'] . '</option>';
}
}
You will also need to pass it in your call
Lead Writer: <select name="dropdown">
<?php query($mysqli); ?>
</select>
You can add some debugging to find out why it is not printing
function query($mysqli){
$myNames = "SELECT LastName FROM Projects";
if(!$result = $mysqli->query($myNames)) {die($mysqli->error);} // check for error message
if($result->num_rows > 0){ // if there is rows
while($record = $result->fetch_array()){
echo '<option value="' . $record['LastName'] . '">' . $record['LastName'] . '</option>';
}
} else { // if there is no rows
echo '<option value="">No Rows</option>';
}
}
per your edit - https://stackoverflow.com/posts/34257335/revisions
Your mysqli connection is $connection
// create connection
$connection = new mysqli($servername, $username, $password, $dbname);
so not sure why you are trying to use $mysqli
$mysqli->query($myNames)
as $connection != $mysqli.
As you are doing the query in a function, you don't need to rename all instances of $mysqli to $connection, as you can just change to
Lead Writer: <select name="dropdown">
<?php query($connection); ?>
</select>
Why this code is not update information?
HTML Form:
<form>
<lable> ID# :</lable>
<input id= "ID" name= "ID" type= "text">
<p>
<label>Select field to Edit</label>
<select name="change">
<option value=""></option>
<option value="fname">First Name</option>
<option value="lname">Last Name</option>
<option value="email">Email</option>
<option value="city">City</option>
<option value="zip">Zip</option>
</select>
<lable> Enter the value to be replaced </label>
<input id = "replace" name = "replace" type = "text">
</p>
<input name="submit" type="submit" value="Submit">
PHP Code for updating information from database:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$conn = mysql_connect($servername,$username,$password);
if(!$conn)
{
die('Error!' . mysqli_error());
}
$sql = 'SELECT * FROM users';
mysql_select_db('mitsdatabase');
$retval = mysql_query($sql, $conn);
if(! $retval)
{
die('Could not get data:' . mysql_error());
}
echo "<table width='300' cellpadding='5' border='1'>";
echo "<tr> <td>ID#</td> <td>FirstName</td> <td>LastName</td> <td> Email </td> <td> City </td> <td> State </td> <td> Zip </td> </tr>";
while($row = mysql_fetch_array($retval,MYSQL_ASSOC))
{
echo "<tr> <td>{$row['ID']}</td> . <td>{$row['fname']}</td> . <td>{$row['lname']}</td> . <td>{$row['email']}</td> . <td>{$row['city']}</td> . <td>{$row['state']} </td>. <td>{$row['zip']}</td>";
}
echo "</table>";
$db_id = $_POST['ID'];
$db_select = $_POST['change'];
$db_replace= $_POST['replace'];
echo " Do you want to edit any entry?";
if(!_POST['submit'])
{
echo " ";
}
else{
mysqli_query("UPDATE users SET db_select='$db_replace' WHERE ID = $db_id ");
}
mysql_close($conn);
?>
I want to update informate selected from select field but somehow it is not doing any thing. Can someone help me what is wrong with this code.
Is your PHP on the same page as your HTML? If not, you are not directing to your php code within the <form> element in your HTML.
For example, if your PHP file was called 'myphpcode.php' (and in the same folder as your HTML code) then you could direct to it using the following:
<form method="post" action="myphpcode.php">
If you want to post to the same page just change <form> to <form method="post" action="#"> and get variables in php like this $nameofvar = $_POST['nameofinputfield'] . Each input field should have the name tag.
Also try to change your mysql connect to this :
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
and after you finished the query
$conn->close();
and the query to insert
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
and you can modify this $sql string to update or delete