php - Using prepared statements in functions -


hi i'm trying use prepared statements within functions. have following function supposed return details of country in db based on inputting id of country - use array company name after. don't know how output data used in array function when use prepared statements. know i'm missing basic. please see below.

function findcountryname($countryid){ include 'connect.php';  $stmt = $conn->prepare("select * countries id=? ,  pic!='null'"); $stmt->bind_param("i", $countryid); $stmt->execute(); } 

the 'connect.php' file consists of following:

<?php   global $conn, $dbname, $username,$servername, $password; $servername = "localhost"; $username = "root"; $password = ""; $dbname = "country"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("connection failed: " . $conn->connect_error); } ?> 

this original function:

function findcountryname($countryid){ $result = mysql_query("select * `countries` `id`=' $countryid '     , `pic` != 'nothing' "); return $result; } 

there no reason use globals or include inside function. if insist on procedural code, should inject mysqli object function argument.

after statement execution, need retrieve mysqli result object manipulation. if you're getting first row, below example work. if expect multiple rows, have call fetch_assoc in loop retrieve 1 row @ time.

function findcountryname($countryid, mysqli $conn) {      $stmt = $conn->prepare("select * countries id=? , pic!='null'");     $stmt->bind_param("i", $countryid);     $stmt->execute();     // mysqli result object     $result = $stmt->get_result();     // return first row of data in associative array     $data = $result->fetch_assoc()     return $data;  } 

Comments