php using result from previous query in another query - php

I need to grab a result from one query and pop it into another.
first query
$query = 'SELECT * FROM singleprop.jos_mls WHERE MSTMLSNO = ' . $mlsnum . ';';
$result = mysql_query($query);
$row = mysql_fetch_row($result);
second query
$aquery = 'SELECT * FROM singleprop.jos_agents WHERE AGTBRDIDMM = ' . $row[0] . ';';
$aresult = mysql_query($aquery);
$agent = mysql_fetch_row($aresult);
I know about JOIN, but don't know how to apply it with a 3rd table. Does my model have something to do with $this->?

The code looks good. You could write a query using join, which you are aware of. What is the question?
SELECT *
FROM singleprop.jos_mls as mls JOIN singleprop.jos_agents
ON singleprop.jos_mls.KEY = singleprop.jos_agents.KEY
WHERE mls.MSTMLSNO = $mlsnum
where KEY is the join key
OR
SELECT *
FROM singleprop.jos_agents
WHERE AGTBRDIDMM = (
SELECT COL_NAME
FROM singleprop.jos_mls
WHERE MSTMLSNO = ' . $mlsnum . '
)
where COL_NAME is the column name for AGTBRDIDMM in the first table

Related

php mysql query adds quotes in the end

I have set up a query as such:
$query = 'SELECT SGC.sys_id, TBL.semester, SGC.bonus, SGC.exam, SGC.ca FROM SubjectGradeComponent AS SGC, ';
$query .= '(SELECT `sys_id`, `semester` FROM AcademicYearTerm AS AYT, SubjectYearTermLevel AS SYTL WHERE academic_year = "' . $academic_year . '" AND SYTL.subject_id = ' . $subject_id . ' AND SYTL.form_level = ' . $form_level. ' AND SYTL.yearTerm_id = AYT.yearTerm_id) AS TBL ';
$query .= 'WHERE SGC.sys_id = TBL.sys_id;';
However when I run the query, $mysql->query($query);it returns an empty result with 0 rows. Running the same query on phpmyadmin shows the desired result. I have looked around but do not understand the problem.
$mysql->error does not show any error message either
EDIT:
generated query is like this:
SELECT SGC.sys_id, TBL.semester, SGC.bonus, SGC.exam, SGC.ca FROM SubjectGradeComponent AS SGC, (SELECT `sys_id`, `semester` FROM AcademicYearTerm AS AYT, SubjectYearTermLevel AS SYTL WHERE academic_year = "2018-2019" AND SYTL.subject_id = 1 AND SYTL.form_level = 1 AND SYTL.yearTerm_id = AYT.yearTerm_id) AS TBL WHERE SGC.sys_id = TBL.sys_id;""
Question is where are the "" from?
Looks like you want a JOIN query instead.
You should also use prepared statement with placeholders ? instead of injecting values directly into the query.
$query = "SELECT SGC.sys_id,
AYT.semester,
SGC.bonus,
SGC.exam,
SGC.ca
FROM SubjectGradeComponent AS SGC
JOIN AcademicYearTerm AS AYT
ON SGC.sys_id = AYT.sys_id
JOIN SubjectYearTermLevel AS SYTL
ON SYTL.yearTerm_id = AYT.yearTerm_id
WHERE academic_year = ?
AND SYTL.subject_id = ?
AND SYTL.form_level = ?";

SQL Join Statement To Update an Entire Column with PHP Loop

I need to update an entire column with new unique phone numbers that live in a second table. I seem to be on the right track... but my loop logic is faulty.
I'm returning the matches correctly as far as I can tell, but when I try to update the entire column in the table it inserts the last phone number in every single row.
$query = "SELECT matched.duns, matched.new_p1, users_data.temp_duns
FROM matched
INNER JOIN users_data ON temp_duns
WHERE temp_duns = duns LIMIT 10";
$result = mysqli_query($connection, $query);
foreach ($result as $key => $val) {
if($val['duns'] === $val['temp_duns']) {
$final_query = "UPDATE users_data SET phone_number = " . $val['new_p1'];
$final_result = mysqli_query($connection, $final_query);
echo $counter . "DUNS From matched: " . $val['duns'] . " DUNS From users_data: " . $val['temp_duns'] . " NEW PHONE: ". $val['new_p1']. "<br>";
}
}
I'm a total newb but any help would be appreciated.
Simply run an update query in one call without looping and in MySQL INNER JOIN can be used:
UPDATE user_data u
INNER JOIN matched m ON u.temp_duns = m.temp_duns
SET u.phone_number = m.new_p1;
Or for the limit of 10:
UPDATE user_data u
INNER JOIN (SELECT * FROM matched LIMIT 10) m ON u.temp_duns = m.temp_duns
SET u.phone_number = m.new_p1;
The problem is that your query doesn't have a WHERE clause, so it's updating every row.
"UPDATE users_data SET phone_number = " . $val['new_p1'];
You need to limit it to just the row that you want to update.
"UPDATE users_data SET phone_number = " . $val['new_p1'] . " WHERE some_id = " . $some_id;
You could probably do the whole thing in a single query.
UPDATE table_to_be_updated
JOIN table_with_value_we_need ON whatever_joins_them
SET table_to_be_updated.column_we_want_to_fill = table_with_value_we_need.value_we_need;

PHP displaying data from four tables in one query (ie: LEFT JOIN)

I have three tables:
I want to display 'Event Details' which shows attending employee details (listo f employee ids from the 'attending_employees table > corresponding employee details form 'employee' table), what team they belong to (from the club_teams table) and the event details from the 'club_events' table).
Currently I am using multiple mysqli queries to display this information however cannot get my head around pulling the data from the database in one query (ie: LEFT JOIN). Your assistance would be greatly appreciated!
Below are the queries i am currently using:
$query = msqli_query($con, "SELECT * FROM attending_employees")or die(mysqli_error($con));
if(mysqli_num_rows($query) > 0){
while($attending = mysqli_fetch_array($query)){
foreach($attending['club_event']){
$eventid = $attending['club_event'];
$query = msqli_query($con, "SELECT * FROM club_events WHERE club_event_id = '$eventid'")or die(mysqli_error($con));
while($event_details = mysqli_fetch_array($query)){
// Echo event details
}
}foreach($attending['employee']){
$empid = $attending['employee'];
$query = msqli_query($con, "SELECT * FROM employees WHERE employee_id = '$empid'")or die(mysqli_error($con));
while($event_employees = mysqli_fetch_array($query)){
// Echo employee details
}
}foreach($attending['team']){
$teamid = $attending['team'];
$query = msqli_query($con, "SELECT * FROM club_teams WHERE clb_team_id = '$teamid'")or die(mysqli_error($con));
while($event_team = mysqli_fetch_array($query)){
// Echo team details
}
}
}
}
This method is highly inefficient and wasteful since its retrieving duplicate data (ie: all repeated 'club_event_id's in the 'attending_employees' table.)
Try this:
$query = msqli_query(
$con,
"SELECT"
. " attending_employees.*"
. ", club_events.*"
. ", employees.*"
. ", club_teams.*"
. " FROM"
. " attending_employees"
. " LEFT JOIN club_events ON club_events.club_event_id = attending_employees.club_event"
. " LEFT JOIN employees ON employees.employee_id = attending_employees.employee"
. " LEFT JOIN club_teams ON club_teams.clb_team_id = attending_employees.team"
) or die(mysqli_error($con));

How to get sum of a column in Zend framework using model and controller

I am looking for a way to get the sum of a column. The query i am using looks like this:
public function gradeRound($rating)
{
$sql = mysql_query("Select SUM(rating) AS grades FROM" . $this->_prefix . "media_set_rating WHERE set_id = set_id");
mysql_real_escape_string($rating->rating);
$row = mysql_fetch_assoc($sql);
$grades = $row['grades'];
}
I am not sure how to get this properly formatted for the controller. right now my controller has this.
i put a text box on the page and echoed $grades - this is also included in the view as so:
$this->_view->assign('grades', $grades);
so that i can use it.
I tried replacing $setId with $rating both of which are being requested at the top.
I do not get anything out of my echo. I had -1 in there earlier. i am not sure where it was getting that from. I was trying different methods and got different results.
appreciate any hints or clues as to how to do this.
thanks
Revised 2:17 EST May 27 2013
Thanks Niko. I must be getting tired!
Here is the revised query:
public function gradeRound($rating)
{
$sql = sprintf("Select SUM(rating) AS grades FROM " . $this->_prefix . "media_set_rating
WHERE set_id = set_id");
$sum = mysql_query($sql);
$row = mysql_fetch_assoc($sum);
$grades = $row['grades'];
return $grades;
}
$grades = $setDao->gradeRound($setId);
Your SQL query looks rather odd. Depending on the type of "set_id", it is supposed to look like this:
mysql_query("
Select SUM(rating) AS grades
FROM " . $this->_prefix . "media_set_rating
WHERE set_id = '". mysql_real_escape_string($rating->rating) ."'"
);
for ยด$rating->rating` being a string. For an integer, it should be:
mysql_query("
Select SUM(rating) AS grades
FROM " . $this->_prefix . "media_set_rating
WHERE set_id = ". (int) $rating->rating
);
And in total (adding also a return statement):
public function gradeRound($rating)
{
// expecting "set_id" to be an integer field
$result = mysql_query("Select SUM(rating) AS grades FROM " . $this->_prefix . "media_set_rating WHERE set_id = ". (int) $rating->rating);
$row = mysql_fetch_assoc($result);
return $row['grades'];
}
Hope this will help You !
$select = $table->select();
$select->from ("table", array("date", "column1" => "sum(column1)"));
$select->group ( array ("date") );

Optimize this SQL query

I've got a SQL query within a foreach loop. Sometimes there can be many, and I mean a lot of queries to do, depending on several criteria, up to 78 queries potentially.
Now, I know that premature optimisation is root cause of all evil, but I don't want to see 78 queries - it's just not healthy.
Here's the code:
$crumbs = explode(",", $user['data']['depts']);
foreach ($crumbs as &$value) {
$data = $db->query("SELECT id FROM tbl_depts WHERE id = '" . $value . "'");
$crumb = $data->fetch_assoc();
$dsn = $db->query("SELECT msg, datetime FROM tbl_motd WHERE deptid = '" . $value . "'");
$motd = $dsn->fetch_assoc();
if ($motd['msg'] != "") {
<?php echo $motd['msg']; ?>
}
}
Can I make it any better?
Use IN MySQL operator to search over a set of values for id:
$ids = '"' . implode('", "',$crumbs) . '"';
$query1 = "SELECT id FROM tbl_depts WHERE id IN (" . $ids . ")";
$query2 = "SELECT msg, datetime FROM tbl_motd WHERE deptid IN (" . $ids . ")";
And so you will not need to retrieve all data you need using foreach loop, so you will have only 2 queries instead of 78.
Example: I have a table named table with 10 records which ids are: 1,2,3,4,5,6,7,8,9,10 (auto-incremented). I know I need records with ids 1,5,8. My query will be:
$sql = "SELECT * FROM `table` WHERE id in (1,5,8);";
And I don't understand why do you need to use & operator in foreach loop if you don't modify the $crubms arrays values.
I think this is want you want.
SELECT msg, datetime
FROM tbl_depts td
INNER JOIN tbl_motd tm ON td.id = tm.deptid

Categories