MySQL query, subquery in codeigniter - php

im using codeigniter as my framework, but i'm not using active records, im having trouble executing this query, it gives me a Error Number 1064
essentialy, im trying to insert a bunch of data to a table, but querying some id numbers from other tables
$titulo = $datos['titulo'];
$tipo = $datos['tipo'];
$autor = $datos['autor'];
$autor2 = $datos['autor2'];
$editorial = $datos['editorial'];
$ano = $datos['ano'];
$paginas = $datos['paginas'];
$descripcion = $datos['descripcion'];
$image_path = 'hola';
$genero = $datos['genero'];
$genero2 = $datos['genero2'];
$sql = "INSERT INTO productos (titulo, autor_id, autor2_id, editorial_id, ano, paginas, genero_id,
genero2_id, tipo, descripcion, image_path)
SELECT ? AS titulo,
id FROM autores WHERE nombre_autor=?,
id FROM autores WHERE nombre_autor=?,
id FROM editoriales WHERE nombre_editorial=?,
? as ano,
? as paginas,
id FROM generos WHERE nombre_genero=?,
id FROM generos WHERE nombre_genero=?,
? as tipo,
? as descripcion,
? as image_path";
if($this->db->query($sql, array($titulo, $autor, $autor2, $editorial, $ano, $paginas, $genero, $genero2, $tipo, $descripcion, $image_path))){
return true;
}else{
return false;
}
can someone help me with this query?
thanks...

A select statement can only have one FROM clause.
http://dev.mysql.com/doc/refman/5.0/en/select.html
Look into using JOIN
http://dev.mysql.com/doc/refman/5.0/en/join.html

This is not a perfect query since I do not know the design of your database, but it should steer you in the right direction as far as the syntax goes.
INSERT INTO productos (titulo, autor_id, autor2_id, editorial_id, ano, paginas, genero_id,
genero2_id, tipo, descripcion, image_path)
SELECT a.titulo, b.id, b.id2, c.id, a.ano, a.paginas, d.id, d.id2, a.tipo, a.description, a.image_path
FROM table_1 a
JOIN table_2 b ON a.autor_id = b.id
JOIN table_3 c ON a.editorial_id = c.id
JOIN table_4 d ON a.genero_id = d.id
WHERE a.id = 25
Essentially this will join all of the data you need into one table before you add into "productos". This is the proper way to do what you need with SQL. Of course, this also depends on the relationships between the tables--in this example I assumed that you had foreign keys in table_1 that referred to data in other tables.
You will then be able to execute this query based on whatever parameters you want/need--just refer to those in the WHERE clause.

Related

Left Join With Null value Table

I was using this query to connect my student table and attendance table,
My Problem is, sometimes, attendance table has no value.
It's not returning any value.
<?php
if($_SERVER['REQUEST_METHOD']=="POST"){
include('include/connection.php');
showData();
}
function showData(){
global $connect;
$teacher_id = $_POST['teacher_id'];
$subject_id = $_POST['subject_id'];
$date = $_POST['date'];
$query ="
SELECT s.student_name
, s.student_number
, s.student_section
, s.subject_id
, s.fingerprint_id
, s.teacher_id
, a.status
FROM tbl_student s
LEFT
JOIN tbl_attendance a
on s.subject_id=a.subject_id
WHERE s.subject_id = '$subject_id'
and a.date='$date'
and s.teacher_id = '$teacher_id';";
$result =mysqli_query($connect,$query);
$number_of_rows = mysqli_num_rows($result);
$temp_array=array();
if($number_of_rows>0){
while($row=mysqli_fetch_assoc($result)){
$temp_array[]=$row;
}
}
header('Content-Type: application/json');
echo json_encode(array("student"=>$temp_array));
mysqli_close($connect);
}
?>
What I want to achive is even if attendance table has no value,
I can still see the student fields.
Is it even possible with SQL query? Thanks
You have to move the fields of table attendance from where to the on condition:
$query ="SELECT student.student_name,student.student_number,student.student_section,student.subject_id,student.fingerprint_id,student.teacher_id,attendance.status
FROM tbl_student student
LEFT JOIN tbl_attendance attendance on student.subject_id=attendance.subject_id and attendance.date='$date'
WHERE student.subject_id='$subject_id' and student.teacher_id='$teacher_id';";
Because first the join Statement will be executed and then the where, if you access the table tbl_attendance in where ans all the columns are null, they will filtered out.
Hint: read about prepared Statements to provide SQL-injection
SELECT student.student_name,student.student_number,student.student_section,student.subject_id,student.fingerprint_id,student.teacher_id,attendance.status
FROM tbl_student student
LEFT JOIN tbl_attendance attendance on student.subject_id=attendance.subject_id and attendance.date='$date'
WHERE student.subject_id='$subject_id' and student.teacher_id='$teacher_id';
Try above code.Hope this will helps.
As you had made condition on student table using attendance.date='$date' on WHERE clause it exclude that record which are not satisfy this condition.
So instead of where i had put that condition through ON clause on LEFT JOIN.
This will achieve your goal.

fetching data from multiple tables with join?

I'm getting started with JOIN and I'm trying to fetch all rows from clasificados and the abrev and nombre column from five of the "JOINED" tables, may be this is not possible but I've being reading about and I thought that it was.
I'm using LIMIT
I'm getting 0 as rowCount. Anyone could guide me please?
$sql2 = "SELECT cl.id AS clasid,
cl.email AS email,
cl.tipo_anuncio AS tipo_anuncio,
cl.reid AS reid,
cl.rcid AS rcid,
cl.img_1 AS img_1,
cl.titulo AS titulo,
cl.precio AS precio,
cl.negociable AS negociable,
cl.estado_art AS estado,
cl.intercambio AS intercambio,
cl.retro AS retro,
cl.id_cat_1 AS id_cat_1,
cl.id_subcat_1 AS id_subcat_1,
cl.id_subcat_2 AS id_subcat_2,
cl.clas_pass AS clasified_key,
cl.user_activo AS user_activo,
cl.approved_pay AS approved,
cl.expiracion AS expiracion,
cl.rep_email_enviado AS rep_email_sent,
eid.abrev AS edm_abrev,
cid.nombre AS cdm_nombre,
negoc.nombre AS neg,
exch.nombre AS exchangable,
estadoTB.nombre AS estado_articulo
FROM clasificados AS cl
JOIN 1_ AS cat_one
ON cat_one.id = cl.id_cat_1
JOIN estados AS eid
ON eid.id = cl.reid
JOIN municipios AS cid
ON cid.id = cl.rcid
JOIN negociable_tb AS negoc
ON negoc.id = cl.negociable
JOIN intercambio_tb AS exch
ON exch.id = cl.intercambio
JOIN estado_articulo_tb AS estadoTB
ON estadoTB.id = cl.estado_art
WHERE cl.user_activo = 1 AND cl.approved_pay = 1 ORDER BY cl.id DESC LIMIT $position, $items_per_group";

Convert this MySQL Query to Codeigniter Active Record

I have got two tables :
Dress (dress_id, title)
Dress_comment (comment_id, dress_id, comment)
I have been trying from hours now and unable to convert this query into the corresponding Codeigniters' Active Class Record functions.
Here is the query :
SELECT d.dress_id, d.title, COALESCE(dc.count, 0)
FROM dress d
JOIN (select dress_id, count(comment_id) as count from dress_comment group by dress_id) dc
ON d.dress_id = dc.dress_id
ORDER BY d.dress_id;
This is what I have tried till now :
//Creating the select subquery for the inner join
$this->db->select('dress_id, count(comment_id) as count')
->from('Dress_comment')
->group_by('dress_id')
->get();
$subQuery = $this->db->last_query();
//Main Query
$this->db->select('d.dress_id, d.title, COALESCE(dc.count,0)')
->from('Dress')
->join($subQuery . ' dc','dc.dress_id = d.dress_id','left')
->order_by('d.dress_id');
$result = $this->db->get();
return $result->result_array();
But Codeigniter is not running this query and always giving mysql syntax error. The sql format that codeigniter is converting this active methods to is
SELECT `d`.`dress_id`, `d`.`title`, COALESCE(dc.count, `0)`
FROM (`Dress`) LEFT JOIN `SELECT` `dress_id`, count(comment_id) as count
FROM (`Dress_comment`)
GROUP BY `dress_id` dc
ON `dc`.`dress_id` = `d`.`dress_id`
ORDER BY `d`.`dress_id`
I was able to solve the problem using the mysql query in the join function like this :
$this->db->select('d.dress_id, d.title, dc.count as comments, dl.count as likes, dt.title, di.image_url')
->from('Dress d')
->join('(select dress_id, count(comment_id) as count from dress_comment group by dress_id) dc','dc.dress_id = d.dress_id','left')
->order_by('d.dress_id');

Inner/Left join with two different where clauses

i'm in the process of joining two tables together under two different conditions. For primary example, lets say I have the following nested query:
$Query = $DB->prepare("SELECT ID, Name FROM modifications
WHERE TYPE =1 & WFAbility = '0'");
$Query->execute();
$Query->bind_result($Mod_ID,$Mod_Name);
and this query:
$Query= $DB->prepare("SELECT `ModID` from `wfabilities` WHERE `WFID`=?");
$Query->bind_param();
$Query->execute();
$Query->bind_result();
while ($Query->fetch()){ }
Basically, I want to select all the elements where type is equal to one and Ability is equal to 0, this is to be selected from the modifications table.
I further need to select all the IDs from wfabilities, but transform them into the names located in modifications where WFID is equal to the results from another query.
Here is my current semi-working code.
$Get_ID = $DB->prepare("SELECT ID FROM warframes WHERE Name=?");
$Get_ID->bind_param('s',$_GET['Frame']);
$Get_ID->execute();
$Get_ID->bind_result($FrameID);
$Get_ID->fetch();
$Get_ID->close();
echo $FrameID;
$WF_Abilties = $DB->prepare("SELECT ModID FROM `wfabilities` WHERE WFID=?");
$WF_Abilties->bind_param('i',$FrameID);
$WF_Abilties->execute();
$WF_Abilties->bind_result($ModID);
$Mod_IDArr = array();
while ($WF_Abilties->fetch()){
$Mod_IDArr[] = $ModID;
}
print_r($Mod_IDArr);
$Ability_Name = array();
foreach ($Mod_IDArr AS $AbilityMods){
$WF_AbName = $DB->prepare("SELECT `Name` FROM `modifications` WHERE ID=?");
$WF_AbName->bind_param('i',$AbilityMods);
$WF_AbName->execute();
$WF_AbName->bind_result($Mod_Name);
$WF_AbName->fetch();
$Ability_Name[] = $Mod_Name;
}
print_r($Ability_Name);
See below:
SELECT ModID,
ID,
Name
FROM modifications M
LEFT JOIN wfabilities WF
ON WF.ModID = M.ID
WHERE TYPE =1 & WFAbility = '0'
To do this, you need to join your tables, I'm not quite sure what you are trying to do so you might have to give me more info, but here is my guess.
SELECT ID, Name, ModID
FROM modifications
JOIN wfabilities
ON WFID = ID
WHERE TYPE = '1'
AND WFAbility = '0'
In this version I am connecting the tables when WFID is equal if ID. You will have to tell me exactly what is supposed to be hooking to what in your requirements.
To learn more about joins and what they do, check this page out: MySQL Join
Edit:
After looking at your larger structure, I can see that you can do this:
SELECT modifications.Name FROM modifications
JOIN wfabilities on wfabilities.ModID = modifications.ID
JOIN warframes on warframes.ID = wfabilities.WFID
WHERE warframes.Name = 'the name you want'
This query will get you an array of the ability_names from the warframes name.
This is the query:
"SELECT A.ID, A.Name,B.ModID,C.Name
FROM modifications as A
LEFT JOIN wfabilities as B ON A.ID = B.WFID
LEFT JOIN warframes as C ON C.ID = B.WFID
WHERE A.TYPE =1 AND A.WFAbility = '0' AND C.Name = ?"

Help construct a simple query Using 3 tables

Hey guys need some more help
I have 3 tables USERS, PROFILEINTERESTS and INTERESTS
profile interests has the two foreign keys which link users and interests, they are just done by ID.
I have this so far
$statement = "SELECT
InterestID
FROM
`ProfileInterests`
WHERE
userID = '$profile'";
Now I want it so that it selects from Interests where what it gets from that query is the result.
So say that gives out 3 numbers
1
3
4
I want it to search the Interests table where ID is = to those...I just don't know how to physically write it in PHP...
Please help.
Using a JOIN:
Best option if you need values from the PROFILEINTERESTS table.
SELECT DISTINCT i.*
FROM INTERESTS i
JOIN PROFILEINTERESTS pi ON pi.interests_id = i.interests_id
WHERE pi.userid = $profileid
Using EXISTS:
SELECT i.*
FROM INTERESTS i
WHERE EXISTS (SELECT NULL
FROM PROFILEINTERESTS pi
WHERE pi.interests_id = i.interests_id
AND pi.userid = $profileid)
Using IN:
SELECT i.*
FROM INTERESTS i
WHERE i.interests_id IN (SELECT pi.interests_id
FROM PROFILEINTERESTS pi
WHERE pi.userid = $profileid)
You are on the right track, lets say you execute the query above using this PHP code:
$statement = mysql_query("SELECT InterestID FROM `ProfileInterests`
WHERE userID = '$profile'");
Then you can use a PHP loop to dynamically generate an SQL statement that will pull the desired IDs from a second table. So, for example, continuing the code above:
$SQL = "";
while ($statementLoop = mysql_fetch_assoc($statement)) {
//Note the extra space on the end of the query
$SQL .= "`id` = '{$statementLoop['InterestID']}' OR ";
}
//Trim the " OR " off the end of the query
$SQL = rtrim($SQL, " OR ");
//Now run the dynamic SQL, using the query generated above
$query = mysql_query("SELECT * FROM `table2` WHERE {$SQL}")
I haven't tested the code, but it should work. So, this code will generate SQL like this:
SELECT * FROM `table2` WHERE `id` = '1' OR `id` = '3' OR `id` = '4'
Hope that helps,
spryno724
Most likely you want to join the tables
select
i.Name
from
ProfileInterests p
inner join
interests i
on
p.interestid = i.interestid
where
p.userid = 1

Categories