I am writing a php site using a mysql database for a class of mine and cannot for the life of me figure out what is wrong with it. I have a query that works locally on my machine (on an identical db to the one on the teacher's server) but when I upload it, it doesn't work. The problem is that the query is returning 0 results even though the db has info in it that should be showing.
function bigAssQuery($whereCondition)
{
$queries[] = 'CREATE TEMPORARY TABLE subAssignments (SELECT ua.assignmentid, ua.assignmentnum, ua.description
FROM Course c JOIN UserAssignment ua ON ua.crn = c.CRN AND ua.term = c.term
WHERE c.CRN = "'.$_SESSION["crnum"].'" AND c.term = "'.$_SESSION["mysem"].'")';
$queries[] = 'CREATE TEMPORARY TABLE subStudents (SELECT s.studentid, s.lastname, s.firstname
FROM Course c JOIN Student s ON s.crn = c.CRN AND s.term = c.term
WHERE c.CRN = "'.$_SESSION["crnum"].'" AND c.term = "'.$_SESSION["mysem"].'")';
$queries[] = 'CREATE TEMPORARY TABLE subRubric(SELECT assignmentid, re.rubricelementid, re.learning_goal_char
FROM RubricElement re JOIN RubricAssignmentRelation rar ON re.rubricelementid = rar.rubricelementid)';
$queries[] = 'CREATE TEMPORARY TABLE subAssignRub(SELECT subAssignments.assignmentid, rubricelementid, learning_goal_char, assignmentnum, description
FROM subRubric JOIN subAssignments ON subAssignments.assignmentid = subRubric.assignmentid)';
$queries[] = 'CREATE TEMPORARY TABLE subAssignRubStud (SELECT *
FROM subAssignRub CROSS JOIN subStudents)';
$queries[] = 'CREATE TEMPORARY TABLE subAssignInstRubStud (SELECT sars.assignmentid, ai.ainstanceid, rubricelementid, learning_goal_char, assignmentnum, description, sars.studentid, lastname, firstname
FROM subAssignRubStud sars LEFT JOIN AssignmentInstance ai ON sars.studentid = ai.studentid AND sars.assignmentid = ai.assignmentid)';
$queries[] = 'CREATE TEMPORARY TABLE subTotal (SELECT assignmentid, siars.ainstanceid, s.ainstanceid As scoreAID, siars.rubricelementid, learning_goal_char, assignmentnum, description, studentid, lastname, firstname, score
FROM subAssignInstRubStud siars LEFT JOIN Score s ON siars.ainstanceid = s.ainstanceid AND siars.rubricelementid = s.rubricelementid
ORDER BY lastname, assignmentid)';
$queries[] = 'SELECT *
FROM subTotal
'.$whereCondition.' Order By lastname, assignmentnum, learning_goal_char';
return($queries);
}
Then when the db is queried the code looks like this. . .
$queries = bigAssQuery($whereCondition);
$result = 1;
foreach($queries as $query)
{
$result = $db->query($query);
if(!$result)
{
echo '<script type="text/javascript">
window.onload=function(){ alert("Error: Could not extract course information. Please try again later."); }
</script> ';
exit;
}
}
$num_rows = $result->num_rows;
I assure you that the local and remote databases are identical. I see no reason why no results are coming back. I did test a few simple temp tables to see if the server wasn't reading those tables for some reason, but they weren't an issue in my tests. I would try with nested subqueries, but it gets so convoluted so quickly that I can't organize it. Maybe there is a better way?
Also, just to clarify the queries aren't failing, they just aren't returning anything when I know that they should.
I apologize for the wall of text, but any help is appreciated.
EDIT: I really don't know which of the queries the problem lies. I do know that I'm probably missing some important information. Part of that lies in my web inexperience. I test locally first because I've got the debugger working, but I honestly don't know how to do remote debugging. I'm using netbeans and xdebug. If someone could suggest a how to get remote debugging set up I would probably be able to come up with some better data. Any suggestions would be helpful
EDIT AGAIN: Found the problem. Embarrassingly enough it was an error in data entry; one of my foreign keys was incorrectly entered. Thanks everybody for pointing me in the right direction.
On having a quick look, your code is stoping the execution of the PHP inappropriately. You should at least the let the remainder to continue. Simply exit out of loop using break; instead.
if(!$result)
{
echo '<script type="text/javascript">
window.onload=function(){ alert("Error: Could not extract course information. Please try again later."); }
</script> ';
break; //exit the loop only NOT THE PHP's Execution
}
Furthermore, check every query individually and run them separately on phpMyAdmin to see, if they are executing correctly. Find the break point and fix the error.
Related
$id = $user['id']; // the ID of the logged in user, we are retrieving his friends
$friends = $db->query("SELECT * FROM friend_requests WHERE accepted='1' AND (user1='".$id."' OR user2='".$id."') ORDER BY id DESC");
while($friend = $friends->fetch_array()) {
$fr = $db->query("SELECT id,profile_picture,age,full_name,last_active FROM users WHERE (id='".$friend['user1']."' OR id='".$friend['user2']."') AND id != '".$id."'")->fetch_array();
echo $fr['age'];
}
I am basically looping through all my friends, and getting information about each one.
How would I ago about optimizing this, I am aware that that it is inefficient to run this query so many times, considering there are thousands of "friends", but I'm not exactly sure how to go about optimizing it. Any help is appreciated, thanks.
That article in the comments is great. You're definitely going to want to figure out how to write the join yourself. Here's my attempt at writing it for you. While you're rewriting the query, you might want to not * columns from friend_requests (or any at all since you're going to use the join). Any column you pull will have to be loaded into memory so any you can avoid pulling will help out. Especially if you're PHP server and your DB server are not on the same machine (less data over the network).
Anyway, here's my shot in the dark:
$id = $user['id'];
$friends = $db->prepare("
SELECT
freq.*
,users.id AS users_id
,users.profile_picture
,users.age
,users.full_name
,users.last_active
FROM friend_requests freq
INNER JOIN users u ON users.id IN (freq.user1,freq.user2) AND freq.id != u.id
WHERE
freq.accepted='1'
AND ? IN (freq.user1,freq.user2
ORDER BY freq.id DESC");
if($friends) {
$friends->bindParam("s",$id);
if($friends->execute()) {
// get_result() only works if you have the MySQL native driver.
// You'll find out real quick if you don't
$myFriends = $friends->get_result();
while($row = $myFriends->fetch_assoc()) {
echo $row['age'];
}
}
}
else {
printf("SQL Error: %s.<br>\n", $friends->error);
}
// cleanup
$friends->close();
quick reference: get_result()
I've posted yesterday an issue with an mySQL update syntax on CodeIgniter in here:
CodeIgniter - MySQL Error 1064 (Update table1 inner join table2(...))
But now after I solved that problem, another one come up. Now the update query doesn't know the new created table. But if I change to a select statement, it works smoothly.
For that reason I've decided to post the full script.
Code:
<?php
$this->load->database();
$query_tbaux='CREATE TABLE IF NOT EXISTS STUDY_LIST_AUX AS (
SELECT DISTINCT p.pat_id, p.pat_custom1 age, p.pat_name,
p.pat_sex, s.study_iuid, p.pat_birthdate, s.accession_no,
s.study_datetime date_s, s.study_desc, s.mods_in_study, s.pk,
c.institution, s.study_block, s.study_urgent,
\'0000-00-00 00:00:00\' AS \'report_date\', \'{null}\' AS \'report_status\',
s.study_tipo,
s.study_src,
s.study_consulta
FROM study s
INNER JOIN patient p ON s.patient_fk = p.pk
INNER JOIN series c ON c.study_fk = s.pk
INNER JOIN rel_users_hosp u ON u.hosp_id = c.institution
WHERE s.study_datetime >= \'2015-04-26 00:00:00\'
AND s.study_datetime <= \'2015-04-30 23:59:59\'
AND s.study_iuid IS NOT NULL
AND u.user_id = \'admin\'
)';
if ($this->db->query($query_tbaux))
{
echo "Q True!<br><br>";
$data = array(
'STUDY_LIST_AUX.report_date' => "DATE_FORMAT(study_report.report_date,'%Y-%m-%d %h:%i:%s')",
'STUDY_LIST_AUX.report_status' => 'study_report.report_status',
);
$this->db->update('STUDY_LIST_AUX, study_report', $data, array('STUDY_LIST_AUX.study_iuid'=>'study_report.study_iuid'));
}
else
{
echo "Q False<br><br>";
};
?>
Display/Error:
Q True!
A Database Error Occurred
Error Number: 1146
Table 'pacsdb.STUDY_LIST_AUX,' doesn't exist
UPDATE STUDY_LIST_AUX, study_report SET
STUDY_LIST_AUX.report_date =
'DATE_FORMAT(study_report.report_date,\'%Y-%m-%d %h:%i:%s\')',
STUDY_LIST_AUX.report_status = 'study_report.report_status' WHERE
STUDY_LIST_AUX.study_iuid = 'study_report.study_iuid'
I've checked phpmyadmin after refresh the page and the table really exists and it contains the data from the select statement.Can you please tell me what mistake I did?
This may cause you real problem.Remove ,study_report
after your table name.Try it
$this->db-
>update('STUDY_LIST_AUX',
$data,
array('STUDY_LIST_AUX.study_iuid'=>
'study_report.study_iuid'));
Pay closer attention.
Table 'pacsdb.STUDY_LIST_AUX,'
See that comma at the end? That should not be there. The error message is right.
The solution was more simple than it looks.
$query_update = "UPDATE STUDY_LIST_AUX
INNER JOIN study_report
SET STUDY_LIST_AUX.report_date = DATE_FORMAT(study_report.report_date,'%Y-%m-%d %h:%i:%s'), STUDY_LIST_AUX.report_status = study_report.report_status
WHERE STUDY_LIST_AUX.study_iuid = study_report.study_iuid";
$this->db->query($query_update);
It seems to be a issue with the CodeIgnigter Framework on the update integrated function ($this->db->update(...)). It doesn't work with sub queries, and the best solution goes for using the normal query execution function ($this->db->update($query))
Anyway, thanks for the help ;) All your answers were very helpful in a way to get to this solution.
I am trying to get a date from my database, but only when certain conditions are met.
I want a table to populate with data from mySQL, only when the data is submitted under a users name. (i.e. this data is relevant to this user.)
This data has been saved as a TIMESTAMP.
$sql = "SELECT * FROM bug LIMIT 100";
$result = mysql_query($sql)or die(mysql_error());
while($row = mysql_fetch_array($result)){
$bdate = $row['bugDate'];
$bfor = $row['bugFor'];
$finduserid= mysql_query
("SELECT UserId FROM user WHERE userName='{$_SESSION['myusername']}'");
if($finduserid)
{
$getuserid = mysql_fetch_assoc($finduserid);
}
$findbdate =
mysql_query("SELECT bugDate FROM bug WHERE bugDate = '$bdate'
AND '$bfor' = '" . $getuserid['UserId'] . "'");
if($findbdate)
{
$getbdate = mysql_fetch_array($findbdate);
}
$bdatetime = new DateTime($getbdate['bugDate']);
$formattedbdate = date_format($bdatetime, 'd,M Y');
If anyone can help me I'd greatly appreciate it.
Obviously the security is terrible and I'm pretty sure this method would be the most inefficient way of doing what I'm trying to do, however I'm a noob and kind of learning by doing. If you have some noob friendly documentation on security and seeing this is making you cringe, feel free to post a link. Any help is greatly appreciated.
(Let me know if you need to know more and sorry if I didn't include it in the first place!)
EDIT: I got it working. I was doing it the most roundabout, ridiculous way anyone could come up with. Although I didn't use JOIN it sent me on the right path. Condensed 250 lines of pointless not working code down to 3-4 that will be obvious to everyone but me.
I selected the row where my session login equalled my loginName on the database.
$finduserid= "SELECT UserId FROM user WHERE userName='{$_SESSION['myusername']}'";
$runuserid = mysql_query($finduserid)or die(mysql_error());
while($getuserid = mysql_fetch_array($runuserid)){
$userid = $getuserid['0'];
}
I then, only Selected records that included my username (instead of everything and then trying to get rid of everything that didn't have my username in it.) -_- (Im an idiot.)
$sql = "SELECT * FROM bug WHERE bugFor = '$userid'";
$result = mysql_query($sql)or die(mysql_error());
Read up on JOINs.
I can't exactly tell what your code is supposed to do, or completely decipher your DB's schema, but the below query should get all bugs for the current user that were filed on the given date:
SELECT b.*
FROM bug b INNER JOIN users u
ON b.bfor = u.userID
WHERE u.userName = '{$_SESSION['myusername']}'
AND b.bugDate = '$bdate'
I never did such PHP/MYSQL tricks to join multitables. Please who has experience in this field Help:
$qry=mysql_query("select {$table_prefix}user_cv.*, {$table_prefix}advertising.* from {$table_prefix}user_cv, {$table_prefix}advertising where {$table_prefix}user_cv.publish='yes' and {$table_prefix}advertising.publish='Y'");
mysql query return 0 results .
$qry = "SELECT {$table_prefix}user_cv.*, {$table_prefix}advertising.*
FROM {$table_prefix}user_cv
LEFT JOIN {$table_prefix}advertising ON {$table_prefix}advertising.publish='Y'
WHERE {$table_prefix}user_cv.publish='yes'";
mysql_query($qry);
I did not test this! I could be wrong but it might be a step in the right direction. (Still new myself)
I have a database listed as $db under mysqli. This database is contains into two tables, I listed them below as table and table2 (just for this example). Table2's rows requires an id from table. This is fine, but there might be a problem adding the columns into table2 thus requiring a rollback routine. However, it doesn't seem to be working.
I started with turning off the auto-commit. I then tried to put in the rollback command even though I am using the die command to signal a failure. As far as I am concerned the transaction could be blasted into oblivion in mid operation and the database should still be stable. So I am not sure what is going on here unless the database is completely ignoring the fact that I am trying to turn off auto-commit.
The basic structure of my code is listed below:
function problem($str)
{
global $db;
mysqli_rollback($db);
die($str);
}
mysqli_autocommit($db,false);
//Basic check if exists
$sqlstr = "SELECT * FROM table WHERE name = '$name';";
$r = mysqli_query($db,$sqlstr);
if (mysqli_num_rows($r)>0){problem("A row already exists under that id");}
//Insert the row
$sqlstr = "INSERT INTO table (name,v1,v2,v3) VALUES ('$name','$v1','$v2','$v3');";
$r = mysqli_query($db,$sqlstr);
if (!$r){problem("Could not insert into the table. $sqlstr");}
//Get the generated id part 1
$sqlstr = "SELECT id FROM table WHERE name = '$name';";
$r = mysqli_query($db,$sqlstr);
if (!$r){problem("Could not add into the table. $sqlstr");}
//Get the generated id part 2
$row = mysqli_fetch_assoc($r);
$eid = $row['id'];
//A simple loop
$count = count($questions);
for ($i=1;i<=$count;$i++)
{
//This is where it typically could die.
$r = mysqli_query($db,"INSERT INTO table2 VALUES (...);");
if (!$r){problem("Could not add to the table2. $sqlstr");}
}
mysqli_commit($db);
Is there something I am missing? I tried to follow the examples I found for the auto-commit as closely as I could.
Transactions only work if the table engine supports them, e.g. InnoDB.