save pdo query result to variable and use it on other queries - php

I'm new in php programming, please help me.
I've to make two postgres queries from two separate databases, but one of the fist queries condition based on the other query result:
1st query:
<?php
$result = "SELECT ...
WHERE ... ";
$query = $pgszlaConn->prepare($result);
$query->execute();
while($row = $query->fetch(PDO::FETCH_BOTH)) {
$contractid=$row[0];
echo "<tr><td>$contractid</td></tr>";
?>
/In this query I've multiple results./
2nd query:
<?php
$result = "SELECT ...
WHERE contract.contract_id= :contract";
$query = $pgConn->prepare($result);
$query->bindparam(':contract', $contractid);
$query->execute();
while($row = $query->fetch(PDO::FETCH_BOTH)) {
echo "<tr><td>$row[0]</td></tr>";
?>
My problem is that the 2nd query has only one result based on the 1st query multiple results.
I'm not sure is this a good solution or not but my programming skills not so advanced ;-)
Please help me if you can!
Thanks a lot!
D. Attila

If i understand what you mean.
You need to make the second query within the loop of the first query so that for each id of the first query available, the id will be passed to the second query to query the database of the second table.
Not with my system would have shown you some of my code.
while($row = $query->fetch(PDO::FETCH_BOTH)) {
echo "<tr><td>$contractid</td></tr>";
## now you make the second query to the second table with the id of the first table
$result = "SELECT WHERE contract.contract_id= :contract";
while($row = $query->fetch(PDO::FETCH_BOTH)) {
echo "<tr><td>$row[0]</td></tr>";
} ## end of second query loop
} ## end of first query loop
Something like this should work just get the idea and implement it for yourself

Related

Pass Value inside row array to another variable name?

How to pass value inside row array to another variable since the result of the row array I need to do another query for selection in other table. In both echo $row['Plate'] and $plateID can show the value, but for another query doesn't show the result. This is my code:
<?php
$connection=mysqli_connect("localhost","root","");
$db=mysqli_select_db($connection,'db_car_identification');
$q="SELECT Plate FROM addplate ORDER BY ID DESC LIMIT 1 ";
$result=mysqli_query($connection,$q);
while($row = mysqli_fetch_array($result)) {
echo $row['Plate'];
$plateID = $row['Plate'];
echo $plateID;
$query="SELECT StuName FROM student_detail WHERE plateID=$plateID";
$query_run=mysqli_query($connection,$query);
while($row1=mysqli_fetch_array($query_run)) {
echo $row1['StuName'];
}
}
?>
You should really be using parameterized prepared statements.
However, in your example you could simply use an SQL subquery instead. It would make your code much simpler.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$connection = new mysqli("localhost", "root", "", 'db_car_identification');
$connection->set_charset('utf8mb4');
$result = $connection->query('SELECT StuName, Plate
FROM student_detail
WHERE plateID = (SELECT Plate FROM addplate ORDER BY ID DESC LIMIT 1)');
foreach($result as $row1){
echo $row1['StuName'];
}
Please check some step
For 1st Query Result which datatype is it?
If it is Integer or any numeric data type then echo the $query variable and check whatever query is right or wrong by simply copy and paste it into database query builder (phpmyadmin).
If it is String data type then simply add '' to your $plateID variable in query. eg:"SELECT StuName FROM student_detail WHERE plateID='$plateID'" (If not working then echo again and check your query problem)
Let me know if this help.

PHP and OCI8 running subquery on a dataset

I'm not sure if I am asking this the correct way, but I want to run a query on an Oracle database, fetch the result, and then run additional queries on that result dataset. Is that possible? I am trying to avoid another call to the database.
$query = "SELECT * FROM MY.TABLE ";
$stid = oci_parse($connection, $query);
oci_execute($stid);
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS_OCI_RETURN_LOBS)) {
//my code for the full dataset
}
Then I would like to do something like
PSUEDO-CODE
$newDataset = runThisQuery("SELECT * FROM [oci dataset from above(what is that syntax?)] WHERE my_value = 1");
while($newRow = loop through $newDataset){
//my code for the subquery
}
Any suggestions?
To further describe my problem: I am getting a table of fields, and from that table I would like to extract the unique values of certain fields into their own php arrays.

How to get all records from two tables with three joins in CodeIgniter?

I have three tables (questions, answers, user) and I want to query all questions and answers posted by user.
Here is my code:
$query = $this->db->select('user.*,questions.*,answers.*')
->from('user')
->join('questions','questions.user_id = user.u_id','LEFT')
->join('answers','answers.user_id = user.u_id','LEFT')
->where('user.u_id',$profile[0]['u_id'])
->group_by('user.u_id')
->get();
echo $query->num_rows();
I have 1 posted question and 1 answer in my tables, but when I am trying this code it gives me only 1 row.
Try this with method..
write your query in single line like this
$query= "select * from user where" ; as well ( this is only query example you have to write your query)
then
if ($result = mysqli_query($connection, $query )) {
/* fetch associative array */
while ($res = mysqli_fetch_assoc($result)) {
print_r($res);
}
mysqli_free_result($result);
}
in this case $connection is a your database connection
Have you tried outer join, instead left join?
Maybe even a left outer join, solves your problem, just try it.
Oh, and instead of 'num_rows()' i suppose you just want to use 'row()' to
retrieve all table´s data.
$this->db->select('user.*,questions.*,answers.*');
$this->db->join('questions','questions.user_id = user.u_id','OUTER LEFT');
$this->db->join('answers','answers.user_id = user.u_id','OUTER LEFT');
$this->db->where('user.u_id',$profile[0]['u_id']);
$this->db->group_by('user.u_id')
$query = $this->db->get('user')->row();
echo $query;
I´ve changed a little your write, just copy and test it if you´d want

Allow user to select specific row of sql select results?

Not sure if this is even possible so sorry if this is a stupid question. I have a sql select query that I will post below. It displays 5 fields into a table from my orders database table. Is there any way that a user can click on one of the rows and then that would take them to a new page showing only that rows results? Is it somehow possible to store the select query results into a session for me to call on the next page? I would like them to be able to print invoices this way. Here is the select sql code.
$sql = "SELECT id, login_id, companyname, address, cost FROM orders WHERE `login_id` = '$_SESSION[login]'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>id</th><th>login_id</th><th>companyname</th>tr><th>address</th><th>cost</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["id"]."</td><td>".$row["login_id"]."</td><td>".$row["companyname"]."</td><td>".$row["address"]."</td><td>".$row["cost"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
Simply save the value of first column (ID). Then use it for new query which selects only this row.
Expanding on i486's answer, here is how you can achieve it in more detail:
Since you already have the $row["id"], you can use this to generate a link:
echo "<a href='newpage.php?id=".$row["id"]."'>Click here</a>";
Now in newpage.php:
// You can access parameters in the url using GET
$id = $_GET["id"];
// Now you can build a new SQL query using this $id, and echo the results table
Do look up the following things:
REST: This explains how GET and POST works
Prepared SQL statements: This will prevent SQL injection, and is needed when you are working with GET or POST values in an SQL query (otherwhise malicious users can destroy your database!)

Mysql Nested Query Trouble

I have created a mysql seect statement with a nested select statement. Now my mysql skills (or lack there of) are very limited. Below is the code that I wrote. I was getting blank results or the Warning. mysql_fetch_Array error. Now I am currently receiving an error that says "Subquery returns more than 1 row" Can anyone point me in the right direction on how I can begin to fix this problem. Thanks for the help.
<?php
session_start();
$memberId = $_GET['id'];
$loggedId = $_SESSION['id'];
include('../connect_DB.php');
$sql = 'SELECT bins.tag_Id, tagging_Info.plant_Id, tagging_Info.photo_Id FROM bins inner join tagging_Info on bins.tag_Id = tagging_Info.tag_Id inner join collections on collections.id = bins.collection_Id WHERE collections.member_Id ='.$memberId.' and collections.id=(SELECT id FROM collections where member_Id='.$memberId.')';
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($result)) {
$collection = "Success"; // test to see if working
}
echo $collection;
?>
Have you tried executing just the subquery to see how many records are actually being returned and to ensure that $memberId is actually set?
It would make sense for a user to have multiple collections so you should probably adjust your main query to use IN instead of = on the subquery results.

Categories