How to load php file to dynamically load dropdown - php

I have a PHP script that dynamically shows the 'course' options from my database
<?php
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = '';
$con = mysqli_connect($db_host,$db_user,$db_pass, $db_name);
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$sql = "SELECT courseID, name FROM courses";
$result = mysqli_query($con, $sql) or die("Error: ".mysqli_error($con));
while ($row = mysqli_fetch_array($result))
{
echo'<option value="'.$row['courseID'].'">'.$row['name'].'</option>';
}
?>
I have a dropdown in my HTML (scorecard.php) page.
<form> <select id="selectCourse" > <option value = "">Select Course</option></select></form>
I was wondering would anyone know a script or way of getting this data to display in my dropdown.
Thanks for any help

You have to run your while loop inside the select tag
Here is updated code
<?php
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = '';
$con = mysqli_connect($db_host,$db_user,$db_pass, $db_name);
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$sql = "SELECT courseID, name FROM courses";
$result = mysqli_query($con, $sql) or die("Error: ".mysqli_error($con));
?>
<form>
<select id="selectCourse" >
<option value = "">Select Course</option>
<?php while ($row = mysqli_fetch_array($result))
{
echo'<option value="'.$row['courseID'].'">'.$row['name'].'</option>';
} ?>
</select>

echo'<option value="'.$row['courseID'].'">'.$row['name'].'</option>';
change it to
$courses[] = '<option value="'.$row['courseID'].'">'.$row['name'].'</option>';
and where u want it to be displayed
foreach($courses as $c){
echo $c;
}

Related

PHP and SQL -- Select from database

I have a problem with this code. It has syntax error and I don't know what is it.
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'id1381007_accounts';
$conn = new mysqli($host,$user,$pass,$db) or die($mysqli->error);
if (!$conn) {
die('Could not connect: ' . mysql_error());
$sql = 'SELECT id FROM users WHERE email=\"donat12#icloud.com\"';
echo $sql;
?>
There are some issue with the code. First you forgot to close the if condition over here
if (!$conn) {
And then you forgot to execute the sql query
the complete code would be like
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'id1381007_accounts';
$conn = new mysqli($host,$user,$pass,$db) or die($mysqli->error);
if (!$conn) {
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT id FROM users WHERE email=\"donat12#icloud.com\"';
if ($result = $conn->query($sql)) {
while ( $row = $result->fetch_assoc()) {
$data[] = $row;
}
echo "<pre>";
print_r($data);
echo "</pre>";
}
$conn->close();
?>
There are two errors
You are missing } closing bracket after die
Mysql query is wrong.
So the code should be
if (!$conn) {
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT id FROM users WHERE email="donat12#icloud.com"';
echo $sql;

How to save a variables value out of the loop in PHP?

<?php
//connecting to the database
define('DB_HOST', 'localhost');
define('DB_NAME', 'visitor_list');
define('DB_USER','root');
define('DB_PASSWORD','');
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error()); $db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " .
mysql_error()); //inserting Record to the database
$dat1 = date("d");
$moth1 = date("m");
$year1 = date("Y");
$sql2 = 'SELECT * FROM list1 ORDER BY card_no DESC LIMIT 1;';
$retval = mysql_query($con,$sql2 );
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
/*echo "{$row['card_no']}";*/
$in= $row['card_no'];
$in++;
}
$ap_ty = $_POST['ap_ty'];
$per = $_POST['per'];
$no_vis = $_POST['no_vis'];
$nm_vis = $_POST['nm_vis'];
$co_nm = $_POST['co_nm'];
$ad = $_POST['ad'];
$po = $_POST['po'];
$ty_vis = $_POST['ty_vis'];
$met_nm = $_POST['met_nm'];
$dep = $_POST['dep'];
$des = $_POST['des'];
$por_met = $_POST['por_met'];
$vad = $_POST['vad'];
if(!isset($_POST['submit'])){
$query = "INSERT INTO list1 (card_no,d1,m1,y1,app_ty,no_per,area_vis,nm,com_nm,add1,pho,ty1_vis,met_with,depart,desi,pur_meet,vad_up) VALUES ('$in','$dat1','$moth1','$year1','$ap_ty','$per','$no_vis','$nm_vis','$co_nm','$ad','$po','$ty_vis','$met_nm','$dep','$des','$por_met','$vad')";}
$result = mysql_query($query);
if($result)
{
echo '<script type="text/javascript">
alert("Your Deatils has been Submitted");
</script> ';
header('location:index.php');
}
else
{ die('Error: '.mysql_error($con)); }
mysql_close($con);
?>
I want to save the $in variables value in the query but not able to save it. At time of insertion it saves the value 0 not the actual value.
<input type="text" class="form-control" name="vis_id" value=" <?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT * FROM list1 ORDER BY card_no DESC LIMIT 1;';
mysql_select_db('visitor_list');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
/*echo "{$row['card_no']}";*/
$in= $row['card_no'];
$in+
$test = $in;
}
mysql_close($conn);
?>" disabled>
this is the actual code
in this input box the value is incrementing
help me save the value of this input box into another file which is database file.

How to show table from MySQL database using php and html

I am trying to connect my html page with MySQL database to show data from one specific table to my page, but I always get an error actually it just goes to die part of an SQL code. I am really new to PHP programming so please can someone help me, what am I doing wrong?
Here is my code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>AJDE</title>
</head>
<?php
$servername = "localhost";
$username = "******";
$password = "*****";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$query = "select * from PERCENTILE";
$result = mysqli_query($conn,$query);
if(!$result) {
die ("Umro!");
}
/* close connection */
$mysqli->close();
?>
<body>
</body>
</html>
Thank you!
Do you want to show the table as a HTML table or just an array?
The following is what I did to display my table as a HTML table:
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '*****';
$dbname = 'dbname';
$selectedTable = 'whateverTableYouWant';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname);
if (!$conn){
die('cannot connect to mysql');
}
$query = "SELECT * FROM $selectedTable";
if ($result = mysqli_query($conn , $query)) {
echo("<div class = 'data_wrapper'>");
// Display Header of the table
$fieldcount=mysqli_num_fields($result); //value = number of columns
$row = mysqli_fetch_assoc($result); //Fetch a result row as an associative array:
//array to string conversion
echo("<table id='example' class='table table-striped table-bordered' cellspacing='0' width='100%'>");
echo("<thead> <tr>");
foreach($row as $item){
echo "<th>" .$item. "</th>";
}
echo("</tr> </thead>");
//Footer
echo("<tfoot> <tr>");
foreach($row as $item){
echo "<th>" .$item. "</th>";
}
echo("</tr> </tfoot>");
//Display Data within the table
echo("<tbody>");
while ($row = mysqli_fetch_assoc($result)){
echo "<tr>";
foreach ($row as $item){
echo "<td contenteditable = 'true'>" . $item . "</td>"; //Change contenteditable later
//Editable data should be constricted, int = numbers only, string = words, date = date
}
echo "</tr>";
}
echo("<tbody>");
echo "</table>";
echo("</div>");
}
The following is just displaying as an array:
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '*****';
$dbname = 'dbname';
$selectedTable = 'whateverTableYouWant';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname);
if (!$conn){
die('cannot connect to mysql');
}
$query = "SELECT * FROM $selectedTable";
if ($result = mysqli_query($conn , $query)) {
while ($row = mysqli_fetch_array($result)){
print_r($row);
}
}
Please change the connection string like mentioned below.
<?php
$con = mysqli_connect("localhost","username","password","dbname");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
Please let me know if you've any queries.
I Think you need to select a database where you will run the query:
Try with this code:
<?php
$username = "your_name";
$password = "your_password";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
//select a database to work with (so replace the database name examples)
$selected = mysql_select_db("examples",$dbhandle)
or die("Could not select examples");
//execute the SQL query and return records
$result = mysql_query("SELECT * FROM PERCENTILE");
//fetch the data from the database and display results
//replace id,name,year with the columns you have on your table PERCENTILE and you want to show
while ($row = mysql_fetch_array($result)) {
echo "ID:".$row{'id'}." Name:".$row{'name'}."Year: ". $row{'year'}."<br>";
}
//close the connection
mysql_close($dbhandle);
?>
Hope it helps,
Vince.

dropdown to show table in DB

I am working on the following code where the user chooses a table from a dropdown. On change, it displays the table but at the moment it is echoing some of the code to screen.
<?php
$dbh = "localhost";
$dbn = "dbname";
$dbu = "dbuser";
$dbp = "dbpassword";
$conn = mysql_connect($dbh,$dbu,$dbp) or die("Unable to connect do database.");
mysql_select_db($dbn, $conn) or die("Unable to select database.");
$result = mysql_query("SHOW TABLES FROM $dbn") or die("Cannot list table names.");
echo "
<form name=\"table_browser\" action=\"".$PHP_SELF."\" method=\"GET\" >
<select name=\"t\" onChange=\"javascript:submit();\">
<option>Select a table</option>
";
while ($row = mysql_fetch_row($result)){
echo " <option value=".$row[0].">".$row[0]."</option>\n";
}
echo " </select>
</form>\n";
if (!isset($t)){
die("Please select a table");
}
?>
You need to use full php code here
<?php
?>

php query result in html option

Why do I get a white row and not the value?
<select name="select">
<?php
$connessione = mysql_connect('localhost' , 'root', '') or die("Impossibile connettersi: " .mysql_error());
mysql_select_db("musica",$connessione);
$query = mysql_query("SELECT * FROM artisti_preferiti");
while($row = mysql_fetch_array($query))
{
?><option value="<?php echo $row['nome']; ?>"> <?php echo $row['cognome'];?></option>
<?php }?>
</select>
I suspect this being a DB connection issue, where I successfully tested this.
Consider the following:
Sidenote: Make sure that your settings are correct, including the DB name, and colum names.
DB connection file: (db_connect.php)
<?php
$mysql_hostname = 'xxx';
$mysql_username = 'xxx';
$mysql_password = 'xxx';
$mysqli = mysql_connect("$mysql_hostname", "$mysql_username", "$mysql_password");
if($mysqli->connect_errno > 0) {
die('Connection failed [' . $mysqli->connect_error . ']');
}
?>
PHP (example.php)
<select name="select">
<?php
include 'db_connect.php';
mysql_select_db("musica",$mysqli);
$query = mysql_query("SELECT * FROM artisti_preferiti",$mysqli);
while($row = mysql_fetch_array($query))
{
?><option value="<?php echo $row['nome']; ?>"> <?php echo $row['cognome'];?></option>
<?php }?>
</select>
On a final note, mysql_* functions are deprecated. Do consider using mysqli_* with prepared statements or PDO.
EDIT
MySQLi_* version
Sidenote: It is best using column names instead of SELECT * --- i.e.: SELECT nome, cognome
DB connection file: (db_connect_mysqli.php)
<?php
$mysql_hostname = 'xxx';
$mysql_username = 'xxx';
$mysql_password = 'xxx';
$mysql_dbname = 'xxx';
$mysqli = new mysqli("$mysql_hostname", "$mysql_username", "$mysql_password","$mysql_dbname");
if($mysqli->connect_errno > 0) {
die('Connection failed [' . $mysqli->connect_error . ']');
}
?>
PHP (example_mysqli.php)
<select name="select">
<?php
include 'db_connect_mysqli.php';
$query = $mysqli->query("SELECT * FROM artisti_preferiti");
while($row = mysqli_fetch_array($query))
{
?><option value="<?php echo $row['nome']; ?>"> <?php echo $row['cognome'];?></option>
<?php }?>
</select>
I changed your script so that we can debug
<?php
$lnk = mysql_connect('localhost' , 'root', '') or die("Impossibile connettersi: " .mysql_error());
mysql_select_db("musica",$lnk);
$q = 'SELECT nome,cognome FROM artisti_preferiti';
$result = mysql_query($q,$lnk);
$numRows = mysql_num_rows($result);
$rows = array();
while($row = mysql_fetch_array($result)) $rows[$row['nome']] = $row['cognome'];
/* show us this!! */
print_r($rows);
?>
<select name="select"><?php
foreach ($rows as $nome => $cognome) {
echo "<option value='$nome'>$cognome</option>";
}
?></select>

Categories