This is my first time try to use object oriented programming. I'm trying to repeat the timeslot from the database but I'm only getting one result.
timeslot table contains:
10:00:00
10:15:00
10:30:00
in PHP class:
class booking {
function __construct($mysqli) {
}
function get_timeslot() {
global $mysqli;
$q = $mysqli->query("SELECT id_timeslot, times FROM timeslot");
while($r = $q->fetch_array(MYSQLI_ASSOC)) :
return $r['times'];
endwhile;
$mysqli->close();
}
}
in the webpage to showing the looping times:
$booking = new booking($mysqli);
<?php echo $booking->get_timeslot(); ?>
result:
10:00:00
return is returning the value for your function, thus you'll only receive 1 value returned. Try
echo $r['times'].'<br/>';
or
function get_timeslot(){
global $mysqli;
$q = $mysqli->query("SELECT id_timeslot, times FROM timeslot");
$timeSlots = array();
while($r = $q->fetch_array(MYSQLI_ASSOC))
{
$timeSlots[] = $r['times'];
}
$mysqli->close();
return $timeSlots;
}
the return statement stops the while loop from continuing any further, and exits the function. You'll either need to modify the function to return an array of time slots, or modify your logic to expect only the first result from the database.
The return statement will exit the function immediately it's called. Instead return you should add the item to array than return the entire array:
class booking {
function __construct($mysqli){}
function get_timeslot(){
global $mysqli;
$q = $mysqli->query("SELECT id_timeslot, times FROM timeslot");
while($r = $q->fetch_array(MYSQLI_ASSOC)) :
$res[] = $r['times'];
endwhile;
$mysqli->close();
return $res;
}
}
function get_timeslot() {
global $mysqli;
$q = $mysqli->query("SELECT id_timeslot, times FROM timeslot");
while($r = $q->fetch_array(MYSQLI_ASSOC)) :
// Cast to array
$t[] = $r['times'];
endwhile;
$mysqli->close();
// Return Array
return $t;
}
// Calling the function
$booking = new booking($mysqli);
// Add print_r() as the return is now in an array format
echo "<pre>".print_r($booking->get_timeslot(),true)."</pre><br />\n";
Because you are using return $r['times']; inside the loop.
This should solve your problem:
function get_timeslot(){
global $mysqli;
$returnArray = array();
$q = $mysqli->query("SELECT id_timeslot, times FROM timeslot");
while($r = $q->fetch_array(MYSQLI_ASSOC)) :
$returnArray[] = $r['times'];
endwhile;
$mysqli->close();
return $returnArray; // now that all results are fetched from DB, return array containing them
}
On other note, using global keyword inside a class method or anywhere for that matter i not advisable, since global scope enables any process to access and change global variable.
I would advise you to try using other means of accessing your DB object (object registry, protected property...)
Also using alternative syntax for while loop (while(): ... endwhile;) is not very readable, but one can debate about that.
Try this:
class booking {
function __construct($mysqli){}
function get_timeslot()
{
global $mysqli;
$q = $mysqli->query("SELECT id_timeslot, times FROM timeslot");
$return = '';
while ($r = $q->fetch_array(MYSQLI_ASSOC)) :
$return.= $r['times'] . '<br/>';
endwhile;
$mysqli->close();
return $return;
}}
Related
This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 5 years ago.
Hy I have code below,
I wanna return value array with function :
<?php
include "config/koneksi.php";
//script1
$fetch1 = mysqli_query($conn, "SELECT * FROM orders_temp");
$array = array();
while($row = mysqli_fetch_assoc($fetch1)){
$array[] = $row[id_orders_temp];
}
echo "script1: ";
print_r($array);
echo "<br>";
//script2
function cart(){
$array1= array();
$fetch2 = mysqli_query($conn,"SELECT * FROM orders_temp");
while ($r=mysqli_fetch_assoc($fetch2)) {
$array1[] = $r[id_orders_temp];
}
return $array1;
}
$cart1 = cart();
echo "script2 : ";
print_r($cart1);
?>
and the result :
script1: Array ( [0] => 150 [1] => 151 )
script2 : Array ( )
there's no problem if I print_r array without function, but
when I used function as above, I got blank array( ).
How can I get array value with function ?
The variable $conn is not defined within the function, so you need to either pass it to the function or reference the globally available $conn.
Pass in $conn
include "config/koneksi.php";
function cart($conn) {
$identifiers = array();
$result = mysqli_query($conn, 'SELECT id_orders_temp FROM orders_temp');
while ($row = mysqli_fetch_assoc($result)) {
$identifiers[] = $row['id_orders_temp'];
}
return $identifiers;
}
$cart = cart($conn);
var_dump($cart);
Reference global $conn
Ideally, you should limit global state (and accessing it), so I would not recommend this.
include "config/koneksi.php";
function cart() {
global $conn;
$identifiers = array();
$result = mysqli_query($conn, 'SELECT id_orders_temp FROM orders_temp');
while ($row = mysqli_fetch_assoc($result)) {
$identifiers[] = $row['id_orders_temp'];
}
return $identifiers;
}
$cart = cart();
var_dump($cart);
Note I have renamed variables within cart() and optimized the SQL query to select only those columns actually required.
Is the variable id_orders_temp
returning a correct value ??
and if its a column of DB then u have to
$row['id_orders_temp'];
You have to assign the array as a global array because of the scoping inside the array, so replace the first line inside the function with one below:
$array1 = global $array;
so i am learning to write functions. Now i know how to echo stuff into a foreach but i do not know how to print a single row outside a foreach (like i only have 1 row in my table and want to print the id and username out of it) how do i do this?
my function :
public function gegevens(){
$stmt = $this->conn->prepare("SELECT * FROM gegevens_locatie");
$stmt->execute();
$result = $stmt->fetchAll();
//Return result
return $result;
}
when i call that function on my other page i call it with :
require_once 'class/class.overig.php';
$overig = new OVERIG();
i have tried stuff like print_r($overig->gevens()) and with a echo but i cant seem to make it work. So how can i do this?
Because you are using ->fetchAll() you will always get an array of rows even if there is only one row returned. You also need to use the correct method name on your call.
So all you need to do is
$arr = $overig->gegevens();
if ( count($arr) == 1 ) {
echo $arr[0]['id'];
echo $arr[0]['username'];
}
if ( count($arr) > 1 ) {
foreach ( $arr as $row) {
echo $row['id'];
echo $row['username'];
}
}
"I have tried stuff like print_r($overig->gevens()) and with a echo but i cant seem to make it work. So how can i do this?"
The Name of the Method you called does NOT match the Name of the Method in your Class. In your Class, You have: gegevens() but in your Call: you specified: gevens(). Unless this is just a normal Typo; you should start your Debugging from there.
In other words; your Call should have been: print_r($overig->gegevens()).
THE CLASS:
<?php
class OVERIG{
public function gegevens(){
$stmt = $this->conn->prepare("SELECT * FROM gegevens_locatie");
$stmt->execute();
$result = $stmt->fetchAll();
//Return result
return $result;
}
}
USING THE CLASS:
<?php
require_once 'class/class.overig.php';
$overig = new OVERIG();
$result = $overig->gegevens();
// TRY DUMPING THE VARIABLE: $result:
var_dump($result);
// TO ECHO OUT SOME VALUES:
if($result){
foreach($result as $key=>$item){
if(is_string($item)){
echo $item;
}
}
}
I am trying to integrate my regular php build script into wordpress. I am stuck in a place where the function works perfectly before, but not in wordpress environment.
In the code below, I am getting blank array in my ajax request whereas I do have results inside myFunc (I have tested by putting wp_send_json inside).
Do I need to change anything to work with PHP globals in wordpress?
$final = array();
function myFunc(){
global $wpdb;
global $final;
$sql = 'SELECT .......';
$result = $wpdb->get_results($sql);
if($wpdb->num_rows > 0){
foreach ( $result as $row ) {
$final[] = $row->pdate;
}
return true;
}
return false;
}
myFunc();
wp_send_json($final);
You can use following statements to get updated value from function.
$arr = array();
function myFunc($new_arr){
global $wpdb;
$sql = 'SELECT .......';
$result = $wpdb->get_results($sql);
if($wpdb->num_rows > 0){
foreach ( $result as $row ) {
$new_arr[] = $row->pdate;
}
}
//It will return updated array if result having rows.Otherwise return empty array.
return $new_arr;
}
$final = myFunc($arr);
if(!empty($final))//if block will be execute if myFunc doesn't return empty array.
{
wp_send_json($final);
}
That should work but globals are nasty things to use and will often conflict I'd suggest just returning the array from the function.
e.g.
function myFunc(){
global $wpdb;
$final = array();
$sql = 'SELECT .......';
$result = $wpdb->get_results($sql);
if($wpdb->num_rows > 0){
foreach ( $result as $row ) {
$final[] = $row->pdate;
}
return $final;
}
return false;
}
$myFuncReturn = myFunc();
if($myFuncReturn !== false){
wp_send_json($myFuncReturn);
}
I want to use 'return' function with a while loop for my Mysql query, but it returns only one result.
I have this in my database :
id name author
1 foo fooo
2 foo2 fooo2
It returns only "2", but i want "1","2","3" ect..
Here's my code :
function get_thm_cat() {
require 'database.php';
$req = $bdd->prepare("SELECT * FROM sk_cat ORDER BY id ASC");
$req->execute();
if ($req->rowCount() > 0) {
while ($row = $req->fetch()) {
return '<ul id="ul_cat"><li id="li_cat">'.$row["id"].' Name = '.$row["name"].'<br>';
}
}
$req->closeCursor();
}
With return you stop the execution of the function, which means that when PHP iterates over your loop for the first time and reaches return, it immediately goes back to where you initially called the function. Any subsequent iterations of the while-loop are not executed and your call to $req->closeCursor(); also isn't executed when the result is more than 0 rows because of this.
The easiest way to return multiple strings after each other is to create a temporary variable that you fill up at every iteration and return after the loop, like this:
$output = '';
while ($row = $req->fetch()) {
$output .= '<ul id="ul_cat"><li id="li_cat">'.$row["id"].' Name = '.$row["name"].'<br>';
}
return $output;
return is the command to end the function and continue processing the code where it left off. You should either store the results in the while loop and return the array that holds these results, or you should echo the results in the while loop.
while ($row = $req->fetch_assoc() ) {
echo '<ul id="ul_cat"><li id="li_cat">'.$row["id"].' Name = '.$row["name"].'<br>';
}
or
$results = array();
while ($row = $req->fetch_assoc() ) {
$results[] = '<ul id="ul_cat"><li id="li_cat">'.$row["id"].' Name = '.$row["name"].'<br>';
}
return $results;
i searched all over the web or i just don't see it.
I want to do the following:
<?php
function abc(){
$sql = "SELECT * FROM table";
$result = mysql_fetch_assoc($sql);
$data = mysql_fetch_assoc($result);
}
?>
<? while(abc()) : ?>
<?=article_title()?>
<?=article_content()?>
<?=endwhile;?>
Could somebody give me a direction and/or example?
Thank you very much
PHP does not have generator/iterator functions, so you cannot do that.
You can however return an array and iterate over that array:
function abc() {
// ...
$rows = array();
while($row = mysql_fetch_assoc($result)) { $rows[] = $row; }
return $rows;
}
foreach(abc() as $row) {
// do something
}
If the functions you call need access to the row, pass it as an argument. Using global variables for it would be very bad/nasty
have you tried to do something like that?
<?php
function getData(){
//get the data from the database
//return an array where each component is an element found
}
$elems = getData();
foreach($elems as $e){
doSomethingWith($e);
}