V
V
Vitaly Slyusar2015-11-05 15:54:55
PHP
Vitaly Slyusar, 2015-11-05 15:54:55

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

and so everything works
$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));

mistake
Warning: mysqli_query() expects parameter 1 to be mysqli, null given

Is it possible to put requests into a function at all and how to do it correctly?
Thank you in advance.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alex Safonov, 2015-11-05
@slusarvitaliy

In your function,
$con is a variable that is not in scope. Its function is not known.
Try

function selected($db_name){
  global $con;
...
}

But in general, I must say that no one has written like this for a long time. Wrap $con in at least a singleton. To be sure that no one will rewrite this variable in the runtime code.

M
Max, 2015-11-05
@MaxDukov

$result = mysqli_query($con, $query); - Local variables are used in the function. $con appears BEFORE the function call.
and so no problem

A
Alexey S., 2015-11-05
@Winsik

your variables inside the function are not visible
Well and accordingly:selected($con,'users');

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question