Can I repeat fetchColumn in a function? - php

I'm trying to show 3 different values in 3 different column in a table. My first $results is okay, it's shows what it has to shows in my database but the second and the third doesn't show up. So tell me guys, how can I fix that problem? How can I show my 3e column and the other one?
public function Show($name) {
$st = $this->db->prepare("SELECT * FROM form WHERE username='$name'");
$st->execute();
$results = $st->fetchColumn(2);
print("Votre adresse: $results <br>");
$results = $st->fetchColumn(3);
print("Votre met: $results <br>");
$results = $st->fetchColumn(4);
print("Votre age: $results <br>");
}

we cannot use fetchColumn and fetchAll multiple times..so that's why we store it in a variable and then fetch data with the help of foreach loop statement for echo all data..but try this one code may be it will be helpful for you
function fetch_det()
{
$query=self::$db->prepare("select * from clas_products");
$query->execute();
$dta=$query->fetchAll(PDO::FETCH_COLUMN,0); //you can enter column num 2,3,4 instead of 0
print_r($dta);
}

Related

SQL | Get all results from query not just the first

Hello i am doing an request to an SQL Database (in php) witch looks like this...
SELECT firstname FROM users WHERE job = '$jobL'
Lets assume in the Database are three users with the $jobL namend: Mike, Steve & Danny.
Expected Output:
array("mike", "steve", "danny")
Given Output:
array("mike")
So mike is the first result in the users table. SQL only gets me the first result, i want to get all results matching my query, not only the first one.
Thanks
EDIT:
Its an php function...
function GetJobMembers($jobL) { //Function to get all Members of an Job in an Array
global $db;
$AllWithJobSQL = $db->query("SELECT firstname FROM users WHERE job = '$jobL'");
$AllUsersWithJob = $AllWithJobSQL->fetch_assoc();
return $AllUsersWithJob;
}
i tested it with $jobL = groove //GTA RP Server stuff
my db manual serach:
Use fetch_all() to fetch all rows as a 2-dimensional array. Then you can use array_column() to extract the firstname index from each row.
You should also use a prepared statement to prevent SQL injection.
function GetJobMembers($jobL) { //Function to get all Members of an Job in an Array
global $db;
$stmt = $db->prepare("SELECT firstname FROM users WHERE job = ?");
$stmt->bind_param("s", $jobL);
$stmt->execute();
$result = $stmt->get_result();
$AllUsersWithJob = $result->fetch_all(MYSQLI_ASSOC);
return array_column($AllUsersWithJob, 'firstname');
}
fetch() is opened as a pointer ready to step through the data one by one (usually in a while loop).
while($row= $AllWithJobSQL->fetch_assoc()) {
echo $row["job"].PHP_EOL;;
}
In your case, you should use fetchAll(). It fetches all the data at once, without opening any pointer, storing it in an array. It is recommended when you do not expect too many results that could cause memory problems when you want to store thousands or millions of rows from a SELECT into an array at once.
$AllUsersWithJob = $AllWithJobSQL-> fetch_all(MYSQLI_ASSOC);
return $AllUsersWithJob;
In this case $AllUsersWithJob is an associative array with all the query data. If you want to read the rows in it, you can implement a loop that loops the array:
$resultado= GetJobMembers("doctor");
foreach ($resultado as $row){
echo $row["job"].PHP_EOL;
}
Ok i fixxed it... was related to how php works with sql.
You just have to set fetch_all(MYSQLI_ASSOC);
Like this:
function GetJobMembers($jobL) { //Function to get all Members of an Job in an Array
global $db;
$AllWithJobSQL = $db->query("SELECT firstname FROM users WHERE job = '$jobL'");
$AllUsersWithJob = $AllWithJobSQL->fetch_all(MYSQLI_ASSOC);
return $AllUsersWithJob;
}
I think you are using wrong fetch method.Fetch, returning matched first row.
Your code should be like that:
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll();
print_r($result);
For more information you can check here
If you are using mysqli your code should be like that.
$AllWithJobSQL = $mysqli->query("SELECT firstname FROM users WHERE job = '$jobL'");
$AllUsersWithJob = $AllWithJobSQL ->fetch_all(MYSQLI_ASSOC);
return $AllUsersWithJob;

Not looping from 2 tables

$sth = $db->prepare("SELECT * FROM users, profile_post WHERE id='$id'");
$sth->execute();
$row = $sth->fetch(PDO::FETCH_ASSOC);
$stuff = array('Published by' => $row['firstname']. " " .$row['lastname'], 'Content profile:' => $row["content"]);
foreach ($stuff as $key => $value) {
echo "$key: $value\n";
}
This code it's not looping, i've been testing this code with return and arrays
How can i fix it?
It just shows one result, I want all of them from the db.
You're only retrieving one result:
$row = $sth->fetch(PDO::FETCH_ASSOC);
This is the only place where you fetch anything (in this case, a single row) from the database.
Your foreach is looping over the $stuff array, which you have defined with content from $row - and it only contains the Published by and the Content profile: keys.
Instead you want to iterate over the actual fetch call:
$sth = $db->prepare("SELECT * FROM users, profile_post WHERE id='$id'");
$sth->execute();
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
// process each row as you need here
var_dump($row);
}
.. should give you all the rows. BUT. There are two other issue here.
Your SQL query doesn't have a join condition, so you're effectively cross joining users with profile_post, which means that every row in users is joined with every row in profile_post. The total number of rows will the become rows in users * rows in profile_post - this is probably not what you want.
You add the join condition by adding profile_post.user_id = users.id to your WHERE condition.
The second issue is that you're using ->prepare, but you're still using $id when building the query itself. You want to use a placeholder and then give the value when you're executing the statement, supplying the value externally.
$sth = $db->prepare("
SELECT
*
FROM
users, profile_post
WHERE
profile_post.user_id = users.id AND
users.id = :id
");
$sth->execute([':id' => $id]);

php mysqli prepared statement all ways skipping the first result

I have a class which takes data from the database. Everything works but the results 'clips' the first result.
For example I have 15 items in my database so by echoing out the id I should get
1
2
3
4
...
13
14
15
But I get
2
3
4
...
13 14 15
The statement is working as the data is displaying but why is it all ways missing the first result.
CODE:
private function formatResults($data){
while($row = $data->fetch(\PDO::FETCH_ASSOC)){
echo $row['product_id'].'<br/>';
}
}
public function getAllProducts(){
if($this->databaseConnection()){
$stmt = $this->db_connection->prepare("SELECT * FROM products ORDER BY product_id DESC");
$stmt->execute();
$result = $stmt->fetch(\PDO::FETCH_ASSOC);
$this->formatResults($stmt);
}
}
That is the original function which works, (except missing out the first row).
I also tried just targeting one row to see if it made a difference but no nothing gets returned.
public function getAllProducts(){
if($this->databaseConnection()){
$stmt = $this->db_connection->prepare("SELECT * FROM products WHERE product_id = ? ORDER BY product_id ASC");
$a =1;
$stmt->bindParam(1,$a,\PDO::PARAM_INT);
$stmt->execute();
while($row = $stmt->fetch(\PDO::FETCH_ASSOC)){
echo $row['product_id'].'<br/>';
}
}
}
Im not sure what to do here, the function appears to work.
Because you're fetching/throwing away a row:
$result = $stmt->fetch(\PDO::FETCH_ASSOC); // fetch first row
$this->formatResults($stmt); // fetch all the other rows
Simply eliminate that "fetch first row" line.

sqlite3 - efficient way to count rows returned from SELECT statement in PHP without using COUNT()

I'm an SQL noob and learning how to use PDO. I'm doing a course which introduces basic user login functions. In an example of a login page, they check the username/password against a MySQL database. I edited their code slightly to be able to simultaneously check whether the user/pass combo exists and also grab the user's first name:
$sql = sprintf("SELECT firstname FROM users WHERE username='%s' AND password='%s'",
mysql_real_escape_string($_POST["username"]),
mysql_real_escape_string($_POST["password"]));
// execute query
$result = mysql_query($sql);
if (mysql_num_rows($result) == 1) {
$_SESSION["authenticated"] = true;
// get contents of "firstname" field from row 0 (our only row)
$firstname = mysql_result($result,0,"firstname");
if ($firstname != '')
$_SESSION["user"] = $firstname;
}
What I want to do is use SQLite instead and do the same thing. Searching around has only resulted in people saying you should use a SELECT COUNT(*) statement, but I don't want to have to use an extra query if it's possible. Since I'm SELECTing the firstname field, I should only get 1 row returned if the user exists and 0 if they don't. I want to be able to use that number to check if the login is correct.
So far I've got this:
$dsn = 'sqlite:../database/cs75.db';
$dbh = new PDO($dsn);
$sql = sprintf("SELECT firstname FROM users WHERE username='%s' AND password='%s'",
$_POST["username"],
$_POST["password"]);
// query the database and save the result in $result
$result = $dbh->query($sql);
// count number of rows
$rows = sqlite_num_rows($result);
if ($rows == 1) { ...
But this is returning Warning: sqlite_num_rows() expects parameter 1 to be resource, object given.
Is there a way I can do this efficiently like in MySQL, or do I have to use a second query?
EDIT:
I found this, not sure if it's the best way but it seems to work: How to get the number of rows grouped by column?
This code let me do it without the second query:
// query the database and save the result in $result
$result = $dbh->query($sql);
// count number of rows
$rows = $result->fetch(PDO::FETCH_NUM);
echo 'Found: ' . $rows[0];
$rows is an array so I can just count that to check if it's > 0.
Thanks to everyone who commented. I didn't know until now that there were 2 different approaches (procedural & object oriented) so that helped a lot.
Normally, you can use PDOStatement::rowCount(), however, SQLite v3 does not appear to provide rowcounts for queries.
You would need to seperately query the count(*), or create your own counting-query-function.
The documentation comments have an example of this
A bit late, but i tried this with SQLite3 successful:
$result = $db->query('SELECT * FROM table_xy');
$rows = $result->fetchAll();
echo count($rows);

PHP, PDO Count on mysql

I am trying to get a count of items with PDO (on a MySql table). I read somewhere that the rowCount does not work on MySql. Is this correct?
So far I definitely can't get it to work as I keep getting count=0.
Could anyone give me an idea so I can avoid going back to the db every time? I have multiple queries that look similar to this one:
$items = $con -> prepare("SELECT * FROM item_descr ORDER BY $sortBy DESC");
$count = $items -> rowCount();
$items -> execute();
while($info = $items->fetch(PDO::FETCH_ASSOC)) { ... }
I want to try to avoid an extra query with SELECT COUNT (*)
Thanks!
You need to first execute the query. Only then will the database do its work and only then can you get a count of the found results.
As, #deceze indicated,
$items = $con -> prepare("SELECT * FROM item_descr ORDER BY $sortBy DESC");
$items -> execute();
$count = $items -> rowCount();
while($info = $items->fetch(PDO::FETCH_ASSOC)) { ... }
rowCount only works after execute. I have never had a problem with rowCount in MySQL.
Using rowCount is nice, but you could also use your own counter variable if you're going to iterate over the results anyway.
Just to add this is all, please refer to the PHP documentation:
http://www.php.net/manual/en/pdostatement.rowcount.php
Particularly:
For most databases, PDOStatement::rowCount() does not return the number of rows affected by a SELECT statement. Instead, use PDO::query() to issue a SELECT COUNT(*) statement with the same predicates as your intended SELECT statement, then use PDOStatement::fetchColumn() to retrieve the number of rows that will be returned. Your application can then perform the correct action.
And an example from said page:
<?php
$sql = "SELECT COUNT(*) FROM fruit WHERE calories > 100";
if ($res = $conn->query($sql)) {
/* Check the number of rows that match the SELECT statement */
if ($res->fetchColumn() > 0) {
/* Issue the real SELECT statement and work with the results */
$sql = "SELECT name FROM fruit WHERE calories > 100";
foreach ($conn->query($sql) as $row) {
print "Name: " . $row['NAME'] . "\n";
}
}
/* No rows matched -- do something else */
else {
print "No rows matched the query.";
}
}
$res = null;
$conn = null;
?>
You can simplify your code so much if you are using PDO, such as:
$items = $conn->query("SELECT * FROM item_descr ORDER BY $sortBy DESC")->fetchAll(PDO::FETCH_ASSOC);
if(count($items))
{
// You can count the array to see how many records you got and you can iterate trough it using foreach / for loops
}
else
{
// 0 records returned
}
There is no need for prepared statements in this particular case or checking whether you got any rows back using rowCount. It is true that rowCount CAN fail even with MySQL, it all depends whether you are using unbuffered queries or not.
This works for me:
$my_query = $db->query('SELECT COUNT(*) AS Count FROM the_table');
$c = $my_query->fetch(PDO::FETCH_OBJ);
return $c->Count;
PDOStatement::rowCount() returns the number of rows only affected by a DELETE, INSERT, or UPDATE statement.
For most databases, PDOStatement::rowCount() does not return the number of rows affected by a SELECT statement. Instead, use PDO::query() to issue a SELECT COUNT(*) statement with the same predicates as your intended SELECT statement, then use PDOStatement::fetchColumn() to retrieve the number of rows that will be returned. Your application can then perform the correct action.

Categories