Need to retrieve single cell in sql db with pdo - php

I want to put the value of count into a variable and display it on the page.
here's my code:
<?php
try {
$pdo = new PDO('Database info');
} catch (PDOException $e) {
exit('Database error.');
}
$query = $pdo->prepare("select count from counter where count_id=1");
$query->execute();
return $query;
echo $query;
?>
This isn't working... any suggestions on how i should change this to get the count to display in a variable?
Thanks.

Change to:
$query = $pdo->prepare("select count(*) from counter where count_id=1");
$query->execute();
$count = $query->fetchColumn();
echo $count;

Modify the query as follows
$count = $con->query("SELECT COUNT(*) as num from counter where count_id=1")
->fetch(PDO::FETCH_ASSOC);
echo $count['num'];

Related

how to echo out every item in table using PDO?

I want to echo everything from table that matched the criteria, currently it should be 3 rows that match, but it echoes out only 1.
public function fetchInventoryItems($user_id)
{
try
{
$stmt = $this->db->prepare("SELECT * FROM items WHERE item_owner=?
AND inventory=?");
$stmt->execute([$user_id,'1']);
if ($stmt->rowCount() > 0)
{
while($userRows = $stmt->fetch(PDO::FETCH_ASSOC))
{
$itemId = $userRows['item_id'];
$stmt = $this->db->prepare("SELECT * FROM items_db WHERE
item_id=?");
$stmt->execute([$itemId]);
while($itemRows = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo '<div class="dragcontainer inventory" ><div
id="'.$itemRows['item_id'].'" class="item '.$itemRows['item_type'].'"
style="background-image:url('.$itemRows['item_icon'].')" draggable="true">
</div></div>';
}
}
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
first fetch should retrieve 3 rows but the while loop only cycles once.
i guess it has something to do with PDO but i dont know what exactly
In the line...
$stmt = $this->db->prepare("SELECT * FROM items_db WHERE item_id=?");
Your overwriting the use of $stmt in the outer loop. Change this and any uses of this version to something else ($stmt1 would do)...
$stmt1= $this->db->prepare("SELECT * FROM items_db WHERE item_id=?");
You could rework both these SQL queries into 1 SQL statement, which would reduce the overhead and stop this sort of issue.

PHP - please check this is the correct way to return the INT from a SQL SELECT COUNT Query with PDO

Please could you inform me if this is the correct way to execute the SQL count query to return an integer value using PHP.
I have only been learning PHP for 2 weeks so apologies if this is a noob question.
CODE:
include 'connection.php';
try {
$results = $conn->query("SELECT COUNT(*) FROM users");
}
catch (Exception $e) {
echo "unable to perform SQL Request";
exit;
}
$result = $results->fetchAll(PDO::FETCH_NUM);
echo $result[0][0];
it should be
include 'connection.php';
$result = $conn->query("SELECT COUNT(*) FROM users")->fetchColumn();
echo $result;

Select All MySQL Rows

I have the following code which choose all rows in MYSQL but it show the last row only
$query = mysql_query("SELECT * FROM `users`") or die(mysql_error());
while ( $row = mysql_fetch_assoc($query) )
{
$token = $row['instagram_access_token'];
}
echo "$token";
Your code echo last row because, within while loop every time you overwrites $token value with new value. Try to connect using PDO & assign variable to array like this.
$token=[];
$user='your_user_name';
$pass='your_password';
$conn= new PDO('mysql:host=your_host_name;dbname=your_db_name', $user, $pass);
$query = $conn->prepare('SELECT * FROM `users`');
$query->execute();
// alternatively you could use PDOStatement::fetchAll() and get rid of the loop
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$token[] = $row['instagram_access_token']; // see this line with []
}
echo '<pre>';
print_r($token);
echo '</pre>';
Note: Don't use mysql_* see more here Why shouldn't I use mysql_* functions in PHP?
Change your code to this:
$query = mysql_query("SELECT * FROM `users` ORDER BY RAND()") or
die(mysql_error());
while ( $row = mysql_fetch_assoc($query) )
{
$m = $row['instagram_access_token'];
echo "$m";
}

SQL Count Not Working From Inside of PHP Code

I have the weirdest issue going on. COUNT() is not working from inside my PHP code, but it is working in the SQL input space in the PHPMyAdmin database. For example if I use the following query:
SELECT COUNT(*) FROM posts WHERE category = "coding"
It will return the correct results from the SQL input in the PHPmyadmin part, but from the PHP code it will always return 1. Here is the code I am using for the PHP:
function numberofposts($category, $connection) {
$query = "SELECT COUNT(*) FROM posts WHERE category = :category";
$params = array(':category' => $category);
try{
$stmt = $connection->prepare($query);
$result = $stmt->execute($params);
}
catch(PDOException $ex){
echo ("Failed to run query: " . $ex->getMessage());
}
return $result;
}
echo "Number of Posts: " . numberofposts("art", $connection);
What it is doing is in the first code at the top it will return the correct results, but in the PHP code it is always returning 1. Is there a problem with me PHP? Please just post if you do not understand what I am asking, or if you would like more information.
You are doing a select and you execute the statement, but you are not fetching the row with the results.
You probably want something like:
function numberofposts($category, $connection) {
$query = "SELECT COUNT(*) as cnt FROM posts WHERE category = :category";
^^^ for easy access
$params = array(':category' => $category);
try{
$stmt = $connection->prepare($query);
$stmt->execute($params);
$row = $stmt->fetch();
}
catch(PDOException $ex){
echo ("Failed to run query: " . $ex->getMessage());
}
return $row['cnt'];
// if you don't alias the column you can do:
// return $row[0];
}

Create an array from database results

I want to create an array from a database query. I want to select 10 random questions by their ID, and put them into an Array, JUST the ID, i do not want it to be like [0]=>array('1'),[1]=>array('2'), I would like to to simply be, array('1','2','3') etc.
After they are in the array i would like to be able to check if the id is in the array
If u use the PDO php extension, use the http://www.php.net/manual/en/pdostatement.fetchcolumn.php to retrieve the values of the column as one-dim array.
try {
$pdo = new PDO([dsn], [username], [password]);
$sql = "
SELECT ID
FROM [tablename]
ORDER BY RAND()
LIMIT 10
";
$statement = $pdo->prepare($sql);
if (!$statement) {
//error handling here
}
$result = $statement->execute();
if (!$result) {
//error handling here
$array = array();
while (list($id) = $statement->fetch(PDO::FETCH_NUM)) {
$array[] = $id;
}
$statement = NULL;
} catch (PDOException $e) {
//error handling here
}
This should leave an enumerated array of the ID's

Categories