I need to do a PHP PDO call to my db with an INNER JOIN and WHERE clause.
In navicat GUI this statement is running fine and i can see the results. The problem come out lather in php environment about string concatenation.
I would like to format this request so that it can be digested by php:
SELECT * FROM tsourcetb as T INNER JOIN users as U ON U.username = T.username WHERE U.username = $username AND T.username = $username;
what I tried to do
$sth = $db->prepare("SELECT * FROM tsourcetb as T INNER JOIN users as U ON U.username = T.username WHERE U.username = $username AND T.username = $username");
the return is an error indicating that there is no table with the variable name. Basically it takes the variable as the name of the table the return is an error indicating that there is no table with the variable name. Basically it takes the variable as the table name and not the table name as it should like (SELECT * FROM $username) jumping out the first part of statement).
The intent is to have all the records of table A where the username field is = to the username field of table B with value passed from a variable.
Thank for any suggestion to achieve my goal.
UPDATE
php is magic need to try and retray. At the end tish one help me to goal:
$username = ($_POST['username']);
$password = ($_POST['password']);
$statement = $db->prepare('SELECT p.* FROM `tsourcetb` as p LEFT JOIN `users`as s ON p.username = s.username WHERE s.username = :username;');
$statement->bindParam(':username', $username, PDO::PARAM_STR);
$statement->execute();
/* look here -> $statement->fetchall(PDO::FETCH_ASSOC) */
$array_select = $statement->fetchall(PDO::FETCH_ASSOC);
echo json_encode($array_select, JSON_PRETTY_PRINT);
<?php
$sth = $db->prepare("SELECT * FROM `tsourcetb` as T INNER JOIN users as U ON U.username = T.username WHERE U.username = ? AND T.username = ? ");
$sth->execute([$username,$username]);
$results = $sth->fetchall();
?>
wrapper your table name with backticks and also use placeholders
Try this:
$stmt = $db->prepare("SELECT * FROM tsourcetb as T INNER JOIN users as U ON U.username = T.username WHERE U.username = :username AND T.username = :username");
$stmt->bindValue(':username', $username, PDO::PARAM_STR);
$stmt->execute();
You need to bind a value with prepared statement:
Source: Docs
You have to bind parameters when you are making an dynamic query with PDO.
Change this in your query.
$username -> :username
And before you make the call
$yourQueryObj->bindValue(':username', $username, PDO::PARAM_STR);
That's why prepared statments are safer than regular variables as you assign it's type before it's sent for query.
You can read about it here
http://php.net/manual/en/pdostatement.bindvalue.php
You should be able also execute with array of parameters after preparing like that :
$sth = execute(array(':username'=> $username));
I am trying to do a multi query using prepared statements.
I am getting number of bind param errors :
Warning: mysqli_stmt::bind_param(): Number of variables doesn't match number of parameters in prepared statement in C:\wamp\www\c\index.php on line 35
Line 35 is:
$stmt->bind_param('i', $user_id);
Here is total codes:
I tried several examples but couldnt make it work.
Example 1:
$stmt->bind_param('i', $id); //output id from session
Example 2:
$stmt->bind_param('ii',$id, $user_id);
And some more tries too.
$id = $_SESSION['id']; // value comes from session and its full
$stmt = $mysqli->prepare("SELECT users.*, stores.*, products.* FROM stores, products, users WHERE users.id = ? AND stores.user_id = ? AND products.user_id = ?");
$stmt->bind_param('i', $user_id);
$stmt->execute();
$stmt->bind_result($id, $user_id, $pname);
$stmt->fetch();
$stmt->close();
echo $pname;
When I do queries in phpmyadmin codes works fine on $sql as following 2 queries:
$sql = "SELECT users.*, stores.*, products.*\n"
. "FROM stores, products, users\n"
. "WHERE ((users.id) AND (stores.user_id) AND (products.user_id))";
AND without php code
SELECT users.*, stores.*, products.*
FROM stores, products, users
WHERE ((users.id)
AND (stores.user_id)
AND (products.user_id))
This is the closest example :
I am having error:
Warning: mysqli_stmt::bind_result(): Number of bind variables doesn't match number of fields in prepared statement in C:\wamp\www\c\index.php on line 37
Line 37 is :
$stmt->bind_result($user_id, $username, $pname);
$id = $_SESSION['id'];
Closest code :
$stmt = $mysqli->prepare("SELECT users.*, stores.*, products.* FROM stores, products, users WHERE users.id = stores.user_id AND stores.user_id = products.user_id AND products.user_id = ?");
$stmt->bind_param('i', $id);
$stmt->execute();
$stmt->bind_result($user_id, $username, $pname);
$stmt->fetch();
$stmt->close();
echo $pname;
Your prepared statement contains 3 questionmarks/placeholder. So you have to bind exactly 3 values.
I think this should work:
$stmt = $mysqli->prepare("SELECT users.*, stores.*, products.* FROM stores, products, users WHERE users.id = ? AND stores.user_id = ? AND products.user_id = ?");
$stmt->bind_param('iii', $user_id, $user_id, $user_id);
See examples at: http://php.net/manual/de/mysqli-stmt.bind-param.php
Here is working sample of the code, I had to change:
SELECT users.*, stores.*, products.* FROM
To
SELECT users.id, users.username, stores.user_id, stores.name, products.user_id, products.pname FROM
And rest of the code like so: and its working now, I wouldlike to know if its safe to use on a live and dynamic website ?
Can someone correct the code please.
Here is total working code
$id = $_SESSION['UserId'];
$stmt = $mysqli->prepare("SELECT users.id, users.username, stores.user_id, stores.name, products.user_id, products.pname
FROM stores, products, users
WHERE users.id = ?
AND stores.user_id = users.id
AND products.user_id = users.id");
$stmt->bind_param('i', $id);
$stmt->execute();
$stmt->bind_result($id, $username, $user_id, $name, $user_id, $pname);
$stmt->fetch();
$stmt->close();
echo $pname;
echo"<br>" .$name;
echo "<br>".$username;
I tried INNER JOIN AND LEFT JOIN (Mentioned in comment) but couldnt made both. work
EDİT :
Same query with INNER JOIN its working.
$sid = $_SESSION['UserId'];
$stmt = $mysqli->prepare("SELECT u.id, u.username, s.user_id, s.name, p.user_id, p.pname FROM stores AS s INNER JOIN products AS p ON p.store_id = s.store_id INNER JOIN users AS u ON u.id = p.user_id WHERE s.user_id = ?");
$stmt->bind_param('i', $sid);
$stmt->execute();
$stmt->bind_result($id, $username, $user_id, $name, $user_id, $pname);
$stmt->fetch();
$stmt->close();
echo $pname;
echo"<br>" .$name;
echo "<br>".$username;
I have a hard problem to solve and I don't know how to do it.
I want to archive some entities and then delete them from initial tables. Problem is these entities are linked together. I have a code which is close to working but I think it's not a clean way to do it. It's composed of SQL queries which copy rows with their IDs to new tables.
Another problem is that I don't need some fields to archive so archive entities are not exactly the same as initial entities.
I'm using raw SQL query and not DQL because of the size of my tables.
I want to archive these entities : Colle, ColleQC, QC, PasserColle, Reponse, ReponseQC, StatistiqueColle, StatistiqueQuestion, RepartitionColle, RepartitionQuestion, Tuteur
TO
BanqueColle, BanqueColleQC, BanqueQC, BanquePasserColle, BanqueReponse, BanqueReponseQC, BanqueStatistiqueColle, BanqueStatistiqueQuestion, BanqueRepartitionColle, BanqueRepartitionQuestion, AncienAdherent.
I'll use these archive for another part of my app.
Sample of table structure :
(Tuteur and AncienAdherent extend User)
Here's a part of the code I made to archive but I don't think it's a clean way to do it :
public function archiveTuteurs() {
$db = $this->em->getConnection();
$query = "INSERT INTO ancien_adherent (id)
SELECT u.id
FROM user u
WHERE discr = 'tuteur'";
$stmt = $db->prepare($query);
$stmt->execute();
$query2 = "UPDATE user
SET user.discr = 'ancien'
WHERE discr = 'tuteur'";
$stmt = $db->prepare($query2);
$stmt->execute();
return true;
}
public function archiveColles() {
$db = $this->em->getConnection();
$query = "INSERT INTO banque_colle (id, typeColle, nom, temps_epreuve, matiere_id, dateCreation, ordre, discr)
SELECT colle.id, colle.typeColle, colle.nom, colle.temps_epreuve, colle.matiere_id, colle.dateCreation, colle.ordre, colle.discr
FROM colle";
$stmt = $db->prepare($query);
$stmt->execute();
$query2 = "INSERT INTO banque_colle_qc (id)
SELECT colle_qc.id
FROM colle_qc";
$stmt = $db->prepare($query2);
$stmt->execute();
return true;
}
public function archiveQC() {
$db = $this->em->getConnection();
$query = "INSERT INTO banque_qc (id, titre, id_colle, ordre, qcPere, enonce, donnees, item1, item2, item3, item4,
item5, corrige_item1, corrige_item2, corrige_item3, corrige_item4, corrige_item5, item1_vrai,
item2_vrai, item3_vrai, item4_vrai, item5_vrai, item1_annule, item2_annule, item3_annule,
item4_annule, item5_annule, multiple_choices, inclu)
SELECT qc.id, qc.titre, qc.id_colle, qc.ordre, qc.qcPere, qc.enonce, qc.donnees, qc.item1, qc.item2,
qc.item3, qc.item4, qc.item5, qc.corrige_item1, qc.corrige_item2, qc.corrige_item3, qc.corrige_item4,
qc.corrige_item5, qc.item1_vrai, qc.item2_vrai, qc.item3_vrai, qc.item4_vrai, qc.item5_vrai,
qc.item1_annule, qc.item2_annule, qc.item3_annule, qc.item4_annule, qc.item5_annule,
qc.multiple_choices, qc.inclu
FROM qc
ORDER BY qc.qcPere ASC";
$stmt = $db->prepare($query);
$stmt->execute();
return true;
}
public function archivePassages() {
$db = $this->em->getConnection();
$query = "INSERT INTO banque_passer_colle (colle_id, dateDebut, note)
SELECT passer_colle.colle_id, passer_colle.dateDebut, passer_colle.note
FROM passer_colle";
$stmt = $db->prepare($query);
$stmt->execute();
return true;
}
public function archiveReponses() {
$db = $this->em->getConnection();
$query = "INSERT INTO banque_reponse (id, discr)
SELECT reponse.id, reponse.discr
FROM reponse
WHERE discr='reponseQC'";
$stmt = $db->prepare($query);
$stmt->execute();
$query2 = "INSERT INTO banque_reponse_qc (id, question, A, B, C, D, E, note)
SELECT reponse_qc.id, reponse_qc.question, reponse_qc.A, reponse_qc.B, reponse_qc.C, reponse_qc.D,
reponse_qc.E, reponse_qc.note
FROM reponse_qc";
$stmt = $db->prepare($query2);
$stmt->execute();
return true;
}
public function archiveStats() {
$db = $this->em->getConnection();
$query = "INSERT INTO banque_statistiquecolle (id, colle_id, effectif, moyenne, mediane, note100, major, minor)
SELECT sc.id, sc.colle_id, sc.effectif, sc.moyenne, sc.mediane, sc.note100, sc.major, sc.minor
FROM statistiquecolle_groupe scg
LEFT JOIN statistiquecolle sc ON sc.id = scg.statistiquecolle_id
WHERE scg.groupe_id = 1
AND sc.id NOT IN (SELECT sc1.id
FROM statistiquecolle_groupe scg1
LEFT JOIN statistiquecolle sc1 ON sc1.id = scg1.statistiquecolle_id
WHERE scg1.groupe_id != 1)";
$stmt = $db->prepare($query);
$stmt->execute();
$query2 = "INSERT INTO banque_statistiquequestion (id, question_id, moyenne, nbReponseTot, nbReponseA, nbReponseB,
nbReponseC, nbReponseD, nbReponseE)
SELECT sq.id, sq.question_id, sq.moyenne, sq.nbReponseTot, sq.nbReponseA, sq.nbReponseB, sq.nbReponseC,
sq.nbReponseD, sq.nbReponseE
FROM statistiquequestion_groupe sqg
LEFT JOIN statistiquequestion sq ON sq.id = sqg.statistiquequestion_id
WHERE sqg.groupe_id = 1
AND sq.id NOT IN (SELECT sq1.id
FROM statistiquequestion_groupe sqg1
LEFT JOIN statistiquequestion sq1 ON sq1.id = sqg1.statistiquequestion_id
WHERE sqg1.groupe_id != 1)";
$stmt = $db->prepare($query2);
$stmt->execute();
$query3 = "INSERT INTO banque_repartitioncolle (id, statColle_id, note, nombre, percentOfEffectif)
SELECT rc.id, rc.statColle_id, rc.note, rc.nombre, rc.percentOfEffectif
FROM repartitioncolle rc
WHERE rc.statColle_id IN (SELECT bsc.id
FROM banque_statistiquecolle bsc)";
$stmt = $db->prepare($query3);
$stmt->execute();
$query4 = "INSERT INTO banque_repartitionquestion (id, statQuestion_id, note, nombre, percentOfEffectif)
SELECT rq.id, rq.statQuestion_id, rq.note, rq.nombre, rq.percentOfEffectif
FROM repartitionquestion rq
WHERE rq.statQuestion_id IN (SELECT bsq.id
FROM banque_statistiquequestion bsq)";
$stmt = $db->prepare($query4);
$stmt->execute();
return true;
}
I've been doing a database migration recently, and have found that the easiest method (for me) is to do everything in SQL. It's a bit laborious, but it worked okay for my project
First drop all the constraints
# Table1.field1
ALTER TABLE Table1 DROP FOREIGN KEY FK_Table1_field1;
ALTER TABLE Table1 DROP INDEX IDX_Table1_field1;
# Table1.field2
ALTER TABLE Table1 DROP FOREIGN KEY FK_Table1_field2;
ALTER TABLE Table1 DROP INDEX IDX_Table1_field2;
Then add all the SQL you have to move the data into the new tables.
Then drop all the old tables
DROP TABLE IF EXISTS Table1;
DROP TABLE IF EXISTS Table2;
Then Add all the constraints back in
ALTER TABLE Table1
ADD INDEX IDX_Table1_field1 (field1 ASC);
ALTER TABLE Table1
ADD CONSTRAINT FK_Table1_field1
FOREIGN KEY (field1)
REFERENCES OtherTable (xxxx)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
I kept each step in it's own sql file, so for this example there would be 4 sql files, might be easier to manage if you split up the data move step into more than one file as well.
I have simple prepared statement, and i can't find solution to bind list of id's, so as you can see in first statement i get all ids that i need, and in next statement i need to put all those ids into IN clause, but i'm not able to do it, any suggestions how and what is best way to do it ?
$stmt = $mysqli->prepare("SELECT id FROM user WHERE groupId = ? ORDER BY id LIMIT ? OFFSET ?");
$stmt->bind_param("iii", $args['groupId'], $pageSize, $offset);
$stmt->execute();
$stmt->bind_result($id);
$userIds= array();
while ($stmt->fetch()) {
$userIds[] = $id;
}
$stmt= $mysqli->prepare("SELECT a.id as attendantId, a.firstName, a.lastName, c.id as caringId, c.startDate, c.endDate FROM attendant a LEFT JOIN caring c ON c.attendantId = a.id WHERE a.id IN (?)");
$stmt->bind_param('i', $userIds);
$stmt->bind_param('i', implode(',', $userIds));
This is my code. I execute then nothing happen. Pls check my code
$id = trim(htmlentities($_REQUEST['id'],ENT_QUOTES)); //call the action from previous page
//fetch data
$stmt = $dbi->prepare("SELECT a.telco, a.no_siri, a.no_topup, a.amount, a.requestingAgentID, a.requestDateTime, a.isUsed, b.name FROM card_telco a LEFT JOIN agents b ON a.requestingAgentID = b.id WHERE id = ?"); //query
$stmt->bind_param('s', $id); //binding
mysqli_stmt_execute($stmt); //execute
mysqli_stmt_store_result($stmt); //store the result
$count = mysqli_stmt_num_rows($stmt); //execute rows
$stmt->bind_result($newTelco, $noSiri, $noTopup, $newAmount, $newRequestAgentID, $newRequestDateTime, $isUsing, $newName, $agendId); //binding new result
$stmt->execute() or die(mysqli_error()); //execute the statement
$stmt->store_result() //store new result
$stmt->fetch(); //fetch the data
$stmt->close(); //close the statement
ChromePhp::log('here'); //console
ChromePhp::log($newTelco, $noSiri); //console
Okay i got it!! My query is wrong.
SELECT a.id, a.telco, a.no_siri, a.no_topup, a.amount, a.requestingAgentID, a.requestDateTime, a.isUsed, b.name FROM card_telco a LEFT JOIN agents b ON a.requestingAgentID = b.id WHERE a.id = ?
This is my new query. Thanks for helping me