I need to create a filled drop down list which is linked to my table called called 'dog' in phpmyadmin. I need a user to be able to select a dog from the list and press search and the results show up. And all information be stored in my table in phpmyadmin. This is what I have so far:
It doest work its just an empty drop down and it does nothing. Please help.
<?php
// set up connection parameters
$dbHost = 'hostnamegoeshere';
$databaseName = 'databasenamehere';
$username = 'usernamehere';
$password = 'passwordhere';
// make the database connection
$db = new PDO("mysql:host=$dbHost;dbname=$databaseName;charset=utf8","$username", "$password");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // enable error handling
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); // turn off emulation mode
?>
//Return an error if bad connection
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ')'
.$mysqli->connect_error);
}
//query database for results
$query = $mysqli->query("SELECT * FROM 'dog'");
?>
<h3> Search dogs</h3>
<select>
<?php
$stmt = $mysqli->prepare($query);
$stmt->execute();
$res = $stmt->get_result();
while($dropdown = $res->fetch_array(MYSQLI_ASSOC)) {
echo '<option value="' . $dropdown['dog'] . '"></option>';} ?>
</select>
I will be very grateful for any help
USE THIS
$res = $stmt->get_result();
$res =$res->fetch_array(MYSQLI_ASSOC)
foreach($res as $a){
echo '<option value="' . $a['dog'] . '">'. $a['dog'] .'</option>';} ?>
}
AT PLACE OF
$res = $stmt->get_result();
while($dropdown = $res->fetch_array(MYSQLI_ASSOC)) {
echo '<option value="' . $dropdown['dog'] . '"></option>';} ?>
Number of issues in your CODE
1) Wrap off quotes form table name(SELECT * FROM 'dog')quotes
2) Don't use prepare and query at one time.($mysqli->query,$mysqli->prepare)
3) Add text to your option(<option value="value"></option>)
4) You are mixing mysqli with pdo
You code would be
Create you connection with mysqli
$mysqli=mysqli_connect($dbHost,$username,$password,$databaseName);
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ')'
.$mysqli->connect_error);
}
<h3> Search dogs</h3>
<select>
<?php
$stmt = $mysqli->query("SELECT * FROM dog");// wrap off and use only query to run
$stmt->execute();
$res = $stmt->get_result();
while ($dropdown = $res->fetch_array(MYSQLI_ASSOC)) {
echo '<option value="' . $dropdown['dog'] . '">'.$dropdown['dog'].'</option>';// add text to dropdown
}
?>
</select>
Related
This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 6 years ago.
So I'm new to mysqli. All of the examples I find online seem to be the old (procedural) way of doing things. Can someone tell me why my code isn't working below? My db is 'templatedb'. My Table is 'template'. I have one entry in my table, but I'm receiving no output with my echo. I'm not getting any errors with my code.
<div id="templateSelector">
<?php
$hostname = "localhost";
$username = "root";
$password = "";
$db = "templatedb";
//connect
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$database = mysqli_connect($hostname, $username, $password, $db);
if(!$database){
die("Could not connect to the database");
}
if ($database->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
} else {
$sql = "SELECT * FROM template";
if (!$result = $database->query($sql)) {
die('There was an error running the query [' . $db->error . ']');
} else {
echo "<label>Select Template</label>";
echo "<select name='templates'>";
while ($row = $result->fetch_assoc()) {
echo "hello";
echo $row['template_name'];
// echo "<option value='" . $row['template'] . "'>" . $row['template'] . "</option>";
}
echo "</select>";
}
}
?>
Try doing the following, worked for me
<div id="templateSelector">
<?php
$hostname = "localhost";
$username = "root";
$password = "";
$db = "templatedb";
$mysqli = mysqli_connect($hostname, $username, $password, $db);
if($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
} else {
$sql = "SELECT * FROM template";
$result = mysqli_query($mysqli, $sql);
if(!$result = $mysqli->query($sql)) {
die('There was an error running the query [' . $db->error . ']');
} else {
echo "<label>Select Template</label>\n";
echo "<select name='templates'>\n";
while($row = $result->fetch_assoc()) {
echo "<option>id = " . $row['id'] . "</option>\n";
}
echo "</select>";
}
}
?>
</div>
Make sure your DATABASE is called templatedb and the table it is in is called template and there is a row called id. I know that sounds trivial, but spelling mistakes will break your code.
I have the following code SELECTING the Title and Image from the "Courses" table in my database.
<?php
$username = 'REMOVED';
$password = 'REMOVED';
try {
$conn = new PDO('mysql:host=localhost;dbname=REMOVED', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT Title, Image FROM Courses');
$stmt->execute();
while($row = $stmt->fetch()) {
print_r($row);
}
}
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
How can I make it so that the Title has a header tag wrapped around it and the Image is inside of an image src=""?
depending on your PDO settings the result may for example be returned in an associative array (which would be the most common default setting):
while($row = $stmt->fetch()) {
echo '<img src="' . $row["Image"] . '" title="' . $row["Title"] . '">';
}
update: to force the fetching of associative array, just replace $stmt->fetch() with $stmt->fetch((PDO::FETCH_ASSOC)
replace while loop with following code:
$string="<header>";
$imagesrc="";
While($row=$stmt->fetch()){
$string+=$row['Title'];
$imagesrc=$row['Image'];
}
$string+="</header>";
$stringImage="<img src='".$imagesrc."' />";
I am trying to get my PHP script to print all rows i have in my database in a neat order. Currently Im not getting anything. My table has 4 columns, Name, Address, Long and Lat, and 2 rows with data. The table is called Locations. I am using the following code but im not getting to to work:
<?php
$con=mysqli_connect("localhost","user","pass","db");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM `Locations` ";
if ($result = mysqli_query($con, $sql))
{
$resultArray = array();
$tempArray = array();
while($row = $result->fetch_object())
{
$tempArray = $row;
array_push($resultArray, $tempArray);
}
echo json_encode($resultArray);
}
// Close connections
mysqli_close($con);
?>
Here is a simple example using pdo instead of mysqli
$dbHOST = 'localhost';
$dbNAME = 'nilssoderstrom_';
$dbUSER = 'nilssoderstrom_';
$dbPASS = 'Durandal82!';
$pdo = new PDO('mysql:host=' . $dbHOST . ';dbname=' . $dbNAME, $dbUSER, $dbPASS); // create connection
$stmt = $pdo->prepare("SELECT Name, Address, Long, Lat FROM Locations");
//you should never use *, just call each field name you are going to use
$stmt->execute(); // run the statement
$arr = $stmt->fetchAll(PDO::FETCH_ASSOC); // fetch the rows and put into associative array
print_r($arr); // print all array items, unformatted
and you can echo out the data and format it yourself using a for loop like so
for($i=0; $i<sizeof($arr); $i++) { // this will loop through each row in the database. i prefer this method over while loops as testing has shown this is much faster for large scale tables
echo 'Name: ' . $arr[$i]['Name'] . '<br />'; // $arr is the array name, $i is the number of the array item, or iterator, ['Name'] is the field name
echo 'Address: ' . $arr[$i]['Address'] . '<br>';
echo 'Long: ' . $arr[$i]['Long'] . '<br>';
echo 'Lat: ' . $arr[$i]['Lat'] . '<br>';
}
If the names are correct, this would echo out your row ID and row CITY. Just change the names to your field names. If you want further assistance, feel free to ask.
However, if you want to stick with mysqli, give the following code a wirl.
$dbHOST = 'localhost';
$dbNAME = 'nilssoderstrom_';
$dbUSER = 'nilssoderstrom_';
$dbPASS = 'Durandal82!';
$mysqli = mysqli_connect($dbHOST, $dbUSER, $dbPASS, $dbNAME);
$query = "SELECT Name, Address, Long, Lat FROM Locations";
$result = mysqli_query($mysqli, $query);
if($result) {
while($row = mysqli_fetch_assoc($result)) {
echo 'Name: ' . $row['Name'] . '<br />';
echo 'Address: ' . $row['Address'] . '<br>';
echo 'Long: ' . $row['Long'] . '<br>';
echo 'Lat: ' . $row['Lat'] . '<br>';
}
}
change fieldname to the field you want to display
EDIT: Paste the following code. It will echo out the number of rows. This will tell you if the query statement is correct.
$dbHOST = 'localhost';
$dbNAME = 'nilssoderstrom_';
$dbUSER = 'nilssoderstrom_';
$dbPASS = 'Durandal82!';
$pdo = new PDO('mysql:host=' . $dbHOST . ';dbname=' . $dbNAME, $dbUSER, $dbPASS);
$stmt = $pdo->query("SELECT Name, Address, Long, Lat FROM Locations");
echo $stmt->rowCount();
Fetch query result as associative array and use for each to print all results
<?php
$con=mysqli_connect("localhost","user","pass","db");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM `Locations` ";
if ($result = mysqli_query($con, $sql))
{
while($rows = mysqli_fetch_assoc($result)) {
foreach($rows as $key => $val)
{
echo $val;
}
}
}
mysqli_close($con);
?>
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 have a MySQL query like this written in PHP:
$merkki = $_GET["merkki"];
// Retrieve all the data from the table
//to show models based on selection of manufacturer
$result = mysql_query("SELECT * FROM Control_Mallit WHERE merkki_id = $merkki")
or die(mysql_error());
echo '{';
while($row = mysql_fetch_array($result)){
echo '"' . $row['id'] . '"' . ":" . '"' . $row['malli'] . '"';
}
echo '}';
Result is correct, but how I can get a comma after each record? If I echo (,) after each row my code doesn't work. I need it formatted as described below.
{
"":"--",
"series-1":"1 series",
"series-3":"3 series",
"series-5":"5 series",
"series-6":"6 series",
"series-7":"7 series"
}
What's the best way to do this?
Immediately stop using your code. It is vulnerable to SQL injection. Think of what would happen if the value of merkki was 1 OR 1=1. The statement would return all records:
SELECT * FROM Control_Mallit WHERE merkki_id = 1 OR 1=1
You need to bind parameters to your query using mysqli_ or PDO functions (mysql_ functions are being deprecated. Also, use a column list and do not SELECT *.
Here is a possible solution using mysqli_ (not tested):
<?php
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'world');
/* check connection */
if (!$link) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$array = array();
/* create a prepared statement */
$stmt = mysqli_prepare($link, "SELECT id, malli FROM Control_Mallit WHERE merkki_id = ?");
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, 'i', $_GET[merkki]);
/* execute query */
$result = mysqli_stmt_execute($stmt);
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
$array[] = '"' . $row['id'] . '"' . ":" . '"' . $row['malli'] . '"';
}
/* free result set */
mysqli_free_result($result);
/* close connection */
mysqli_close($link);
echo '{' . implode(',', $array) . '}';
?>
Edit
Following your original code, this solution should work:
$merkki = $_GET["merkki"];
$array = array();
// Retrieve all the data from the table to show models based on selection of manufacturer
$result = mysql_query("SELECT * FROM Control_Mallit WHERE merkki_id = $merkki")
or die(mysql_error());
while($row = mysql_fetch_array($result)){
$array[] = '"' . $row['id'] . '"' . ":" . '"' . $row['malli'] . '"';
}
echo '{' . implode(',', $array) . '}';
Try:
$merkki = $_GET["merkki"];
$merkki = mysql_real_escape_string($merkki);
// Retrieve all the data from the table to show models based on selection of manufacturer
$result = mysql_query("SELECT * FROM Control_Mallit WHERE merkki_id = $merkki")
or die(mysql_error());
$numRows = mysql_num_rows($result);
$row = 1;
echo '{';
while($row = mysql_fetch_array($result)){
echo '"' . $row['id'] . '"' . ":" . '"' . $row['malli'] . '"';
if ($row < $numRows) {
echo ',';
}
$row++;
}
echo '}';
It just uses the row count to determine if it should echo a comma or not based on whether or not it is on the last result.
Also, be sure to escape any input you pass to mysql queries or you are vulnerable to SQL injection. See about switching to PDO or Mysqli in the future.
I'd just stick everything in an array and use json_encode() to output it, eg
$data = array();
while ($row = mysql_fetch_array($result)) {
$data[$row['id']] = $row['malli'];
}
echo json_encode($data);
Small example here - http://codepad.viper-7.com/My27XJ
Also, you should not be using the deprecated mysql extension. Instead, I recommend PDO, eg
$db = new PDO(/* connection details */);
$stmt = $db->prepare('SELECT id, malli FROM Control_Mallit WHERE merkki_id = ?');
$stmt->bindParam(1, $_GET['merkki']);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
// and so on