First of all I don't know php and I certainly don't know sql or how wordpress interacts with it, but I have to use php etc so here I am. So please try to explain things clearly and simply.
I have added three values to my sql wordpress tables. Two values share the same room_id (1) and the third has a value of (2). They each have a different start and end date in the table. I am trying to loop through each room_id first, checking the dates, before moving to the next room. I have more code with this function but essentially my problem is that I only seem to be printing out the first value of the array with each iteration. Here is the code:
<?php
/*Plugin Name: HotelMania Functions*/
function checkRoom() {
global $wpdb;
$query = "SELECT * FROM hm_booking ORDER BY room_id DESC";
$rooms = $wpdb->get_results($query);
foreach ($rooms as $room) {
$test= $wpdb->get_var("SELECT room_id FROM hm_booking");
echo $test;
}
}
add_shortcode('TEST', 'checkRoom');
?>
When I try to test the value either using room_id or start_date I keep getting hte first value in the table. But I think my sql is right because it is working in the database. Please can someone help I have read around and can't seem to figure out what I am doing wrong.
Thanks in advance.
Once you got $rooms
from get_results
, you don't need to run another query with get_var
.
For example, to get the room_id
and place it into $test
, instead of
$test= $wpdb->get_var("SELECT room_id FROM hm_booking");
do
$test = $room->room_id;
The SQL statement you're using "SELECT room_id FROM hm_booking"
along with get_var()
will return the same value no matter what. The codex mentions that:
The get_var function returns a single variable from the database.
Assuming the hm_booking
table contains multiple rows, then the SQL statement you're running will return multiple rows of just the room_id
column in your table, and the get_var()
function will only return the first row of the room_id
column.
Also, consider taking advantage of get_results()
. Your first SQL query may already be storing everything you need. The $rooms
variable is an object containing all the rows and columns from your SELECT
query:
$query = "SELECT * FROM hm_booking ORDER BY room_id DESC";
$rooms = $wpdb->get_results($query);
foreach ($rooms as $room) {
echo 'Room ID:' . $room->room_id; // $room object represents a single row
}