I'm trying to run an alternate query if the initial query fails (it does because the id I'm searching for in this instance only exists in one of the databases being joined) using an if statement and I've constructed it like so:
<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/php/link_costreport_2013.php');
$id = $_GET['id']; //ID # For page/query
if($query = $link->prepare("SELECT locale.id, locale.provider_num, locale.provider_name, locale.state, locale.city,
finstat_ca.coh_and_banks, finstat_ca.temp_investments, finstat_ca.notes_receivable, finstat_ca.accounts_receivable, finstat_ca.other_receivables,
finstat_ca.afun_and_ar, finstat_ca.inventory, finstat_ca.prepaid_expenses, (finstat_ca.other_cur_assets + finstat_ca.due_from_other_funds) as other_cur_assets, finstat_ca.total_current_assets,
finstat_fa.total_fixed_assets,
finstat_olta.investments, (finstat_olta.dep_on_leases + finstat_olta.due_from_owners_officers + finstat_olta.other_assets) as all_olta, finstat_olta.total_other_assets, finstat_olta.end_assets,
finstat_cl.accounts_payable, finstat_cl.salaries_wages_fees_payable, finstat_cl.payroll_taxes_payable, finstat_cl.notes_loans_payable, finstat_cl.deferred_income, finstat_cl.total_current_liabilities,
(finstat_cl.total_current_liabilities - (finstat_cl.accounts_payable + finstat_cl.salaries_wages_fees_payable + finstat_cl.payroll_taxes_payable + finstat_cl.notes_loans_payable + finstat_cl.deferred_income)) as all_other_cl,
finstat_ltl.mortgage_payable, finstat_ltl.notes_payable, finstat_ltl.unsecured_loans, finstat_ltl.other_long_term_liabilities, finstat_ltl.total_long_term_liabilities,
finstat_talfb.total_fund_balance, finstat_talfb.total_lia_plus_fb
FROM `locale`
INNER JOIN `finstat_ca`
ON locale.id = finstat_ca.id
INNER JOIN `finstat_fa`
ON locale.id = finstat_fa.id
INNER JOIN `finstat_olta`
ON locale.id = finstat_olta.id
INNER JOIN `finstat_cl`
ON locale.id = finstat_cl.id
INNER JOIN `finstat_ltl`
ON locale.id = finstat_ltl.id
INNER JOIN `finstat_talfb`
ON locale.id = finstat_talfb.id
WHERE locale.id = :id
LIMIT 1")){
} else {
$query = $link->prepare("SELECT id, provider_num, provider_name, state, city
FROM `locale`
WHERE id = :id
LIMIT 1");
}
$query->bindParam(':id', $id);
$query->execute();
$results = $query->fetch(PDO::FETCH_ASSOC);
echo json_encode($results);
Basically it defaults to the single table where the ID does exist and only pulls a couple fields as opposed to the large statement above it. My only issue is that my code here is not working. My JSON only says false when I echo it. It obviously should not.
Is there an error in my code here?
Thanks in advance
:edit: I should note that when I enter an ID that exists in all the tables joined, the correct result (json) is displayed on the page.
I believe the problem is that even if ID does not exist in the first query, the $query variable still has a proper query in it and there is nothing false about it. That's not what you should be if-testing.
I think you should be testing $results.
This shows you the logic.
<?php
require_once($_SERVER['DOCUMENT_ROOT'] . '/php/link_costreport_2013.php');
//ID # For page/query
$id = $_GET['id'];
$sql_1 = "SQL CODE FOR QUERY 1";
$sql_2 = "SQL CODE FOR QUERY 2";
$query = $link->prepare($sql_1);
$query->bindParam(':id', $id);
$query->execute();
$results = $query->fetch(PDO::FETCH_ASSOC);
if (!$results)
{
$query = $link->prepare($sql_2);
$query->bindParam(':id', $id);
$query->execute();
$results = $query->fetch(PDO::FETCH_ASSOC);
}
echo json_encode($results);
However as you can see there are a few lines of code that are repeated inside the if-statement that very similar to code that was just before the if-statement. Perhaps with a loop that loops twice but breaks out if $results is not false would be neater.
<?php
require_once($_SERVER['DOCUMENT_ROOT'] . '/php/link_costreport_2013.php');
//ID # For page/query
$id = $_GET['id'];
$sql[] = "SQL CODE FOR QUERY 1";
$sql[] = "SQL CODE FOR QUERY 2";
foreach ($sql as $sql_query)
{
$query = $link->prepare($sql_query);
$query->bindParam(':id', $id);
$query->execute();
$results = $query->fetch(PDO::FETCH_ASSOC);
if ($results)
{
break;
}
}
echo json_encode($results);
The world is your oyster.
Related
I got issue with nested array which seems are not Json object for some reason. When i try for e.g access jsonData["user"] it works, but when i try go deeper such as jsonData["user"]["photo_url"] then it's treated like a string and i cant access the value.
Current code:
<?php
require_once("db_connection.php");
$userId = $_GET["user_id"];
$query = "WITH user AS (SELECT id, JSON_OBJECT('display_name', u.display_name, 'photo_url', u.photo_url) AS user FROM users u WHERE id = :userId), info AS (SELECT id, JSON_ARRAYAGG(JSON_OBJECT('text', text, 'start_at', start_at, 'end_at', end_at, 'status', status)) AS information FROM report GROUP BY id), img AS (SELECT report_id, JSON_ARRAYAGG(JSON_OBJECT('name', name)) AS images FROM report_images GROUP BY report_id), cmt AS (SELECT report_id, COUNT(*) AS totalcomments FROM report_comments rc JOIN users u ON rc.user_id = u.id GROUP BY report_id) SELECT u.user, info.information, img.images, cmt.totalcomments FROM report r JOIN user u ON u.id = r.user_id LEFT JOIN info ON info.id = r.id LEFT JOIN img ON img.report_id = r.id LEFT JOIN cmt ON cmt.report_id = r.id";
$stmt = $db->prepare($query);
// Bind our variables.
$stmt->bindValue(":userId", $userId);
// Execute.
$stmt->execute();
$result = $stmt->fetchAll();
if (count($result) > 0) {
$toJson = json_encode($result);
echo $toJson;
} else {
$toJson = json_encode("Error");
echo $toJson;
}
?>
Old code which worked:
<?php
require_once("db_connection.php");
require_once("functions.php");
$userId = $_GET["user_id"];
$query = "SELECT * FROM report WHERE `user_id` = :userId";
$stmt = $db->prepare($query);
// Bind our variables.
$stmt->bindValue(":userId", $userId);
// Execute.
$stmt->execute();
$result = $stmt->fetchAll();
if (count($result) > 0) {
foreach ($result as $key => $value) {
$result[$key]["user"] = getUserById($db, $value["user_id"]);
}
$toJson = json_encode($result);
echo $toJson;
} else {
$toJson = json_encode("Error");
echo $toJson;
}
?>
Because you are aggregating some of the values as JSON in your query, you need to decode those first before attempting to use the values and then JSON encode the whole result set. You need to do that as you fetch the data, so replace:
$result = $stmt->fetchAll();
with:
$result = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$row['user'] = json_decode($row['user']);
$row['images'] = json_decode($row['images']);
$row['comments'] = json_decode($row['comments']);
$result[] = $row;
}
Okay I try with the first query to get all names of the computers from the table psComputers. Now I need in the second query a variable from the first query to iterate over all entries which are assigned to the respective computer in the table psTest. I wonder if such a thing is possible at all?
Table psComputer contains ID, name
Table psTest contains ID, computername, category, value
index.php
$statement = $pdo->prepare("SELECT * FROM psComputers ");
$statement->execute();
$result = $statement->fetchAll();
if ($statement->rowCount() > 0) {
foreach ($statement->fetchAll() as $row) {
$id = $row['ID'];
$name = $row['name'];
$statement2 = $pdo->prepare("SELECT * FROM psTest WHERE computerName = $name");
$statement2->execute();
$result2 = $statement2->fetchAll();
if ($statement2->rowCount() > 0) {
foreach ($statement2->fetchAll() as $row2) {
$id2 = $row2['ID'];
$computerName = $row2['computerName'];
$category = $row2['category'];
$value = $row2['value'];
}
}
}
}
You need quotes around $name in the second query, since it's a string.
$statement2 = $pdo->prepare("SELECT * FROM psTest WHERE computerName = '$name'");
But since you're using a prepared query, you should use a parameter instead of substituting a variable.
You also shouldn't call $statement->fetchAll() twice. The first call will read all the rows, and the second won't have anything left to read (it doesn't reset the cursor).
$statement = $pdo->prepare("SELECT * FROM psComputers ");
$statement->execute();
$result = $statement->fetchAll();
if (count($result) > 0) {
$statement2 = $pdo->prepare("SELECT * FROM psTest WHERE computerName = :name");
$statement2->bindParam(':name', $name);
foreach ($result as $row) {
$id = $row['ID'];
$name = $row['name'];
$statement2->execute();
$result2 = $statement2->fetchAll();
if (count($result2) > 0) {
foreach ($result2 as $row2) {
$id2 = $row2['ID'];
$computerName = $row2['computerName'];
$category = $row2['category'];
$value = $row2['value'];
}
}
}
}
But even better is to just join the two queries:
$statement = $pdo->prepare("
SELECT c.id AS computerID, c.name AS computerName, t.id AS testID, t.category, t.value
FROM psComputers AS c
JOIN psTest AS t ON c.name = t.computerName
ORDER BY c.id");
A couple things to note,
When using strings in queries, they must be quoted.
You are already preparing the statement - bind the value instead, and the note above becomes irrelevant.
You can use a JOIN instead of running a query in a loop. This will also remove the variable in the name, making both notes above irrelevant! (You should take note of both, but they become irrelevant for the code in question).
Its rarely a good idea to run a query within a loop.
$statement = $pdo->prepare("SELECT pt.*
FROM psTest pt
JOIN psComputers pc ON pt.computerName=pc.name");
$statement->execute();
$result = $statement->fetchAll();
if (count($result)) {
foreach ($result as $row) {
$id2 = $row['ID'];
$computerName = $row['computerName'];
$category = $row['category'];
$value = $row['value'];
}
}
problem occurred while creting comment system for my web site
select statement not working
$reslt = mysqli_query($connection,"SELECT * FROM tbl_users where id='".$_SESSION['id']."'");
$row= mysqli_fetch_array($reslt);
$comm = mysqli_query($connection,"SELECT * FROM tbl_comments where id='".$_SESSION['id']."'");
While( $row= mysqli_fetch_array($comm))
{
$comm[] = $row;
}
if i remove second statement ($comm) first statement works fine
My second question
how can i fetch data from database in php ?
Here is the code
$comm = mysqli_query($connection,"SELECT * FROM tbl_comments where id='".$_SESSION['id']."'");
While( $row= mysqli_fetch_array($comm))
{
$comm[] = $row;
}
Not getting results (comments)
echo $row['comment'];
Unsure of your schema, but perhaps something like this:
$result = $connection->query("
SELECT
C.comment AS comment, U.user AS user
FROM
tbl_comments C, tbl_users U
WHERE
C.id = U.id
");
while($data = $result->fetch_assoc()) {
echo"$data[comment] by $data[user] </br>";
}
I've a PHP application that works with MySQL through PDO. I have a table with different records and I have to prevenet inserting a duplicate one. But when I want to check existing items, select statement does not return a true value. This is my code:
$sql = "SELECT COUNT(id) FROM tbl_product_category1 WHERE title = '?'";
$q = $db->prepare($sql);
$q->execute(array($title));
if ($q->fetchColumn() == 0)
{
...
I also tested this one:
$sql = "SELECT id FROM tbl_product_category1 WHERE title = '?'";
$q = $db->prepare($sql);
$q->execute(array($title));
$rows = $q->rowCount();
if ($rows == 0)
{
...
Imagine $title=1. I have 4 records with this value. But I can not see anything in SELECT statement. What is wrong here ?
try this: (don't wrap the value of the title with single quotes)
$sql = "SELECT COUNT(id) FROM tbl_product_category1 WHERE title = ? ";
Assuming I have a uniqid key in my table and that same key is sent to my site in a get method, how do I pull that specific key out and assign all the data from the table to variables. This is what I have so far but cant seem to figure it out.
$query1 = "SELECT *
FROM todo_item2 as ti INNER JOIN todo_category2 as tc ON ti.todo_id = tc.todo_id'
WHERE todo_id = :todo_id";
$statement1 = $db->prepare($query1);
$statement1 -> execute(array(
'todo_id' =>$id
));
while ($row = $statement1->fetch())
{
$text = $row['todo'];
$cat = $row['category'];
$percent = $row['precent'];
$date = $row['due_date'];
}
You should ready about what execute actually does .. the parameters to execute (and I assume you're using PDO or something similar here) are the tokens of the query. What you want is something like:
$query = " ... WHERE todo_id = ?"
$stmt = $db->prepare($query);
$stmt->execute(array($id));
while ($row = $stmt->fetch()) {
//$row is now an associative array of row values.
}
// Start the Load
$query1 = "SELECT *
FROM todo_item2 as ti INNER JOIN todo_category2 as tc ON ti.todo_id = tc.todo_id
WHERE ti.todo_id = :todo_id";
$statement1 = $db->prepare($query1);
$statement1 -> execute(array(
'todo_id' =>$id
));
// Make Sure the Data Exists
if( $statement1->rowCount() == 0 )
{
die('Please Enter a Valid ID Tag - (id)');
}
while($row = $statement1->fetch())
{
$text = $row['todo'];
$cat = $row['category'];
$percent = $row['percent'];
$date = $row['due_date'];
}