1

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.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Ashish Garg
  • 11
  • 1
  • 6

2 Answers2

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>';
    }

}
Osama Jetawe
  • 2,697
  • 6
  • 24
  • 40
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) {
Pupil
  • 23,834
  • 6
  • 44
  • 66