I'm trying to run multiple queries on a MySQL server at the same time from PHP with the same database connection. I have run the SQL statement on the server itself but the response is as expected. I'm getting no SQL exceptions but just no SQL query response at all (the result is FALSE).
Is this because you can't query when another query is already active on the same connection?
The code loads data from the database table with people's names and last paid date information. This is displayed in a form and then the user can select members to update payments for. Then, the part I'm stuck on is the second query where the selected names are trying to find family_id for families.
Code snippet:
mysql_select_db($database_W3OITesting, $W3OITesting);
$yearnow = date("Y",strtotime('+1 year')).'-12-31';
$yearrecent = date("Y",strtotime('-1 year')).'-12-31';
$query_Recordset1 = "SELECT DISTINCT lname, fname, suffix, fcccall, members.member_id, MaxDateTime " .
"FROM members " .
"INNER JOIN " .
"(SELECT paid.member_id, MAX(paid.year) AS MaxDateTime " .
"FROM paid " .
"GROUP BY paid.member_id) groupedpaid ".
"ON members.member_id = groupedpaid.member_id " .
"Where (MaxDateTime < '$yearnow') AND ".
"(MaxDateTime >= '$yearrecent')" .
"ORDER BY lname, fname, suffix, fcccall";
$Recordset1 = mysql_query($query_Recordset1, $W3OITesting) or die(mysql_error());
$row_Recordset1 = mysql_fetch_assoc($Recordset1);
$totalRows_Recordset1 = mysql_num_rows($Recordset1);
//if a post is received handle it here
function getPostArray($array){
foreach ($array as $key => $value){
//search here for if this member is part of a family
//if not part of a family just update the payment
//record for the member with the value
try {
$query_Recordset3 = "SELECT lname, fname, suffix, `members`.member_id , `family`.member_id " .
"FROM members, family " .
"WHERE (`members`.member_id = `family`.member_id " .
"AND `members`.member_id = $key)";
echo $query_Recordset3. "<br>";
$Recordset3 = mysql_query($query_Recordset3, $W3OITesting);
$row_Recordset3 = mysql_fetch_assoc($Recordset3);
$totalRows_Recordset3 = mysql_num_rows($Recordset3);
echo $totalRows_Recordset3 . "<br>";
echo "$key => $value";
if($totalRows_Recordset3==FALSE) {//Recordset3 is always FALSE
echo " Error - " . $row_Recordset3['lname'];
}
if($totalRows_Recordset3!=0) {
echo " - A Family";
} else {
echo " - Individual";
}
echo "<br>";
}
catch(Exception $e)
{
echo "Exception: $e";
die();
}
if(is_array($value)){ //If $value is an array, get it also
getPostArray($value);
}
}
}
Related
I am trying to join two standard woocommerce tables and get the results.
My ultimate goal being to get out the zone_name based off a location_code.
My current query is as follows but with no results:
<?php
function prntPage() {
global $wpdb;
// The SQL query
$results = $wpdb-> get_results("SELECT location_code, zone_id, zone_name ".
"FROM {$wpdb->prefix} woocommerce_shipping_zone_locations ".
"JOIN {$wpdb->prefix} woocommerce_shipping_zones ".
"ON (woocommerce_shipping_zone_locations.zone_id = woocommerce_shipping_zones.zone_id)");
// Loop though rows data
foreach( $results as $row ){
echo $row ."<br>";
}
}
prntPage();
?>
Did you not enabled error reporting? this should have given you an error
{$wpdb->prefix}has to be direct in front of the table names at any time
$results = $wpdb-> get_results("SELECT location_code, zone_id, zone_name ".
"FROM {$wpdb->prefix}woocommerce_shipping_zone_locations ".
"JOIN {$wpdb->prefix}woocommerce_shipping_zones ".
"ON ({$wpdb->prefix}woocommerce_shipping_zone_locations.zone_id = {$wpdb->prefix}woocommerce_shipping_zones.zone_id)");
but it seems more logical
{$wpdb->prefix}has to be direct in front of the table names at any time
$results = $wpdb-> get_results("SELECT location_code, zone_id, zone_name ".
"FROM {$wpdb->prefix}shipping_zone_locations ".
"JOIN {$wpdb->prefix}shipping_zones ".
"ON ({$wpdb->prefix}shipping_zone_locations.zone_id = {$wpdb->prefix}shipping_zones.zone_id)");
Because woocommerce_ is already your prefix.
I have one table name Blog and i insert data on the table by using tne next query
INSERT INTO `blog`(title,desc) VALUES ('blog1','description')
And then i select data from the table by using
SELECT * FROM `blog`
This gives two hit to the database. Is there any possible way to do both queries at the same time. I want to make the process with one hit to the database.
i suppose you can use below statement :
INSERT INTO blog(title,desc) VALUES ('blog1','description') SELECT *
FROM blog ;
Here is the document
https://www.php.net/manual/en/mysqli.quickstart.multiple-statement.php
<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT)")) {
echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
$sql = "SELECT COUNT(*) AS _num FROM test; ";
$sql.= "INSERT INTO test(id) VALUES (1); ";
$sql.= "SELECT COUNT(*) AS _num FROM test; ";
if (!$mysqli->multi_query($sql)) {
echo "Multi query failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
do {
if ($res = $mysqli->store_result()) {
var_dump($res->fetch_all(MYSQLI_ASSOC));
$res->free();
}
} while ($mysqli->more_results() && $mysqli->next_result());
?>
I have three tables; Table 1 (appointments) that contains the appointment start and end time in YYYY-MM-DD HH:MM:SS format, provider ID, Customer ID and Service ID.
Table 2 (users) contains both Provider and Customer IDs and First/Last names.
Table 3 (services) contains the service ID, service name, and service description.
I need to create a fourth table, called display, that will display the Provider name, Client name, Service name, and start and end times in HH:MM format.
I've tried googling joins, but I'm not seeming to get anywhere.
I'm using a simple script from w3schools, below:
<?php
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM ea_appointments INNER JOIN ea_services";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "Start: " . $row["start_datetime"]. "End: " . $row["end_datetime"]. " - Provider: " . $row["id_users_provider"]. " - Customer: " . $row["id_users_customer"]. " - Service: " . $row["id_services"]."<br>";
}
} else {
echo "0 appointments";
}
$conn->close();
?>
In this case do not create a table because you just want to combine data from various tables. Just have a query or create a view.
In the query you need to tell mysql how to join your tables using the on clause. I'll show you how to join 2 tables, the rest is up to you:
SELECT *
FROM ea_appointments a
INNER JOIN ea_services s on a.serviceid=s.serviceid
I do not know what I am doing wrong here. When the following query is executed I receive the following error:
SQLSTATE[HY093]: Invalid parameter number: number of bound variables
does not match number of tokens
This is my query :
SELECT id, recipe_name, ingredients, directions, user_id, category_id, country_id, name, type, size FROM recipes WHERE user_id =:user_id LIMIT:per_page OFFSET:pagination_offset
And here is the script:
$page = !empty($_GET['page']) ? (int)$_GET['page'] : 1;
$per_page = 3;
$total_count = $this->countAll($iId); // which is 9 at this point
$pagination = new Pagination($page, $per_page, $total_count);
$pagination_offset = $pagination->offset();
$sWhereClause = "WHERE user_id =:user_id ";
$sLimitClause = "LIMIT:per_page ";
$sOffsetClause = "OFFSET:pagination_offset " ;
$aBinding = array (
':user_id' => $iUserId,
':per_page' => (int)$per_page,
':pagination_offset' => (int)$pagination_offset,
);
$sql = "
SELECT
*
FROM
recipes
" . $sWhereClause . "
" . $sLimitClause . "
" . $sOffsetClause . "
";
try{
$var = $this->db->prepare($sql);
$var->execute($binding);
return $var->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $ex) {
die($ex->getMessage());
}
Thank you for any help!
You define your bindings in the array $aBinding, but then send $binding to execute. Just use the same variable consistently, and you should be fine:
$var->execute($aBinding);
I'm trying to a single value in my DB...When I run it through the console, it works correctly (as I'm replacing the variables with numbers and text).. However, My query is not returning a value for book ID when I insert the PHP variable for it.. It's because the book_id is unpopulated...
$query = "UPDATE books "
. "SET readstatus='".$readstatus."' "
. "WHERE book_id=".$book_id;
echo $query
The echoed query states:
UPDATE books SET readstatus='half' WHERE book_id=0
The book ID is stored in the URI as bookstatusupdate.php?book_id=
Just cannot figure this one out!
It would help to know the error. Firstly, echo out the query:
$query = "UPDATE books "
. "SET readstatus='".$readstatus."' "
. "WHERE book_id=".$book_id;
echo $query;
I would guess that $book_id is unpopulated, so the query fails. What you should really be doing to make it secure is casting integers with (int) and wrapping strings in mysqli_real_escape_string().
$query = "UPDATE books "
."SET readstatus='". mysqli_real_escape_string( $readstatus )."' "
."WHERE book_id=". (int) $book_id;
If you're trying to get data from the URL, do it like so:
$book_id = (int) $_GET['book_id'];
$query = "UPDATE books "
."SET readstatus='". mysqli_real_escape_string( $readstatus )."' "
."WHERE book_id=". (int) $book_id;
echo $query;