Answer the question
In order to leave comments, you need to log in
How to place a Mysql database query inside a function in PHP?
I want to execute a query inside a function and display the result, how to arrange it correctly?
let's say there is already a connection to the database and I want to make a request to a particular database:
this gives an error
<?php
$con = mysqli_connect("localhost","root","","mybd");
mysqli_set_charset($con,"utf8");
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
function selected($db_name){
$query = "select * from $db_name";
$result = mysqli_query($con, $query);
$row = mysqli_fetch_array($result);
do
{
echo $row['name']."<br>";
}while($row = mysqli_fetch_array($result));
}
selected('users');
$query = "select * from users";
$result = mysqli_query($con, $query);
$row = mysqli_fetch_array($result);
do
{
echo $row['name']."<br>";
}while($row = mysqli_fetch_array($result));
Warning: mysqli_query() expects parameter 1 to be mysqli, null given
Answer the question
In order to leave comments, you need to log in
In your function,
$con is a variable that is not in scope. Its function is not known.
Try
function selected($db_name){
global $con;
...
}
$result = mysqli_query($con, $query); - Local variables are used in the function. $con appears BEFORE the function call.
and so no problem
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question