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
Related
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 have looked online for a solution to my problem for many hours to no avail.
I have multiple selct statements, receiving data from different mysql tables.
I want to echo completely separated results. Currently, results are printed as if they are one,
so I cannot work on the answers separately.
Suppose the output from table is:
100
200
300
400
I want to echo out:
result1 = 100;
result2 = 200;
etc
So I can work on the final results in another program. If a result is null, it should not produce an error,
but just post 0.
Example, if output from mysql table is:
100
null
null
100
I want the output to clearly show
result1 = 100;
result2 = 0;
result3 = 0;
result4 = 100;
etc.
$check_sco = 100;
$sql = "SELECT TABLE_1 FROM RIDER_1 WHERE score1=$check_sco;";
$sql .= "SELECT TABLE_1 FROM RIDER_2 WHERE score1=$check_sco;";
$sql .= "SELECT TABLE_1 FROM RIDER_3 WHERE score1=$check_sco;";
$sql .= "SELECT TABLE_1 FROM RIDER_4 WHERE score1=$check_sco";
if (mysqli_multi_query($con,$sql)) {
do {
/* store first result set */
if ($result = mysqli_store_result($con)) {
while ($row = mysqli_fetch_row($result)) {
printf("%s\n", $row[0]);//how to echo separated result that can be manipulated indepedently?
}
mysqli_free_result($result);
}
} while (mysqli_next_result($con));
}
Thank you.
Why not just run them in sequence?
$check_sco = 100;
$riders = array();
for($i=1; $i<=4; $i++) {
$sql = "SELECT TABLE_1 FROM RIDER_" . $i . " WHERE score1=" . $check_sco;
$result = mysqli_query($con, $sql);
$row = $result->fetch_assoc();
$riders[] = ($row['TABLE_1']) ? $row['TABLE_1'] : 0;
}
Then you'll have an array with the results you want
You need to use IFNULL which if TABLE_1 is not null it will return TABLE_1 otherwise it will give you 0
SELECT IFNULL(TABLE_1, 0) FROM RIDER_1 WHERE score1=$check_sco;
SELECT IFNULL(TABLE_1, 0) FROM RIDER_2 WHERE score1=$check_sco;
SELECT IFNULL(TABLE_1, 0) FROM RIDER_3 WHERE score1=$check_sco;
SELECT IFNULL(TABLE_1, 0) FROM RIDER_4 WHERE score1=$check_sco
I have an array in PHP that is looping through a set of names (and a corresponding quantity). I would like to print the ones found in a MYSQL database table (to which I've succesfully connected). I'm currently using the code:
foreach ($arr as $name => $quan) {
$query = "SELECT * FROM table WHERE name='$name'";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result) > 0) {
$row = mysql_fetch_array($result);
echo $quan." ".$row['name']. "\n";
}
}
For some reason, this only prints the last quantity and name in the array. Help?
For example, if the array has key-value pairs of {A-4, B-2, C-3}, and table contains {A, B, D} as names ... it'll only print "2 B".
Change the code to the following:
foreach ($arr as $name => $quan) {
$query = "SELECT * FROM table WHERE name='$name'";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result) > 0) {
while($row = mysql_fetch_array($result)) {
echo $quan." ".$row['name']. "\n";
}
}
}
You have to loop through the result. By the way, stop using mysql_query()! use MySQLi or PDO instead ( and be careful of SQL Injection ; you can use mysqli_real_escape_string() to handle input parameters ). For MySQLi implementation , here it is :
foreach ($arr as $name => $quan) {
$query = "SELECT * FROM table WHERE name='$name'";
$result = mysqli_query($query) or die(mysqli_error());
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_array($result)) {
echo $quan." ".$row['name']. PHP_EOL;
}
}
}
And rather "\n", I prefer using PHP_EOL ( as shown above )
And as the comment suggests, the SQL statement can be executed once, as follow:
$flipped_array = array_flip($arr); // flip the array to make "name" as values"
for($i = 0; $i < count($flipped_array); $i++) {
$flipped_array[$i] = '\'' . $flipped_array[$i] . '\''; // add surrounding single quotes
}
$name_list = implode(',', $arr);
$query = "SELECT * FROM table WHERE name IN ($name_list)";
// ... omit the followings
e.g. in $arr contains "peter", "mary", "ken", the Query will be:
SELECT * FROM table WHERE name IN ('peter','mary','ken')
sidenote: but I don't understand your query. You only obtain the name back from the query? You can check number of rows, or you can even group by name, such as:
SELECT name, COUNT(*) AS cnt FROM table GROUP BY name ORDER BY name
to get what you want.
UPDATE (again): based on the comment of OP, here is the solution :
$flipped_array = array_flip($arr); // flip the array to make "name" as values"
for($i = 0; $i < count($flipped_array); $i++) {
$flipped_array[$i] = '\'' . $flipped_array[$i] . '\''; // add surrounding single quotes
}
$name_list = implode(',', $arr);
$query = "SELECT name, COUNT(*) AS cnt FROM table WHERE name IN ($name_list) GROUP BY name HAVING COUNT(*) > 0 ORDER BY name";
$result = mysqli_query($query) or die(mysqli_error());
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_array($result)) {
echo $quan." ".$row['name']. ": " . $row['cnt'] . PHP_EOL;
}
}
The above query will show the name appearing in the table only. Names not in table will not be shown. Now full codes ( be cautious of SQL Injection , again )
this is my first time posting here, although I have gotten many great tips and techniques reading the posts here.
Here is my objective:
I have 2 somewhat similar tables to compare. For each row of each table, I am pulling the fields I want into into an array.
I basically want to echo out the values of any array from one table that has matching values in the other array.
Here is my code, maybe it will be easier to understand.
$sql = "SELECT * FROM $i_comp ORDER BY `manufacturer`";
$statement = $objDb->query($sql);
$c_skus = $statement->fetchAll(PDO::FETCH_ASSOC);
$sql = "SELECT `sku_one`,`sku_two`,`qty`,`manufacturer`";
$sql .= "FROM $i_gas ORDER BY `manufacturer`";
$statement = $objDb->query($sql);
$d_skus = $statement->fetchAll(PDO::FETCH_ASSOC);
foreach ( $c_skus as $c_sku ) {
// i want to see if any values of this array exist in the array created hy
// the foreach loop below (yes, repeat for each row)
$c = array($c_sku['sku'],$c_sku['sku_one'],$c_sku['sku_two'],$c_sku['sku_three']);
foreach ( $d_skus as $d_sku ) {
$d = array($d_sku['sku_one'],$d_sku['sku_two']);
$intersect = array_intersect($c, $d);
echo '<pre>', print_r($intersect), '</pre>';
}
}
Here are the results I receive for each iteration of the code:
Array
(
)
1
It should also be noted that I am not concerned with the Keys, just the Values. Eventually, those values will be works into an INSERT statement but for the time being I just need to get the right results.
Anyways, thanks for any and all help!
This is usually done in SQL
if you want whole row that has at least 1 matching SKU in another table:
$sql = "
SELECT c.* FROM $i_comp AS c
JOIN $i_gas AS d
ON d.sku_one in (c.sku, c.sku_one, c.sku_two, c.sku_three)
OR d.sku_two in (c.sku, c.sku_one, c.sku_two, c.sku_three)
ORDER BY c.`manufacturer`";
$statement = $objDb->query($sql);
$c_skus = $statement->fetchAll(PDO::FETCH_ASSOC);
// all rows that have at least 1 matching sku on another table
print_r($c_skus);
If you want only SKUs
$sql = "
SELECT d.sku_one FROM $i_comp AS c
JOIN $i_gas AS d
ON d.sku_one in (c.sku, c.sku_one, c.sku_two, c.sku_three)
UNION
SELECT d.sku_two FROM $i_comp AS c
JOIN $i_gas AS d
OR d.sku_two in (c.sku, c.sku_one, c.sku_two, c.sku_three)
";
$statement = $objDb->query($sql);
$c_skus = $statement->fetchAll(PDO::FETCH_ASSOC);
// all skus that have at least 1 matching sku on another table
print_r($c_skus);
In PHP intersect variant you need to build the arrays separately and then use array_intersect
$c = array();
foreach ( $c_skus as $c_sku ) {
$c[] = $c_sku['sku'];
$c[] = $c_sku['sku_one'];
$c[] = $c_sku['sku_two'];
$c[] = $c_sku['sku_three'];
}
$d = array();
foreach ( $d_skus as $d_sku ) {
$d[] = $d_sku['sku_one'];
$d[] = $d_sku['sku_two'];
}
$intersect = array_intersect($c, $d);
echo '<pre>', print_r($intersect), '</pre>';
I need to select a whole column.
So my question is how do i get a whole column ?
$query = "SELECT * ";
$query .= "FROM employees ";
$query .= "WHERE id=*";
$query .= "ORDER BY id ASC ";
I tried id=* but no luck ...
My goal is to cycle through all IDs but some may be missing so i figured i put them in a numeric or associative array and use foreach. If there is a better way , please do share.
EDIT:
function get_all_ids()
{
global $connection;
$query = "SELECT * ";
$query .= "FROM employees ";
$query_result = mysql_query ( $query , $connection );
confirm_query($query_result);
$query_result_array = mysql_fetch_assoc($query_result);
return $query_result_array;
}
i use this to print the array
$all_id = get_all_ids();
// preparing the table;
echo "<pre>";
print_r($table);
print_r($all_id);
echo "</pre>";
and this is the array
Array
(
[id] => 1
[department_id] => 1
[name] => jordan
[EGN] => 9108121544
[email] => testEmail
[address] => testAddress
[country] => testCounty
)
If there's more than one row in your result set, you need to keep fetching until all results are retrieved:
$q = mysql_query('SELECT * FROM `table`');
while (($row = mysql_fetch_assoc($q)) != FALSE)
{
// Do something with *one* result
}
mysql_free_result($q);
If you'd like to retrieve all ids in a single fetch, you could do:
$q = mysql_query('SELECT GROUP_CONCAT(`id`) AS `id_list` FROM `table`');
$row = mysql_fetch_assoc($q);
mysql_free_result($q);
$list_of_ids = explode(',', $row['id_list']);
WARNING: GROUP_CONCAT() usually has a result limit of 1024 bytes; meaning your results will be truncated for large tables. You could either resort to the first solution, or increase group_concat_max_len for the current connection.
If you want ALL the records then you dont need a WHERE condition at all.
Perhaps you mean the simple:
SELECT id
FROM employees
ORDER BY id ASC
If this gives you only one row, then either you have only one row or you are adding a LIMIT 1 or your PHP code does not loop through all the results but just shows the first one of them. Please add the PHP code.
If you want to select a single column. Then do not use "*", give the name of the columns name separated by comma and quoted with "`" (tick) for safety.
$query = "SELECT `id` "; //if you only want to get ids from the table
$query .= "FROM employees ";
$query .= "WHERE id=*";
$query .= "ORDER BY id ASC ";