am trying change project mysql mysqli. have db connection as:
$link = mysqli_connect($hostname, $username, $password, $database); if(mysqli_connect_errno()) { echo "opps! connection not established: ", mysqli_connect_error(); exit(); } then have user defined function as:
function get_name($id) { $query = mysqli_query($link, "select name staff id='$id'"); $result = mysqli_fetch_assoc($query); return $data = $result['name']; } i understand have declare $link global (as shown below) work fine.
function get_name($id) { global $link; $query = mysqli_query($link, "select name staff id='$id'"); $result = mysqli_fetch_assoc($query); return $data = $result['name']; } my question here is: practice , safe?
i wouldn't call or bad practice write function such specific purpose, fits needs. if plan exact task in multiple places throughout code, function useful make code easier read , avoid repeating yourself.
as far safety goes, need sanitize inputs before using them in query. case of integer $id field, cast integer $id = (int)$id;. other data types, want escape using $id = mysqli_real_escape_string($link, $id);. you'll safe.
i advise pdo instead of mysqli. believe it's more commonly used these days.
Comments
Post a Comment