select statments not working - php

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>";
}

Related

Get values from different tables inside a while loop statement using php

I'm having an issue of retrieving values from two different tables. Here's the code so far:
$result = mysqli_query($conn,"SELECT * FROM articles");
$num = mysqli_num_rows($result);
while ($row = mysqli_fetch_array($result)) {
$uid=$row['_uid'];
$result2 = mysqli_query($conn, "SELECT _username FROM users WHERE _id = '$uid' ";
$num2 = mysqli_num_rows($result2);
while ($row2 = mysqli_fetch_array($result2)) {
$username = $row2['_username'];
}
$divtext='<h3>'.$row['_posttype'].'</h3> <h2>'.$username.' </h2>';
}
I've been reading that I should preform this while inside a while with multiple query, also found on w3 that you could directly assign a value to a variable directly using:
"SELECT _username INTO $username FROM users WHERE _id = '$uid' LIMIT 1";
But this works in SQL inside myadmin, in a php I can't find how to cast it.
I have also replace the fetch_row for fetch_assoc and still nothing, im struggling for two days already with this.
you could select al the value using a single query
SELECT a._uid , a._posttype, u._username
FROM articles a
INNER JOIN users u on a._uid = u._id
..
$result = mysqli_query($conn,
"SELECT a._uid , a._posttype, u._username
FROM articles a
INNER JOIN users u on a._uid = u._id");
$num = mysqli_num_rows($result);
while ($row = mysqli_fetch_array($result)) {
$divtext='<h3>'.$row['_posttype'].'</h3> <h2>'.$username.' </h2>';
}
$echo $divtext;

While loop showing only one record when i use nested while loop for fetch data from another table

I have case manager table where i have inserted court table id as foreign key. i want to fetch record from both tables. when using nested while loop it shows only one row data.
$id = $_SESSION['id'];
$query1 = "SELECT * from `case_manager` where user_id = '$id' ";
$result1 = mysqli_query($conn, "$query1");
while($row = mysqli_fetch_array($result1, MYSQLI_ASSOC)) {
$Status = $row['status'];
$id = $row['id'];
$case_type = $row['case_type'];
$court_id = $row['court_id'];
$query2 = "SELECT * from `case_type` where case_id = '$case_type'";
if($result1 = mysqli_query($conn, "$query2")) {
while($row2 = mysqli_fetch_array($result1, MYSQLI_ASSOC)) {
echo $row2['case_name'];
}
}
}
Because you are overwritting you $result1 change inner query result to $result2 then try
$id = $_SESSION['id'];
$query1 ="SELECT * from `case_manager` where user_id = '$id' ";
$result1 = mysqli_query($conn , "$query1");
while ($row = mysqli_fetch_array($result1 ,MYSQLI_ASSOC)) {
$Status=$row['status'];
$id = $row['id'];
$case_type = $row['case_type'];
$court_id = $row['court_id'];
$query2 ="SELECT * from `case_type` where case_id = '$case_type'";
if($result2 = mysqli_query($conn , "$query2")){;
while ($row2 = mysqli_fetch_array($result2 ,MYSQLI_ASSOC)) {
echo $row2['case_name'];
}
}
}
1st : Because you are overwriting the variable $result1 In second query execution.
if($result1 = mysqli_query($conn , "$query2")){;
^^^^^^^^ ^^
Note : And remove that unnecessary semicolon .
2nd : No need multiple query simple use join
SELECT cm.*,c.* from `case_manager` cm
join `case_type` c
on cm.cas_type=c.case_id
where cm.user_id=$id;
You can use below query to fetch your record:
$query = SELECT case_manager.* ,case_type.case_name FROM case_manager Left JOIN case_type ON case_manager.case_type=case_type.case_id where case_manger.user_id = $id;
While($row = mysql_fetch_array()){
echo $row['case_name'];
}

I have got this code it is working fine but I want to change the having code into another structure

This is the code I have at the moment which works fine:
<?php
$sql = "SELECT * FROM te_events order by eventTitle ASC ";
$result = $conn->query($sql);
while($row = $result->fetch_assoc())
{
$venueID = $row['venueID'];
$catID = $row['catID'];
$sql2 = "SELECT * FROM te_venue where venueID='$venueID'";
$result2 = $conn->query($sql2);
while($row2 = $result2->fetch_assoc())
{
$venueName = $row2['venueName'];
}
$sql3 = "SELECT * FROM te_category where catID='$catID'";
$result3 = $conn->query($sql3);
while($row3 = $result3->fetch_assoc())
{
$catName = $row3['catDesc'];
}
?>
But I want to Change it into this format. I could do only till this bit couldn't go further than this I get errors.
<?php
$sql ="SELECT eventTitle, eventID, venueID, catID, eventStartDate, eventEndDate, eventPrice FROM te_events ORDER BY eventTitle ASC";
$queryresult = mysqli_query($conn, $sql) or die(mysqli_error($conn));
while ($row = mysqli_fetch_array($queryresult)) {
$venueID = $row['venueID'];
$catID = $row['catID'];
$venueName = $row['venueName'];
$catName = $row['catDesc'];
?>
How can I do that then?
how can I join two tables?
You should be able to join the additional 2 tables to get the columns you need.
SELECT e.eventTitle, e.eventID, e.venueID, e.catID, e.eventStartDate, e.eventEndDate, e.eventPrice, v.venueName, c.catDesc
FROM te_events as e
join te_venue as v
on e.venueID = v.venueID
join te_category as c
on c.catID = e.catID
ORDER BY eventTitle ASC
You also should avoid putting data directly into a query. If you need to do that use parameterized queries. This is how SQL injections (or second level) occur.

Alternate query using if statement in PHP

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.

parametr's from mysql_fetch_assoc() don't want to displays ;

i can't understand why echo don't displays value. Query return values in phpmyadmin sow query is fine. Please help
$query="SELECT `doctor_name` , `doctor_secondname`
FROM `doctors`
INNER JOIN `patients` ON `patients`.doctor_id = `doctors`.doctor_id
WHERE `patients`.patient_id = '{.$patient_id.}'" ;
$result = mysql_query($query) or die(mysql_error());
print_r($row);
if(mysql_num_rows($result) > 0) {
$row = mysql_fetch_assoc($result);
echo "Your doctor is :";
echo $row['doctor_name'];
echo $row['doctor_secondname'];
}
Try This:
$query="SELECT doctor_name , doctor_secondname
FROM doctors
INNER JOIN patients ON patients.doctor_id = doctors.doctor_id
WHERE patients.patient_id = '".$patient_id."'" ;

Categories