I would like to save variable from database to <option>.
PHP code:
<?php
$query = $db->prepare("SELECT * FROM classes");
$query->execute();
$result = $query->fetchAll();
?>
<script>var select_class = document.getElementById('select_class');</script>";
<?php
foreach ($result as $to_result)
{
?>
<script>
var option = document.createElement('option');
option.value = "<?php echo($to_result['name']); ?>";
select_class.appendChild(option);
</script>
<?php
}
?>
HTML code:
<select id="select_class"></select>
Database:
ID_class[1] = something
...
ID_class[12] = something
TypeError: select_class is null
But why? I dont know what is my problem.
There were several mistakes in you code. For example, you reopened a script tag while the old one wasn't even closed.
Besides that, I don't think that the javascript was needed in this code. I've simplified it for you:
<select id="select_class">
<?php
$query = $db->prepare("SELECT * FROM classes");
$query->execute();
$result = $query->fetchAll();
foreach ($result as $to_result)
{
?>
<option value="<?php echo $to_result['name']; ?>">
<?php echo $to_result['name']; ?>
</option>
<?php
}
?>
</select>
Related
So I'm trying my hand at creating php methods from scratch. My classes aren't exactly classes yet, I'm still working on that. Anyway, my issue's I can't seem to get the values I expect from my database. Here's a snippet of my code:
file1.php
<?php function dbConnect() {
$connection = mysqli_connect("localhost", "music_root", "", "music");
if($connection->connect_error) {
return null;
}
return $connection;}
function getCategory() {
$cn = dbConnect();
if($cn == null) {
echo "Failed to connect to database.";
} else {
$fetchQuery = mysqli_query($cn, "SELECT * FROM tbl1 ORDER BY 'Name'") or die(mysqli_error($cn));
if(mysqli_num_rows($fetchQuery) > 0) {
while($item = mysqli_fetch_array($fetchQuery)) {
return $item["Name"];
}
}
}} ?>
Here's the snippet of how I call the above method in file2.php
<?php ini_set("display_errors", 1);
include_once("file1.php");
$con = dbConnect();
$updateStat = false; ?>
<div>
<label>Genre</label>
<select id="genre" name="genre" value="Please select genre">
<option value="<?php $con->getCategory() ?>"></option>
</select>
</div>
I've tried printing a message at the start of the method to see if the it's being called but the message did not print either so I was wondering, what am I possibly missing here?
I think you have serveral mistakes in your code ... i guess, you don't use OOP (classes) so i modfiy a example which should work .. .if not, please post error messages
file1.php
function getCategory($cn) {
$out = array();
if($cn == null) {
echo "Failed to connect to database.";
} else {
$fetchQuery = mysqli_query($cn, "SELECT * FROM tbl1 ORDER BY 'Name'") or die(mysqli_error($cn));
if(mysqli_num_rows($fetchQuery) > 0) {
while($item = mysqli_fetch_array($fetchQuery)) {
$out[] = $item["Name"];
}
}
return $out;
}
}
fil2.php
<?php
ini_set("display_errors", 1);
require_once("file1.php");
$con = dbConnect();
$updateStat = false;
$res = getCategory($con);
?>
<div>
<label>Genre</label>
<select id="genre" name="genre" value="Please select genre">
<?php
foreach($res as $cat):
?>
<option value="<?php echo $cat ?>"><?php echo $cat ?></option>
<?php endforeach;?>
</select>
How to fix conflict in foreach mysql PDO
I Try use other looping function but no give result, like while.this my script
the mysql PDO query, like this:
<?php
function calldata($table){
$db = dbConn::getConnection();
$sql = "select * from ".$table."" or die(mysql_error());
$q = $db->query($sql) or die("failed!");
while($res = $q->fetch(PDO::FETCH_ASSOC)){
$record = array_map('stripslashes', $res);
$db->records[] = $record;
}
return $db->records;;
//else echo "No records found";
}
?>
and to display the result, like this:
<table>
<tr><td>Category</td><td>
<select>
<option value="0">- select -</option>
<?php
try{
$db = dbConn::getConnection();
$table='str_prod_category';
$recordscat = calldata($table);
if(count($recordscat)){
foreach($recordscat as $key1=>$Recordcat){
?>
<option value="<?=$Recordcat['id_category'];?>"><?=$Recordcat['cat_name'];?></option>
<?php }}}catch (PDOException $e) {
//Output error - would normally log this to error file rather than output to user.
echo "Connection Error " . $e->getMessage();
} ?>
</select>
</td></tr>
<tr><td>Brand</td><td>
<select>
<option value="0">- Select -</option>
<?php try{
$db = dbConn::getConnection();
$table1='str_prod_brand';
$recordsbrand = calldata($table1);
if(count($recordsbrand)){
foreach($recordsbrand as $key2=>$Recordbrand){
?>
<option value="<?=$Recordbrand['id_brand'];?>"><?=$Recordbrand['brand_name'];?></option>
<?php }}}catch (PDOException $e) {
//Output error - would normally log this to error file rather than output to user.
echo "Connection Error " . $e->getMessage();
} ?>
</select>
</td></tr>
</table>
this code is work and dislpay the data but for the option select brand, There is an empty selection, and then the right data after the empty data.
how to fix this?i have tried change the loop from foreach to while but no give result.
thanks
i try to use fillter using if and it's work to remove the blank recode
foreach($recordsbrand as $key2=>$Recordbrand){
if($Recordbrand['brand_name'] == ''){}else{
<option value="<?=$Recordbrand['id_brand'];?>"><?=$Recordbrand['brand_name'];?></option>
}}
but, i don't know is good or bad.
This is my simple php html code.
<select id="district" name="district">
<option value="">Select district</option>
<?php
$sql="SELECT * FROM district";
$result = mysqli_query($sql);
while($row = mysqli_fetch_array($result))
{
$district_id = $row['district_id'] ;
$district_name = $row['district_name'];
?>
<option value="<?php echo $district_id;?>"><?php echo $district_name;?></option>
<?php
}
?>
</select>
But it's not working. database is autoloaded.What will be the problem.
you are using direct query not with CI db instance so you will not getting db connection try in CI way
$sql ="SELECT * FROM district";
$query = $this->db->query($sql);
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {?>
<option value="<?php echo $row->district_id;?>"><?php echo $row->district_name;?></option>
<?php }
}
or
$this->db->from('district');
$query = $this->db->get();
if($query->num_rows > 0 ) {
foreach ($query->result() as $row) {
// do your stuff
}
}
Better method to work with MVC framework:- use model for db queries and return data on view via controller (do not use direct query on view)
May be your get CI instance wirte you CI query directly
$CI =& get_instance();
$CI->load->model('modelname');
$result = $CI->modelname->functionname();
If you must access db directly from, view try this:
$this->load->view('view_name',["db"=>$this->db,"other_data=>"data"]);
//$this->db //CI db instance
In view you can now do:
$db->query("select * from table")->result();
please try this
<select id="district" name="district">
<option value="">Select district</option>
$result = mysqli_query($sql);
while($row = $result->fetch_array())
{
$district_id = $row['district_id'] ;
$district_name = $row['district_name'];
?>
<option value="<?php echo $district_id;?>"><?php echo $district_name;?></option>
<?php } ?>
To begin with, I'm having this small PDO snippet of code which gets me all available databases on the server and another function for the tables:
I need whenever I select and submit an option from the db list to display its corresponding tables in the select menu below. I managed to display the databases with a foreach but I kinda miss the point why this doesn't work.
Thanks in advance for any answers/solutions :)
see below for a revision to your code in order to achieve what you're looking for.
<form method='post' action="<?php $_SERVER['PHP_SELF']; ?>">
<?php
define('PDO_USER', 'root');
define('PDO_PASS', '');
function getDatabases(PDO $pdo) {
$stmt = $pdo->query('SHOW DATABASES');
$result = $stmt->fetchAll();
$dbs = array();
foreach($result as $row) {
$dbs[] = $row['Database'];
}
return $dbs;
}
$pdo = new PDO('mysql:host=localhost', PDO_USER, PDO_PASS);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$databases = getDatabases($pdo);
// Table code
$selectedDB = (!empty($_POST['database'])) ? $_POST['database'] : null;
function getTables(PDO $pdo, $databaseName) {
if(!in_array($databaseName, getDatabases($pdo))) {
return array();
}
$stmt = $pdo->query('SHOW TABLES FROM '.$databaseName);
$result = $stmt->fetchAll();
$tables = array();
foreach($result as $row) {
$tables[] = $row['Tables_in_'.$databaseName];
}
return $tables;
}
$tables = array();
if(!empty($selectedDB)) {
$tables = getTables($pdo, $selectedDB);
}
?>
Database:
<select name='database'>
<?php foreach($databases as $row): ?>
<option value="<?php echo $row; ?>"><?php echo $row; ?></option>
<?php endforeach; ?>
</select>
<input type='submit' name='formSubmit' value='Submit'></form>
UPDATE
<select name='formTable1'>
<?php foreach($tables as $tbName): ?>
<option value='<?php echo $tbName; ?>'><?php echo $tbName; ?></option>
<?php endforeach; ?>
</select>
A couple of notes:
You need to include the "action" attribute in the form tag in order to give the form a target URL for submission.
In your original select you had 2 name attributes
(name='formDatabases[]' name='database'). You should only have one
name per form element, which is what is determined to be used as the
key in the $_POST array for that particular field.
You should only use "name='var[]'" format in the HTML, if you expect
that particular POST item to be an array in PHP. Otherwise you can
just use "name='var'"
This may be out of the scope of your original question, but you may
want to consider separating your database business logic into a separate
class, to keep your HTML clean. For now at least, I updated the code to have
the logic at the top of the file so that in can be extracted into a
class more easily in the future. This avoids the perilous path into PHP Spaghetti string code!
Hello and Good Morning,
I am still learning PHP and for some reason my script will not post any data in my foreach loop. Any Idea why? The emailRow Echos out fine but I am going to remove My code is below:
<?php
include 'includes/header.php';
$accountUser = array();
$upgradeEmail = $_GET['currEmail'];
$emailQuery = "SELECT fbID, firstName, lastName FROM users WHERE emailOne='".$upgradeEmail."' AND authLevel=0";
<?php echo $emailRow['fbID']; ?>
<?php echo $emailRow['firstName']; ?>
<?php echo $emailRow['lastName']; ?>
while($emailRow = mysql_fetch_assoc($emailQuery, $conn))
{
$accountUser[]=$emailRow;
}
?>
<table>
<?php foreach($accountUser as $emailData) { ?>
<tr><td> <?php emailData['fbID']; ?> </td><td><?php emailData['firstName']; ?></td><td><?php emailData['lastName']; ?></td></tr>
<?php } ?>
</table>
You have constructed your SQL query in $emailQuery, but never executed it. Call mysql_query(), and pass its result resource to mysql_fetch_assoc().
$emailQuery = "SELECT fbID, firstName, lastName FROM users WHERE emailOne='".$upgradeEmail."' AND authLevel=0";
$result = mysql_query($emailQuery);
if ($result)
{
while($emailRow = mysql_fetch_assoc($result, $conn))
{
$accountUser[]=$emailRow;
}
}
else // your query failed
{
// handle the failure
}
Please also be sure to protect your database from SQL injection by calling mysql_real_escape_string() on $upgradeEmail since you're receiving it from $_GET.
$upgradeEmail = mysql_real_escape_string($_GET['currEmail']);
You don't actually echo anything.
as well as not running the query.
and there are some other methods to do things, much cleaner than usual uglyPHP.
a function
function sqlArr($sql){
$ret = array();
$res = mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
if ($res) {
while($row = mysql_fetch_array($res)){
$ret[] = $row;
}
}
return $ret;
}
a code
$email = mysql_real_escape_string($_GET['currEmail']);
$data = sqlArr("SELECT * FROM users WHERE emailOne='$email' AND authLevel=0");
include 'template.php';
a template
<? include 'includes/header.php' ?>
<table>
<? foreach($data as $row) { ?>
<tr>
<td><?=$row['fbID']?></td>
<td><?=$row['firstName']?></td>
<td><?=$row['lastName']?></td>
</tr>
<? } ?>
</table>
YOU HAVE A SYNTAX ERROR. You can't open a new php tag within an existing php tag. You have to close the already open tag first.
As far as getting the query to work,
First you have to fetch data before printing it or echoing it...
while($emailRow = mysql_fetch_assoc($emailQuery, $conn))
{
$accountUser[]=$emailRow;
}
then you may write statements..
echo $emailRow['fbID']; etc. code.
Secondly you have not fired a query, just written the query statement. Use mysql_query to fire it.
Your code would be something like this..
<?php include 'includes/header.php';
$accountUser = array();
$upgradeEmail = $_GET['currEmail'];
$emailQuery = mysql_query("SELECT fbID, firstName, lastName FROM users WHERE emailOne='".$upgradeEmail."' AND authLevel=0") or die (mysql_error());
while($emailRow = mysql_fetch_assoc($emailQuery, $conn))
{
$accountUser[]=$emailRow;
}
echo $emailRow['fbID'];
echo $emailRow['firstName'];
echo $emailRow['lastName'];
print '<table>';
foreach($accountUser as $emailData) {
print '<tr><td>'$.emailData['fbID'].'</td><td>'.$emailData['firstName'].'</td><td>'.$emailData['lastName'].'</td></tr>';
}
print '</table';
?>
Feel free to use this code, modifying it to fit your needs.