I have this code which bring a single post from my database depend on id
global $connect;
$id = $_GET['id'];
$sql_query="SELECT * FROM `topics` WHERE id = {$id}";
$result = mysqli_query($connect,$sql_query);
while ($row = mysqli_fetch_assoc($result)) { ....}
How can i make this as function (My try) :
Function get_single_post($id) {
global $connect;
$id = (int)$id;
$sql_query="SELECT * FROM `topics` WHERE id = {$id}";
$result = mysqli_query($connect,$sql_query);
while ($row = mysqli_fetch_assoc($result)) {
$post[] = $row;
}
return $post;
}
to use this function i use this :
get_single_post($_GET['id']);
and when i call something i use : $post['title'];
for title as ex
If your id
is primary key than you don't need while loop as it will return only one result
modified function
Function get_single_post($id) {
global $connect;
$id = (int)$id;
$sql_query="SELECT * FROM `topics` WHERE id = {$id}";
$result = mysqli_query($connect,$sql_query);
return mysqli_fetch_assoc($result);
}
Remember, a function returns a value, but that value must be assigned to a variable for you to be able to access it.
$post = get_single_post($_GET['id]);
Using the above should now allow you to access the post as you expect.