My existing SQL Query:
$getEdu = "SELECT * FROM Request_Subject WHERE REQUEST_ID = $id
AND SUBJECT_ID IN (2,3,4)";
So in my Database, each REQUEST_ID can be associated with multiple SUBJECT_IDs
And SUBJECT_ID has values ranging from 1 to 10.
So my existing values in the table are:
REQUEST_ID: 1 -> SUBJECT_IDs: 2,3
REQUEST_ID: 2 -> SUBJECT_IDs: 2,4
REQUEST_ID: 3 -> SUBJECT_IDs: 2,8
So currently when the query runs, REQUEST_ID = 3 will still be included in the results because it has the SUBJECT_ID = 2.
Is there a possible way for me to create a SQL Query where even if one value matches, the Query would ignore the REQUEST_ID because it has different values from the array.
Thank you in advance.
UPDATE
Current Results:
$requestSubjects = array();
// So if I call REQUEST_ID = 3
$getEdu = "SELECT * FROM Request_Subject WHERE REQUEST_ID = 3
AND SUBJECT_ID IN (2,3,4)";
$getEdu_answer = mysqli_query($connection, $getEdu);
if(!$getEdu_answer || mysqli_num_rows($getEdu_answer)==0) {
echo "Error";
die();
}
else {
while($subjectRow = mysqli_fetch_assoc($getEdu_answer)) {
$subject = $subjectRow["Subject_ID"];
array_push($requestSubjects, $subject);
}
$reqSub = '{"reqSubject":' .json_encode($requestSubjects). '}';
echo $reqSub; // Returning a JSON to ajax
}
Echoed Results:
{"reqSubject":[2]}
The result is correct as the REQUEST_ID=3 is associated with a SUBJECT_ID = 2.
However what I want is that since REQUEST_ID=3 is also associated with SUBJECT_ID = 8, it should not echo a result at all.
If I understand you correctly, you have ALL SUBJECT_IDS of a REQUEST_ID to match (2,3,4) and only then to print the result?
if so, you can construct the query for each SUBJECT_ID
EDIT:
You must get ALL SUBJECT_IDs of REQUEST_ID using another sqlquery
Contact SUBJECT_IDs to your $getEdu query, and only then execute $getEdu query
Example:
$getEdu = "SELECT * FROM Request_Subject WHERE REQUEST_ID = $id";
//$sub_list is the all subect_id of $id
foreach ($sub_list as $sub_id){
$getEdu.=" AND $sub_id IN (2,3,4)";
}
$getEdu_answer = mysqli_query($connection, $getEdu);
If you execute it on your example, REQUEST_ID =3,
Than $qetEdu query should be:
SELECT * FROM Request_Subject WHERE REQUEST_ID = 3 AND 2 IN (2,3,4) AND 8 IN (2,3,4)
meaning that REQUEST_ID = 3 won't return because 8 is not in (2,3,4)
Hope it help a bit.
maybe
$getEdu = "SELECT * FROM Request_Subject WHERE REQUEST_ID=3
AND SUBJECT_ID IN (2,3,4, if(REQUEST_ID=3,8,null))";
if I understand you correctly...
Related
I am fetching multiple rows from my data base like,
$query = "SELECT * FROM student_info where district = '".$admdistrict."' AND user_status = 'approved' ORDER BY id DESC";
$result = mysql_query($query) or die(mysql_error());
$delete = mysql_fetch_array($resultt);
$std_delete_array = explode(',', $delete['id']);
the value of id in database is like 4,5,6 in different rows but it is giving only first value 4.
Another array I am fetching is,
$query="SELECT * FROM events where id='$district'";
$showdata=mysql_query($query) or die(mysql_error());
$user=mysql_fetch_array($showdata);
$std_fulllist_array = explode(',', $user['std_list']);
the value in database is 4,5,6,8. But in single coloumn, so it is giving proper output. now I want to subtract $std_delete_array from $std_fulllist_array.
I am using following code,
$values = array_diff($std_fulllist_array, $std_delete_array);
which is only subtracting first value of $std_delete array.
strucutre of table student_info is
id ! name ! District
4 a panipat
5 b panipat
6 c panipat
strucutre of table events is
id ! district ! std_list
1 panipat 4,5,6
2 karnal 4,7,8
3 chandigarh 5,6,7
You are saying the value of id in database is like 4,5,6 in different rows
that means your table is look like
id district
-- ---------
4 abc
5 def
6 geh
8 ijk
so your first query is fetching multiple records.
EDIT
So your query would be
$ret_ = array();
$query = "SELECT * FROM student_info where district = '".$admdistrict."' AND user_status = 'approved' ORDER BY id DESC";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result) > 0) {
// output data of each row
while($row = mysql_fetch_array($result)) {
echo $row['id'];
$ret_[] = $row;
}
}
print_r($ret_);
I have two different tables of the following structure:
grouprel
id | userId | pupID | groupId
pupils
id | userId | fname | lname
pupId in groulrel is equal to id in pupils.
I want to fetch pupils from a different group and then order them by fname, lname.
Now I have two queries like this:
$q = "SELECT * FROM grouprel WHERE userid = ". $userid ." AND groupId = ". $_GET['id'] ."";
$r = mysqli_query($mysqli, $q);
while ($rows = mysqli_fetch_object($r)) {
$query = "SELECT id, fname, lname FROM pupils WHERE userid = ". $userid ." AND id = ". $rows->pupId ." AND status = 0 ORDER BY fname, lname";
$result = mysqli_query($mysqli, $query);
while($row = mysqli_fetch_object($result)) {
echo stuff...
}
}
This works, but it doesn't order the names alphabetically like I want to.
How could I fix this?
This is iterating over the first query:
while ($rows = mysqli_fetch_object($r)) {
And this iterates over each instance of the second query:
while($row = mysqli_fetch_object($result)) {
So if the first query returns 1,2,3, and each iteration of the second query returns A,B, then your output would be:
1 A
1 B
2 A
2 B
3 A
3 B
The second query is ordering by the ORDER BY clause you gave it. But you are ordering the entire output by the first query.
Ultimately, why do you need these separate queries at all? Executing a database query in a loop is almost always the wrong idea. It looks like all you need is one query with a simple JOIN. Guessing on your logic, something like this:
SELECT
pupils.id, pupils.fname, pupils.lname
FROM
pupils
INNER JOIN grouprel ON pupils.id = grouprel.pupId
WHERE
pupils.userid = ?
AND grouprel.groupId = ?
AND pupils.status = 0
ORDER BY
fname, lname
It may take a little tweaking to match exactly what you're looking for, but you can achieve your goal with a single query instead of multiple separate queries. Then the results of that query will be ordered the way you told MySQL to order them, instead of the way you told PHP to order them.
I'm trying to select something from a table and insert that information into another table
For example I've 3 rows in table A which I want to insert into table B, he only inserts 2 of the 3.
I got this: I've tried it with fetch_array() but I get only the error non-object
EDIT: THE PART OF THE SCRIPT
$log = $db->query("SELECT itemname FROM log_mitem WHERE mobname = '".$mobname."' AND game = '".$game."'") or die($db->error);
if($log1 = $log->fetch_object());
{
while($loco = $log->fetch_object())
{
You shouldn't have that first if, just do:
$log = $db->query("SELECT itemname FROM log_mitem WHERE mobname = '".$mobname."' AND game = '".$game."'") or die($db->error);
while($loco = $log->fetch_object()) {
// do something
}
Also note that you don't need a while loop for this trivial task, you can use INSERT INTO ... SELECT syntax
INSERT INTO table1 ( column1 )
SELECT col1
FROM table2
WHERE cond1
I'm trying to return a MySQL query using GROUP BY as a array.
My table looks like this:
user_id | type
--------------------
1 | test
1 | test
2 | test
1 | hello
1 | helloworld
And my code and query:
$number_of_workouts = array();
$query = mysqli_query(connect(),"SELECT type, COUNT(*) FROM `log` WHERE `user_id` = $user_id GROUP BY type");
$number_of_workouts = mysqli_fetch_assoc($query);
return $number_of_workouts;
This code above isn't returning a array with all types listed, it will only return the number of one type(assuming that $user_id = 1.
How can I return the result of the query as an array?
mysqli_fetch_assoc($query);
fetches 1 row only from the resultset
If you want ALL rows from the resultset, you have to loop for each row and add it to a stack like:
$number_of_workouts = array();
$query = mysqli_query(connect(),
"SELECT type, COUNT(*) AS count
FROM `log`
WHERE `user_id` = $user_id
GROUP BY type"
);
$array = array();
while ($number_of_workouts = mysqli_fetch_assoc($query)) {
$array[$number_of_workouts['type']] = $number_of_workouts['count'];
}
// Now you have all results like you want in the variable array:
print_r($array);
// print count of type test:
echo $array['test'];
Or you try out mysqli_fetch_all() (http://www.php.net/manual/en/mysqli-result.fetch-all.php)
(sorry for many updates)
You are fetching only first record here. Keep the fetching statement in while loop
while($number_of_workouts = mysqli_fetch_assoc($query))
{
echo "<pre>";
print_r($number_of_workouts);
}
this is my script
<?php
if(isset($_GET['id']))
{
$id = $_GET['id'];
}
else
{
$id = 1;
}
$random = $conn->query("SELECT * FROM records ORDER BY RAND()");
$row = $random->fetch();
$stmt_1 = $conn->prepare("SELECT * FROM records WHERE id > ? ORDER BY id ASC LIMIT 1");
$stmt_1->bindValue(1,$id);
$stmt_1->execute();
$stmt_1->setFetchMode(PDO::FETCH_ASSOC);
$row = $stmt_1->fetch();
$id = $row['id'];
$stmt_1 = $conn->prepare("SELECT * FROM records WHERE id < ? ORDER BY id DSC LIMIT 1");
$stmt_1->bindValue(1,$id);
$stmt_1->execute();
$stmt_1->setFetchMode(PDO::FETCH_ASSOC);
$row = $stmt_1->fetch();
$id = $row['id'];
?>
But I have a problem with it. For example i have 4 records in database :
ID String
1 Test-1
2 Test-2
3 Test-3
4 Test-4
the query works fine it gives me the next record but not the id which i put like if i put id=1 returns id 2 or id=2 returns info for id 3 and the result is not accurate. So my question is what should I do id to return correct result not +1. I know it starts to count from 0 and i want to fix that in my script i want to make it to start from 1.
replace this
$id = 1;
by
$id = 0;
or replace this
SELECT * FROM records WHERE id > ?
by
SELECT * FROM records WHERE id >= ?
^--//-will look for id equal to 1 or bigger
why don't you change your query to
EDIT: Query will not work as records are deleted.
$stmt_1 = $conn->prepare("SELECT * FROM records WHERE id = ?");
$stmt_1->bindValue(1,$id +1);
$stmt_1->execute();
So you will get the record with the next highest id.
Just a hint to optimize your query.
One further question do you use auto_increment in your table definition. If you do so, you shold keep in mind that this mysql-sequence starts by one to calculate the primary key
Hope it helps