How to make a feature?

Working code: (taken from here)
<?php
include_once 'config.php';

$mysqli = new mysqli("$host", "$user" "$pass" "$dbname");
/* check connection */
if ($mysqli->connect_errno) {
 printf("failed to connect: %s\n", $mysqli->connect_error);
exit();
}

$query = "SELECT * FROM mytable";

if ($result = $mysqli->query($query)) {

 /* fetch object array */
 while ($obj = $result->fetch_object()) {
 echo "$obj->id. $obj->name <br>";
}

 /* free result set */
$result->close();
}

/* close connection */
$mysqli->close();
?>


Trying to make this into a function:

<?php
include_once 'config.php';

$mysqli = new mysqli("$host", "$user" "$pass" "$dbname");
/* check connection */
if ($mysqli->connect_errno) {
 printf("failed to connect: %s\n", $mysqli->connect_error);
exit();
}

function GetName($id, $mysqli) {

$query = "SELECT * FROM mytable";

if ($result = $mysqli->query($query)) {

 /* fetch object array */
 while ($obj = $result->fetch_object()) {
 return "$obj->name";
}

 /* free result set */
$result->close();
}
}

echo GetName(2, $mysql);

/* close connection */
$mysqli->close();
?>


It turns out the mistake.
Where looked?
March 20th 20 at 11:47
2 answers
March 20th 20 at 11:49
Solution
$mysqli = new mysqli("$host", "$user" "$pass" "$dbname");
...
echo GetName(2, $mysql);
well, as always :)
thank you very much - orlando commented on March 20th 20 at 11:52
@mitchel97, and if they were included the error output, it would not have to shame - Matilde78 commented on March 20th 20 at 11:55
March 20th 20 at 11:51
Mysqli variable is not visible in a function, make it global.
function GetName($id, $mysqli) {
global $mysqli;
// code...
}
He's got the variable $mysqli is passed to the function as an argument, do not advise anyone of such, and do not use) - aidan.Hil commented on March 20th 20 at 11:54
@yolanda_Tillman29, and how best to proceed? to tell you how I or is there better ways? - orlando commented on March 20th 20 at 11:57

Find more questions by tags PHPMySQL