Fetching number of rows after PDO execute - php

I am trying to show the number of rows found in the database after the searching.
Here is my code:
$city = $_POST['city'];
$bloodType = $_POST['donorType'];
$q = $db->prepare("SELECT count(*) FROM `users` AS numusers WHERE `city` = :city AND `bloodType` = :bloodType");
$q->bindValue(":city",$city,PDO::PARAM_INT);
$q->bindValue(":bloodType",$bloodType);
$q->execute();
while($row = $q->fetch(PDO::FETCH_ASSOC)){
echo "<p align='center'><h5> There is/are <span class='red-text'>".$row['numusers']."</span> available donor(s) found.
You must be a <b><a href='register.php'>registered user</a></b> to view their details.</h5></p>";
}
That's the last try I did. And I get this error message
`Notice: Undefined index: numusers
How do I solve that Tips ?

Just create alias of count(*)
SELECT count(*) AS numusers..
It would be
$q = $db->prepare("SELECT count(*) AS numusers FROM `users` WHERE `city` = :city AND `bloodType` = :bloodType");

There is a special method in PDO to retrieve this kind of data - a single value returned by the query, PDOStatement::fetchColumn(). So you don't have to hassle with aliases at all.
Besides, a while loop is superfluous here.
$city = $_POST['city'];
$bloodType = $_POST['donorType'];
$q = $db->prepare("SELECT count(*) FROM `users` WHERE `city` = :city AND `bloodType` = :bloodType");
$q->bindValue(":city", $city, PDO::PARAM_INT);
$q->bindValue(":bloodType", $bloodType);
$q->execute();
$numusers = $q->fetchColumn();
echo "<p align='center'><h5> There is/are <span class='red-text'>$numusers</span> available donor(s) found.
You must be a <b><a href='register.php'>registered user</a></b> to view their details.</h5></p>";

Related

How to join two diffrent tables in php PDO

I have two tables with this content:
Table users:
id 1
username demoUser
pwd 123
uid ghuyd3t2fgaggascxucxtu767fjc1g1e
Table all_product:
id 1
p_name demoNmae
price demo
product_id ghuyd3t2fgaggascxucxtu767fjc1g1e
I want to join them and fetch data, this is the code I'm using:
$uid = $_GET['pid'];
$query = "SELECT users.*, all_product.* FROM users tableUsers JOIN all_product tableProduct ON tableUsers.uid = tableProduct.product_id WHERE tableProduct.product_id = tableUsers.$uid";
$statement = $con->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row){
echo $row['id'];
echo $row['username'];
echo $row['p_name'];
}
But I got this error:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42S02]: Base table or view not found: 1051 Unknown table 'users'' in /Applications/AMPPS/www/AppenceMedia/fetch_user.php:22 Stack trace: #0 /Applications/AMPPS/www/AppenceMedia/fetch_user.php(22): PDOStatement->execute() #1 {main} thrown in /Applications/AMPPS/www/AppenceMedia/fetch_user.php on line 22
You're using the alias of table but in select you're using the name of table.. that gives you the error.
Also in where condition bind the parameter
Try this code:
$uid = $_GET['pid'];
$query = "SELECT tableUsers.*, tableProduct.* FROM users tableUsers JOIN all_product tableProduct ON tableUsers.uid = tableProduct.product_id WHERE tableProduct.product_id = :product_id";
$statement = $con->prepare($query);
$statement->bindParam(':product_id', $uid, PDO::PARAM_STR);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row){
echo $row['id'];
echo $row['username'];
echo $row['p_name'];
}
Be sure that you have really a table named users and If you are using table alias the try use these in everywhere
$query = "SELECT tableUsers.*, tableProduct.*
FROM users tableUsers
JOIN all_product tableProduct ON tableUsers.uid = tableProduct.product_id
WHERE tableProduct.product_id = tableUsers.$uid";
anyway you should not use php var in sql .. you are at risk for sqlijection .. try take a look at prepared statement and binding param
I think your query is a bit wrong. You should do it like:
table_name as table_alias
So in your case:
$query = "SELECT users.*, tableProduct.* FROM tableUsers as users JOIN all_product as tableProduct ON tableUsers.uid = tableProduct.product_id WHERE tableProduct.product_id = tableUsers.$uid";
br

How to do Looping to Check Duplicate in MySQL with PHP

I want to make for each data exist on databases then do loop up to get unique data.
Here my code:
$id = rand(10000000,99999999);
$check_id = $db->prepare("SELECT * FROM sh_url WHERE sh_id='$id'");
$check_id->execute();
$count_id = $check_id->rowCount();
for ($count_id != 0) {
$lid = $id+1;
}
$shorturl = htmlentities(base_convert($lid,20,36));
$query = $db->prepare("INSERT INTO `sh_url`(`sh_id`) VALUES (:id)");
$query->bindParam(":id", $lid);
$query->execute();
Why don't you use distinct keyword to do this.
SELECT DISTINCT column1, column2, ...
FROM table_name;

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.

My code returning incorrect values

In my PHP code I run the following statement:
$stmt = $pdo->prepare("SELECT * FROM `tb_services` WHERE tb_services.user_id = :var1 AND
(tb_services.user_id = :var1 OR tb_services.user_id = (SELECT subuser_owner_id FROM tb_users WHERE user_id = :var1))
AND tc_services.sub_id = :var2");
$stmt->bindParam(":var1", $_GET['var1']);
$stmt->bindParam(":var2", $_GET['var2']);
However doing $stmt->rowCount() returns 0, but when I run this exact statement(filled with the same values that I'm inputting instead of the :var1, :var2) it finds the row perfectly.
while($info = $stmt->fetch(PDO::FETCH_ASSOC)) {
The above is the code that is not running. As the return of the rowCount() is 0 and the while loop is not running, that just shows to me that it is for some reason not finding the row. If I input static values into the SQL statement, it works perfectly.
I have found the error. I was overlooking my code and saw the stupid mistake I made. For anyone out there that might experience a similar problem, the following MySQL statement:
$stmt = $pdo->prepare("SELECT * FROM `tb_services` WHERE tb_services.user_id = :var1 AND
(tb_services.user_id = :var1 OR tb_services.user_id = (SELECT subuser_owner_id FROM tb_users WHERE user_id = :var1))
AND tc_services.sub_id = :var2");
should be
$stmt = $pdo->prepare("SELECT * FROM `tb_services` WHERE(tb_services.user_id = :var1 OR tb_services.user_id = (SELECT subuser_owner_id FROM tb_users WHERE user_id = :var1))
AND tc_services.sub_id = :var2");
Removing the first tb_services.user_id = :var1 as that caused the error.

php/mysql not counting rows in table

I am trying to run this Query:
$stmt = $conn->prepare("SELECT COUNT(*) as a from session ");
$stmt->execute(array());
$records = $stmt->fetch();
echo '- '.$result["a"];
but its just displaying:
-
on its own, with no number of records, i know there is rows because when i run
SELECT COUNT(*) from `session` as a
in PHPMyAdmin it shows all the rows there in the column a
why would this query not work?
Here you go for a single column result you can use fetchColumn() and also you have aliased the table name not the column name
$stmt = $conn->prepare("SELECT COUNT(*) as a from `session`");
$stmt->execute(array());
echo $stmt->fetchColumn();
PDOStatement::fetchColumn
try this
$stmt = $conn->prepare("SELECT COUNT(*) as cnt from `session` ");
$stmt->execute(array());
$records = $stmt->fetch();
echo '- '.$records["cnt"];
why you are echoing $result.. you havent declared it..
use $records
echo '- '.$records["a"];
Try like this
$stmt = $conn->prepare("SELECT COUNT(*) as a from `session` ");
$stmt->execute(array());
$records = $stmt->fetch();
echo '- '.$records["a"];

Categories