How do I write a SELECT IF statement with 2 conditionals? - php

so I got this PHP code here:
SELECT status , IF(type = '" . mysqli_real_escape_string($con,$type) . "' , type, '') AS status FROM novacorp.status WHERE type = '" . mysqli_real_escape_string($con,$type) . "' LIMIT 1;
I also want to add another conditional to this so it'll only select status if the info column is also equal to something which I pass using escape string just like shown above.
Same for this statement:
UPDATE `novacorp`.`status` SET `status`=". $status ." WHERE `type`='" . mysqli_real_escape_string($con,$type) . "';

IF(type=whatever AND info=other, valueiftrue, valueiffalse)
is probably what you want

Related

How to fix slow query performance using NOT EXISTS MySQL? CodeIgniter

I am trying to optimize / speed up the performance the loading of my data, is there a way to fix this?
I have 3 tables involved:
tbl_tt_college_studentpersonalinfo - This table displays the name of students, it is join in my query
tbl_tt_college_preenrollment - This table displays the pending status of pre-enrolled students
tbl_tt_college_enlistment - This table will check the existing record the student has.
Here is my Query: - The problem that I am having is the load of data is slow, it may take 30-50 seconds. Is there a way to improve this or make it like a join query?
public function get_enlists()
{
$this->db->join('tbl_tt_college_studentpersonalinfo','tbl_tt_college_preenrollment.studentID = tbl_tt_college_studentpersonalinfo.studentID');
$this->db->where('tbl_tt_college_preenrollment.departmentID', $this->input->post('course'));
$this->db->where('tbl_tt_college_preenrollment.yearLevel', $this->input->post('yearLevel'));
$this->db->where("NOT EXISTS (SELECT tbl_tt_college_enlistment.studentKeyID FROM tbl_tt_college_enlistment WHERE tbl_tt_college_enlistment.studentKeyID = tbl_tt_college_preenrollment.studentKeyID AND schoolYear = '" . $this->session->userdata('currentAcademicYear') . '-' . ($this->session->userdata('currentAcademicYear') + 1) . "' AND semester = '" . $this->session->userdata('currentSemester') . "')");
$query = $this->db->get('tbl_tt_college_preenrollment');
return $query->result_array();
}
Here is the raw query for the reference:
NOT EXISTS (
SELECT studentKeyID FROM tbl_tt_college_enlistment
WHERE tbl_tt_college_studentpersonalinfo.studentKeyID = tbl_tt_college_enlistment.studentKeyID
AND schoolYear = '" . $this->session->userdata('currentAcademicYear') . '-' . ($this->session->userdata('currentAcademicYear') + 1) . "'
AND semester = '" . $this->session->userdata('currentSemester') . "'
)
See if this composite index on tbl_tt_college_enlistment helps:
INDEX(schoolYear, semester, studentKeyID)
If not adequate, please provide SHOW CREATE TABLE and EXPLAIN SELECT ...

How do I stop duplicate rows on table join in SQL?

Trying to join this table, so that i can change the code if the tutor ID matches the session tutor ID. But it shows multiple results in the calendar that its generating.
Below is the current PHP code, although the entries are being duplicated due to having multiple tutor ID's within the table. i'm not sure how to change this.
<?php
$sqlAssignments = "SELECT * FROM tbl_assignments LEFT JOIN tbl_tutorModules ON tbl_assignments.module_code = tbl_tutorModules.module_code"; //
$qryAssignments = mysqli_query($con, $sqlAssignments); // running the query
while($rowAssignment = mysqli_fetch_assoc($qryAssignments)){
if ($_SESSION["ID"] == $rowAssignment['tutor_id']) {
echo "{ title: '" . $rowAssignment['assignment_name'] . "', start: '" . $rowAssignment['hand_in_date'] . "', end: '" . $rowAssignment['hand_in_date'] . "', url: 'view/assignments.php?id=" . $rowAssignment['assignment_id'] . "', color: '#f1f1f1'},";
} else {
echo "{ title: '" . $rowAssignment['assignment_name'] . "', start: '" . $rowAssignment['hand_in_date'] . "', end: '" . $rowAssignment['hand_in_date'] . "', url: 'view/assignments.php?id=" . $rowAssignment['assignment_id'] . "'},";
}
}
?>
The actual results at the moment is that when the tutorModules has multiple tutors, the output duplicates calendar results.
Thanks
Edit: Tables look like this with some example data
tbl_tutorModules
con_id module_code tutor_id
2 ISYS30025 1
3 ISYS30025 2
tbl_assignments
assignment_id
module_code
assignment_name
assignment_weight
set_date
hand_in_date
hand_in_method
assignment_type
This is the current output
The expected output is for these not to be duplicated.
You want to know whether a certain tutor is involved in an assignment. So pass the tutor ID to the DBMS in order to let it find out in a query.
SELECT
assignment_id, assignment_name, hand_in_date,
case when module_code in (SELECT module_code FROM tbl_tutorModules WHERE tutor_id = ?)
then 'yes' else 'no'
end as tutor_involved
FROM tbl_assignments
ORDER BY assignment_id;
As you can see, I don't join the tables, because I'm not interested in the joined result. I merely want to look up a record in tbl_tutorModules. We use IN or EXISTS in SQL to look up records in another table.
See here how to pass parameters to the DBMS in mysqli: http://php.net/manual/en/mysqli.prepare.php

PHP + MySQL 3 Condition

so I have this query below in my php code :
$query ="SELECT *
FROM material_tools_master_data
WHERE material_name like '" . $_POST["keyword"] . "%'
ORDER BY material_code
LIMIT 0,50";
It does pretty well and give me a result called 'autocomplete' in my form. The problem is, I wanna make it more complex, I want my autocomplete filter the data selection not only by material_name but also with material_tools_group and show me exactly the material_name which is filtered by material_group = 'Measuring' OR 'Tools'.
The point is, I want to make this query works with my autocomplete. So here is my new query :
$query ="SELECT *
FROM material_tools_master_data
WHERE `material_tools_group` = 'Measuring' OR 'Tools' AND `material_name` like '" . $_POST["keyword"] . "%'
ORDER BY material_code LIMIT 0,50";
The query above is not working, the query above is giving me all the material_name rows in the table.
Any help will be much appreciated.
See warnings about PHP's deprecated API, and the proper use of prepared statements above...
$query ="
SELECT *
FROM material_tools_master_data
WHERE material_tools_group IN('Measuring','Tools')
AND `material_name` LIKE '" . $_POST["keyword"] . "%'
ORDER
BY material_code LIMIT 0,50;
";

Type cast warning for SQL command

I have been stuck on this for a while now, very beginner I know, but couldn't find any similar issues.
I am trying to display my last topic details but I'm getting a warning.
*Warning: pg_exec() [<a href='function.pg-exec'>function.pg-exec</a>]:
Query failed:
ERROR: operator does not exist: character varying = integer LINE 4: WHERE
t_cat = 3 ^
HINT: No operator matches the given name and argument type(s). You
might need to add explicit type casts.*
Any help appreciated
$topicsearh = pg_exec($db,
"SELECT t_id, t_subject, t_date, t_cat
WHERE t_cat = " . $row['s_id'] . "
ORDER BY t_date DESC LIMIT 1"
);
if(!$topicsearh){
echo 'Last topic could not be displayed.';
}
else{
while($trow = pg_fetch_assoc($topicsearh))
echo '<a href="topicview.php?id=' . $trow['t_id'] . '">' . $trow['t_subject'] .
'</a> at ' . date('d-m-Y', strtotime($trow['t_date']));
}
You need to define FROM table.
Example
SELECT t_id, t_subject, t_date, t_cat FROM TABLE_NAME WHERE...
----------^^^^^^^^^^^^^^^-----
and also con-cat as below.
WHERE t_cat = '". $row['s_id'] ."'
While #Dipesh is right about the missing FROM clause, the error at hand points to another problem in your query. t_cat obviously is of type character varying. Therefore you must compare it to a matching string constant. But you are handing in a numeric constant without single quotes.
PHP (or MySQL) traditionally tend to silently swallow such errors and do what they think "is best" (which is not the best they could do). PostgreSQL luckily doesn't. It forces you to be unambiguous.
Should be:
WHERE t_cat = '" . $row['s_id'] . "' ORDER BY t_date DESC LIMIT 1"
instead of:
WHERE t_cat = " . $row['s_id'] . " ORDER BY t_date DESC LIMIT 1"
Read the chapter Constants in the manual, in particular String Constants and Numeric Constants.

Order by Total For Sum function used

<?
$tablae = mysql_query("SELECT * FROM order_history where (type!='rent_referral' AND type!='rental_balance') AND date>'" . strtotime($time1) . "' AND date<'" . strtotime($time2) . "' GROUP BY user_id");
while ($order = mysql_fetch_array($tablae)) {
?>
<tr>
<?
$tablaes = mysql_query("SELECT * FROM members where id='$order[user_id]'");
$user = mysql_fetch_array($tablaes);
$idsd=$user['id'];
$rPaid=mysql_query("SELECT SUM(`price`) AS total FROM order_history WHERE (type!='rent_referral' AND type!='rental_balance') AND date>'" . strtotime($time1) . "' AND date<'" . strtotime($time2) . "'");
$hdPaid = mysql_fetch_array($rPaid);
$sPaid=mysql_query("SELECT SUM(`price`) AS total FROM order_history WHERE user_id='$idsd' AND (type!='rent_referral' AND type!='rental_balance') AND date>'" . strtotime($time1) . "' AND date<'" . strtotime($time2) . "'");
while ($hPaid = mysql_fetch_array($sPaid)) {
?>
<td><?=$user['username']?></td>
<td><?=$hPaid['total']?></td>
<?
}
?>
</tr>
<? } ?>
This gets me this result http://dl.dropbox.com/u/14384295/test.jpeg
I want to order the price totals by DESC.
I would need
$sPaid=mysql_query("SELECT SUM(`price`) AS total FROM order_history WHERE user_id='$idsd' AND (type!='rent_referral' AND type!='rental_balance') AND date>'" . strtotime($time1) . "' AND date<'" . strtotime($time2) . "'");
the total on that to be ordered by DESC.
Be really carefull with GROUP BY instructions in your SQL query. All columns which are in the result and which are not aggregate expressions (expressions would be the count, SUM, max, etc working on the group and not on the rows) should be in your group by expression;
Here you use a select *, you should try to list the real columns instead, and get this list in your group by, or use only SELECT user_id.
Most database would prevent you of running such not-very-well-formted group by query, but MySQl is not bailing you, tthat does not mean he won't gives you completly wrong results if you do not rexpect this rule (all columns which are not aggregates must be in the group by).
Then you should be able to order by an agregate expression by reusing this expression and not his alias in the order clause.
You could either use client side sorting with javascript, there are some nice jQuery addons that can do that.
Or you have to totaly rewrite your code to have a single sql using joins and group by.
But I cannot realy follow the logic with $rPaid, $hPaid and $sPaid so I cannot help you there.

Categories