mysql - Give argument php function to show database results in another file -
hello gays have php code connect database works fine.
$servername = "localhost"; $username = "root"; $password = ""; $dbname = "cv"; // create connection $conn = new mysqli($servername, $username, $password, $dbname); mysqli_set_charset($conn,"utf8"); // check connection if ($conn->connect_error) { die("connection failed: " . $conn->connect_error); } $sql = "select * services"; $result = $conn->query($sql); if ($result->num_rows > 0) { // output data of each row while($row = $result->fetch_assoc()) { echo "id: " . $row["id"]. " - name: " . $row["service_name"]. " " . $row["service_desc"]. "<br>"; } } else { echo "0 results"; } $conn->close();
my question is: how create function getservices() , give argument show results in php file using foreach or while, this:
<?php foreach ($results $key=>$result) : ?> <?php echo $result['service_name']; ?> <?php endforeach; ?>
okay. have following things:
db.php :
$servername = "localhost"; $username = "root"; $password = ""; $dbname = "cv"; // create connection $conn = new mysqli($servername, $username, $password, $dbname); mysqli_set_charset($conn,"utf8"); // check connection if ($conn->connect_error) { die("connection failed: " . $conn->connect_error); } function yourfunctionname() { $sql = "select * services"; $result = $conn->query($sql); return $result; } $conn->close();
otherfile.php :
<?php include 'db.php'; $data = yourfunctionname(); if ($data->num_rows > 0) { // output data of each row while($row = $data->fetch_assoc()) { echo "id: " . $row["id"]. " - name: " . $row["service_name"]. " " . $row["service_desc"]. "<br>"; } } else { echo "0 results"; } ?>
hope works, haven't tested yet.
Comments
Post a Comment