I want to print a select list on my webpage using Mysqli select query. I have checked a lot of questions there, but i am failed to find my problem. Pls help.
php
<select name="bcat" id="bcat" required="required" class="search-field">
<option value="" selected="selected" disabled="disabled">Select a Category</option>
<?php getTierOne(); ?>
</select>
getTierOne()
function getTierOne()
{
$result = mysqli_query($mysqli,"SELECT bcat FROM advertise");
while($tier = mysqli_fetch_assoc($result))
{
echo '<option value="' .$tier['bcat'] . '">' . $tier['bcat'] . '</option>';
}
}
db.php
$mysqli = new mysqli('localhost', 'root', '', 'lwv');
if($mysqli->connect_errno > 0){
die('Unable to connect to database [' . $mysqli->connect_error . ']');
}
It is working absolutely fine with sql query and syntax but not working with mysqli query. I don't have knowledge about mysqli queries so please help me out. Thanks in advance.
答案 0 :(得分:1)
you have to pass $mysqli
to the finction
try this
$mysqli = new mysqli('localhost', 'root', '', 'lwv');
if($mysqli->connect_errno > 0){
die('Unable to connect to database [' . $mysqli->connect_error . ']');
}
?>
<select name="bcat" id="bcat" required="required" class="search-field">
<option value="" selected="selected" disabled="disabled">Select a Category</option>
<?php getTierOne($mysqli); ?>
</select>
<?php
function getTierOne($mysqli)
{
$result = mysqli_query($mysqli,"SELECT bcat FROM advertise");
while($tier = mysqli_fetch_assoc($result))
{
echo '<option value="' .$tier['bcat'] . '">' . $tier['bcat'] . '</option>';
}
}
答案 1 :(得分:0)
You are not getting variable $mysqli
inside the function.
Make this variable global
.
Change
function getTierOne() {
to
function getTierOne() {
global $mysqli;
Or, else pass database connection as parameter:
function getTierOne($mysqli = NULL) {