I have the following function:
private static function getFixedFare($FixedFareId) {
$pdo = new SQL();
$dbh = $pdo->connect(Database::$serverIP, Database::$serverPort, Database::$dbName, Database::$user, Database::$pass);
try {
$query = "SELECT Fare FROM tblfixedfare
WHERE FixedFareId = :fixed_fare_id
AND DayHalf = :day_half";
$stmt = $dbh->prepare($query);
$stmt->bindParam(':fixed_fare_id', $FixedFareId, PDO::PARAM_INT);
$stmt->bindParam(':day_half', self::$day_half, PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_COLUMN);
$stmt->closeCursor();
$dbh = null;
return $result;
}
catch (PDOException $pe) {
die("Error: " .$pe->getMessage(). " Query: ".$stmt->queryString);
}
}
Basically I want to change the query to do nine different selects, as follows:
$query = "SELECT Fare FROM tblfixedfare
WHERE FixedFareId = :fixed_fare_id
AND DayHalf = :day_half
AND CarType = 'Car'";
and
$query = "SELECT Fare FROM tblfixedfare
WHERE FixedFareId = :fixed_fare_id
AND DayHalf = :day_half
AND CarType = 'Est'";
and the same for all the other car types, 'Exec', 'ExecEst', '6B', '7B', '7W', '8B' and 'Bus' which will only ever be these car types.
I was hoping I could store each of these query results into different variables without having to do 9 different queries (reducing code). Such as a loop and then storing the results to $resultcar, $resultest and so on...
Not to sure how I would do this so any help would be much appreciated! :-)
You can do an IN
SELECT CarType, Fare FROM tblfixedfare
WHERE FixedFareId = :fixed_fare_id
AND DayHalf = :day_half
AND CarType IN ('Car', 'Est' ...);
Note that you have to include the CarType in the Select so you can filter them after the query.
UPDATED: You can group your results by CarType already like this:
$results = $stmt->fetchAll(PDO::FETCH_ASSOC|PDO::FETCH_GROUP);
The code above should give you something like:
array(
'Car' => array(
// data
),
'Est' => array(
// data
)
)
If you don't mind changing your variables, you can immediately have them in variables without looping through extract(...)
So feeding
$results = $stmt->fetchAll(PDO::FETCH_COLUMN|PDO::FETCH_GROUP);
which is the array mentioned above to extract:
extract($results, EXTR_PREFIX_ALL, 'result');
will let you have the result sets in variables already:
var_dump($result_Car);
array(2) {
[0]=> array(1) {
["Fare"]=> string(1) "100"
}
[1]=>
array(1) {
["Fare"]=> string(1) "200"
}
}
All in all, in one line:
extract($q->fetchAll(PDO::FETCH_ASSOC|PDO::FETCH_GROUP), EXTR_PREFIX_ALL, 'result');
For repeating the query on the nine different car types, you can store each of the car names into an array and loop through the array inserting the new name each time:
$cars = array();
array_push($cars, "Car", "Est", "Exec", "ExecEst", "6B", "7B", "8B","Bus");
for($i=0; $i < sizeof($cars); $i++)
{
try {
$query = "SELECT Fare FROM tblfixedfare
WHERE FixedFareId = :fixed_fare_id
AND DayHalf = :day_half
AND CarType = '".$cars[i]."'";
//.....rest of your code
}
catch (PDOException $pe) {
die("Error: " .$pe->getMessage(). " Query: ".$stmt->queryString);
}
}
You can then store the result of each query in a new array using the name of the car ( i.e $cars[i] ) as the key.
Related
include "includes/dbh.inc.php";
$data = file_get_contents("dumps/datadump-hung1.json");
$post = json_decode($data, true);
foreach($post['sessionResult']['leaderBoardLines'] as $userArr){
$carname .=$userArr['car']['carModel'];
} echo $carname;
this echoes out the carmodel numbers like this= 19115 instead of 19 1 15
when i try to match these with my database to echo out the name of cars the numbers respond to with:
$carGETdb = "SELECT carName FROM cars WHERE carID IN ($carname)";
$result = mysqli_query($conn, $carGETdb);
$row = mysqli_fetch_array($result)["carName"];
echo $row;
it posts nothing, because no cars is associated with 19115 but 3 different cars is associated with 19, 1 and 15
is there a way to foreach each array in singles, so i can match them with my database and echo out as carnames instead of numbers?
Map the values you're after to a new array
Build a prepared statement with the appropriate number of ? parameters in your IN clause
Bind the array of values to your statement
Execute and fetch
$carIds = array_map(function($userArr) {
return $userArr['car']['carModel'];
}, $post['sessionResult']['leaderBoardLines']);
// [ 19, 1, 15 ]
$placeholders = implode(', ', array_fill(0, count($carIds), '?'));
// "?, ?, ?"
$bindTypes = str_repeat('i', count($carIds));
// "iii"
$stmt = $conn->prepare(
"SELECT `carID`, `carName` FROM `cars` WHERE `carID` IN ($placeholders)");
$stmt->bind_param($bindTypes, ...$carIds);
$stmt->execute();
$stmt->bind_result($carId, $carName);
$carNames = [];
while ($stmt->fetch()) {
$carNames[$carId] = $carName;
}
var_dump($carNames);
Using your code...
include "includes/dbh.inc.php";
$data = file_get_contents("dumps/datadump-hung1.json");
$post = json_decode($data, true);
$carname = [];
foreach($post['sessionResult']['leaderBoardLines'] as $userArr){
$carname[] = $userArr['car']['carModel'];
}
$carnames = implode(',', $carname);
echo $carnames;
Then with your following statement when querying the database, you can use the implded value ( but this is bound to sql injection attacks ). You should use parameterised query instead. However, I am not going to change too much of your code so you can see what is going on.
$carGETdb = "SELECT carName FROM cars WHERE carID IN ($carnames)";
$result = mysqli_query($conn, $carGETdb);
$row = mysqli_fetch_array($result)["carName"];
echo $row;
I want to select records from two tables. These two tables have the prefix "shop_".
How do I select the records for both shops in a sql statement?
My current statement:
// Select
$stmt = $mysqli->prepare("SELECT name, html_id, price FROM database_name WHERE TABLE_NAME LIKE 'shop%'");
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc())
{
$arr[] = $row;
}
$name = [];
foreach($arr as $arrs)
{
$name[] = array(0 => $arrs['name'], 1 => $arrs['html_id'], 2 => $arrs['price']); //here
}
$stmt->close();
print_r($name);
The mysql php current error is:
Fatal error: Uncaught Error: Call to a member function execute() on boolean in C:\wamp642\www\webcart\search.php on line 17 and line 17 is: $stmt->execute();
I can get the tables to "show" with this command:
$stmt = $mysqli->prepare("show tables like '%shop%'");
But it doesn't get the records, just an object I think.
The output of "show tables like '%shop%'" prints 2 arrays just like it should, but the arrays are empty with no data/records.
I'm thinking it's the sql statement that needs work. Thanks.
EDIT:
I've also tried:
$stmt = $mysqli->prepare("SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='feeds' AND TABLE_NAME LIKE 'shop%'");
EDIT: The contents of search.php
<?php
include 'define.php';
$mysqli = new mysqli($host, $db_user, $db_password, $db_database);
if($mysqli->connect_error)
{
?><script>var profiles_delete_modal_1 = ' Error 3: Problem deleteing profile. Make sure database login credentials are correct.';</script>
<script>$(".modal").css({"opacity":"1", "z-index":"100"});$(".modal_mid").html("<pre>" + profiles_delete_modal_1 + "</pre>");setTimeout(function(){$(".modal").css({"opacity":"0", "z-index":"-100"});},5000);</script><?php
exit;
}
$shop = 'shop';
// Select
//$stmt = $mysqli->prepare("show tables like '%shop%'");
//$stmt = $mysqli->prepare("SELECT * FROM feeds WHERE TABLE_NAME LIKE 'shop%'");
$stmt = $mysqli->prepare("SELECT name, html_id, price FROM database_name WHERE TABLE_NAME LIKE 'shop%'");
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc())
{
$arr[] = $row;
}
$n=0;
$name = [];
foreach($arr as $arrs)
{
$name[] = array(0 => $arrs['name'], 1 => $arrs['html_id'], 2 => $arrs['price']); //here
$n++;
}
$stmt->close();
print_r($name);
and the contents of define.php:
$www_dir = 'webcart';
$url_root = 'http://localhost/' . $www_dir . '';
$www_dir_slash = $_SERVER['DOCUMENT_ROOT'] . '' . $www_dir . '/';
$host = 'localhost';
$db_user = 'webcart_admin';
$db_password = 'asd123';
$db_database = 'shop';
$_SESSION['host'] = $host;
$_SESSION['db_user'] = $db_user;
$_SESSION['db_password'] = $db_password;
$_SESSION['db_database'] = $db_database;
EDIT
From going on the answer stated below I've been able to create a string like this:
SELECT name, html_id, price FROM shop_a UNION shop_b
however it won't execute properly.
This is my code:
$stmt = $mysqli->prepare("SELECT name, html_id, price FROM shop_a UNION shop_b");
$result = $stmt->execute();
It gives the following error:
Fatal error: Uncaught Error: Call to a member function execute() on boolean in C:\wamp642\www\webcart\search.php on line 43
EDIT Got it.
I'll post the answer up soon. The statement goes like this:
"SELECT name, html_id, price FROM shop_a UNION SELECT name, html_id, price from shop_b"
I got the answer pretty much from musafar, although I needed to get to the objects in the array. So I used some foreach loops to do this seeing as I don't know any other way. If there's another way to get to mysqli_object data, please let me know.
$stmt = $mysqli->prepare("SELECT TABLE_NAME FROM information_schema.tables WHERE table_schema = 'shop' AND table_name LIKE 'shop%'");
//table_schema is the database name and 'shop%' is the search string
$stmt->execute();
$tables = $stmt->get_result();
$stmt->close();
$arr = [];
foreach($tables as $tabless)
{
$arr[] = $tabless;
}
foreach($arr as $arrs)
{
$toby[] = implode(',',$arrs);
}
$tobyy = implode(' UNION SELECT name, html_id, price from ',$toby);
//$tobyy = "shop_a UNION SELECT name, html_id, price from shop_b"
$arr = [];
$stmt = $mysqli->prepare("SELECT name, html_id, price FROM " . $tobyy);
$result = $stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc())
{
$arr[] = $row;
}
$n=0;
$name = [];
foreach($arr as $arrs)
{
$name[$n] = array(0 => $arrs['name'], 1 => $arrs['html_id'], 2 => $arrs['price']); //here
$n++;
}
$stmt->close();
print_r($name);
//$name = "Array ( [0] => Array ( [0] => Chromecast [1] => chromecast [2] => 59 ) [1] => Array ( [0] => EZCast [1] => ezcast [2] => 49 ) )"
SELECT query is used to fetch data from DB tables, not DB itself. So you need to provide a table name in the FROM part of your query.
Considering you're trying to fetch data from similar tables (same fields)...
$stmt = $mysqli->prepare("SELECT table_name FROM information_schema.tables WHERE table_schema = 'wp_105424' AND table_name LIKE 'shop%'");
$stmt->execute();
$tables = $stmt->get_result();
$dataStmt = $mysqli->prepare("SELECT name, html_id, price FROM " . implode(',', $tables)); // name, html_id, price should be in all tables that starts with *shop*
$dataStmt->execute();
$data = $dataStmt->get_result();
And you may need to add conditions to handle all scenarios.
i need to check if in an exam that contains 5 students
exist 3 students from the same class.
here is what i tried
<?
//this array contains all student id's that are in an exam
$exam = array('s1' => $s1, 's2' => $s2, 's3' => $s3, 's4' => $s4, 's5' => $s5);
$values = implode(", ", $exam);
$sql = "SELECT class FROM students WHERE students.id IN (" . $values . ")";
try{
$db = new db();
$db = $db->connect();
$stmt = $db->query($sql);
$studs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$db = null;
if(!empty($studs)) {
//check if 3 students from the same class are taking the exam
$i = 0; $s = 0;
foreach($exam as $e )
{
if( !in_array( $e, $studs[$i] ) )
{
$exist = FALSE;
}
else {$s++;}
$i++;
}
if ($s<=3) {
#do sth
}
else {
echo "more than 3 students";
}
} else {
echo "error";
}
} catch(PDOException $e) {}
?>
Problem
what i am not sure about is how to count that 3 students have the same class id in this exam array.
i know there is something i need to fix in my foreach just trying with no success.
You can ask your database to return all classes with 3 or more students from your id list by applying an an aggregate snd grouping your results by the class ánd using a HAVING clause:
SELECT class, COUNT(id) as num_students_in_class FROM students WHERE id IN (1,2,3,4) GROUP BY class HAVING COUNT(id) >= 3
More info:
How to use group by in SQL Server query?
What's the difference between HAVING and WHERE?
If you dont want to query as suggested in https://stackoverflow.com/a/46517195/100809 you’ll need to keep an assoc array of the classes and the number of times you’ve seen it:
$seenClasses = array_count_values($studs);
foreach($seenClasses as $class => $numStudents) {
if ($numStudents > 4)
echo “class $class has $numStudents”;
}
I am trying to make a selection based on a nested array I get from a prior selection.
Here is where I make my first selection:
$coursequery = "
SELECT
courseID
FROM enrollments
WHERE
studentID = '$userid'
";
try
{
$stmt = $db->prepare($coursequery);
$result = $stmt->execute();
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$rows = $stmt->fetchAll();
$_SESSION['studentcourses'] = $rows;
This gets all the courseID's in the following format:
Array ( [0] => Array ( [courseID] => 6 ) [1] => Array ( [courseID] => 7 ) )
and I want to be able to access these ID's for selecting information from a different table. I've started by trying to use a for loop to grab all the "course information" depending on the ID.
for($i = 0; $i < $count; $i++) {
$coursequery = "
SELECT
*
FROM courses
WHERE courseID = '$studentcourses[$i]'
";
try
{
$stmt = $db->prepare($coursequery);
$result = $stmt->execute();
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$row = $stmt->fetchAll();
$_SESSION['studentcourseinfo'] = $row;
}
Any help would be greatly appreciated in accomplishing this!
You can accomplish this with one SQL query thus eliminating all these loops
SELECT
*
FROM courses
INNER JOIN enrollments ON
enrollments.courseID = courses.courseID
AND enrollments.studentID = '$userid'
WHERE 1
you can use same array in query, can use implode function
$coursequery = "SELECT * FROM courses
WHERE courseID IN (" . implode(",", $studentcourses) . ");";
As long as you change the output format
Array (6, 7)
where 6 and 7 would be the id of the courses
Also in you code have mistake in rewrite var $_SESSION['studentcourseinfo'] = $row; these overwriting the same variable at a time
I am using mysqli to fetch data from the database and put it into an array with a while loop. When i echo out the array i get an empty array however in a function i previously did this code worked but it had a different result from the database. I know that the database is giving out good data because when i echo out the result $idGroup it gives me 2 which is correct.
Ps i know it will keep replacing itself because i don't specify an index
private function Groups()
{
$functionRun = 0;
$i = 0;
$helperArray = array();
$this->grouplist = array();
$query = "SELECT GroupName, Groups.idGroup
FROM Groups
INNER JOIN Members
ON Groups.idGroup = Members.idGroup
WHERE Members.idMember = ? ";
//prepare query and execute
if($stmt = $this->connection->prepare($query))
{
$stmt->bind_param('s', $this->id);
$stmt->execute();
$stmt->bind_result($GroupName, $idGroup);
while ($stmt->fetch())
{
$helperArray[] = $idGroup;
}
echo $helperArray;
}
Use print_r when dealing with arrays. Use echo on strings.
Try this
$query = "SELECT GroupName, Groups.idGroup
FROM Groups
INNER JOIN Members
ON Groups.idGroup = Members.idGroup
WHERE Members.idMember = ? ";
//prepare query and execute
if($stmt = $this->connection->prepare($query))
{
$stmt->bind_param('s', $this->id);
$stmt->execute();
$stmt->bind_result($GroupName, $idGroup);
$helperArray =array();
while ($stmt->fetch())
{
$helperArray[] = $idGroup;
}
print_r($helperArray);
}