Multiple queries with same variable on same page - php

QUESTION 1
Okay so I need to clear a confusion. I have multiple queries on the same page like this.
$abc = $pdo->prepare("SELECT COUNT(*) FROM tablename");
$abc-> execute();
$count1 = $abc->fetchColumn();
$bcd = $pdo->prepare("SELECT COUNT(*) FROM tablename");
$bcd-> execute();
$count2 = $bcd->fetchColumn();
$def = $pdo->prepare("SELECT COUNT(*) FROM tablename");
$def-> execute();
$count3 = $def->fetchColumn();
This works fine. But declaring a new name for each query somewhat gives me an irritation. Therefore, I assumed that wouldn't it be nice if all the queries could be written in the same variable? So, will it be wrong if I write these queries in one variable only? Like the following code.
$stmt = $pdo->prepare("SELECT COUNT(*) FROM tablename");
$stmt-> execute();
$count1 = $stmt->fetchColumn();
$stmt = $pdo->prepare("SELECT COUNT(*) FROM tablename");
$stmt-> execute();
$count2 = $stmt->fetchColumn();
$stmt = $pdo->prepare("SELECT COUNT(*) FROM tablename");
$stmt-> execute();
$count3 = $stmt->fetchColumn();
Will writing the queries in the same way give any errors in the future? Is it safe to write in the same variable? Is there any difference? Which method is better?
QUESTION 2
To get $count1, $count2 and $count3 I had to pass three different queries. But I prefer writing as less query as possible to prevent the use of much resources. So, is it necessary to be done this way? Or, is it possible to get them all in one single query? If yes, then how?
Please help me clear these doubts devs.

as long as you are sure that you won't use the first variable, it will be okey to use it's name to define another variable.
however, it's a good practice to unset unused variables.
for your second question, you may combine your three queries in one query using Unions as follows:
i'm assuming that you are asking for those particular three queries
SELECT COUNT(*) FROM `table1`
UNION
SELECT COUNT(*) FROM `table2`
UNION
SELECT COUNT(*) FROM `table3`

Related

What can be problem in this line with PDO? [duplicate]

I have a mysql query that targets a single column in a single row
"SELECT some_col_name FROM table_name WHERE user=:user"
After I execute the statement $stmt->execute(); how do I get this single cell directly placed into a variable with no loops? In other words how to get
from $stmt->execute();
to $col_value = 100;
I tried the 2 below, but neither worked.. The column is number 4 in the original table, but I'm assuming since in my select statement I'm selecting it only, it should be 1 when I specify the parameter for fetchColumn.
$col_value = $stmt->fetchColumn();
$col_value = $stmt->fetchColumn(0);
As you can see, I'm trying to do it in as few lines as possible.
Are you sure it's returning any rows?
$stmt->fetchColumn()
is correct way to fetch a single value, so either you probably didn't bind the :user parameter or it simply returned no rows.
$sql='SELECT some_col_name FROM table_name WHERE user=?';
$sth=$pdo_dbh->prepare($sql);
$data=array($user);
$sth->execute($data);
$result=$sth->fetchColumn();
I'm not sure why so many people mess this up:
$stmt = $dbh->prepare("SELECT `column` FROM `table` WHERE `where`=:where");
$stmt->bindValue(':where', $MyWhere);
$stmt->execute();
$SingleVar = $stmt->fetchColumn();
Make sure that you are selecting a specific column in the query and not * or you will need to specify the column order number in fetchColumn(), example: $stmt->fetchColumn(2); That usually isn't a good idea because the columns in the database may be reorganized by, someone...
This will only work properly with unique 'wheres'; fetchColumn() will not return an array.
When you want to get the last insert you add the DESC Limit 1 to the sql statement.
$sql = "SELECT `some_col_name` FROM table_name\n"
. "ORDER BY `some_col_name` DESC\n"
. "LIMIT 1";
$stmt = $conn->prepare($sql);
$result = $stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
//convert the array content to string and store in variable
$col = implode(" ", $row);
echo $col;
Have you prepared the statement first? (Before $stmt->execute())
$stmt = $db->prepare("SELECT some_col_name FROM table_name WHERE user=:user");
You could use this:
$stmt->fetch(PDO::FETCH_COLUMN, $number_of_column);

PHP PDO Prepared Statements with Where IN Clause

This is my PHP PDO Code
$stmt = $conn->prepare("SELECT * FROM TABLE
WHERE tag1 IN ('$tag1','$tag2') $andor tag2 IN ('$tag1','$tag2 ') ORDER BY $sort DESC LIMIT $limit OFFSET $start");
// Then fire it up
$stmt->execute();
// Pick up the result as an array
$result = $stmt->fetchAll();
// Now you run through this array in many ways, for example
I am trying to convert it into prepared statements, but I really don't understand, how it will work. I tried a lot of things from Google, but nothing worked.
$stmt = $conn->prepare("SELECT * FROM table WHERE tag1=? OR tag1=? AND tag2=? OR tag2=? ORDER BY id DESC LIMIT 15,10");
$stmt->execute(array($tag1, $tag2, $tag1, $tag2));
$result = $stmt->fetch(PDO::FETCH_ASSOC);
I hope it works.

Which is better and secure method of writing PDO statements?

Ok so I am in a confusion here. I have seen multiple queries like these.
Query 1
$stmt = "SELECT * FROM tablename WHERE user = :user";
$stmt = $pdo->prepare($stmt);
$stmt-> bindValue(':user', $user);
$stmt-> execute();
Query 2
$stmt = $pdo->prepare("SELECT * FROM tablename WHERE user = :user");
$stmt-> execute(['user' => $user]);
So, I want to know which of the above queries are most efficient and preferred while coding? Or is there any other better way than these to code in PDO?
It is not bindParam/bindValue that makes your query safe but :user thing that is called parameter or placeholder. As long as you have all variables in your query substituted with parameters, your query is 100% safe.
So you can tell that the second option is as safe as the fiirst one, though being more concise. Personally, I'd prefer positional placeholders that makes even more concise code:
$stmt = $pdo->prepare("SELECT * FROM tablename WHERE user = ?");
$stmt-> execute([$user]);
but all there variants are equally safe and only a matter of taste.

mysqli counting results and fetching them

Hello I have a prepared statement and I need to count the number of results I get. In order to do this I use store_result and num_rows
$query = 'SELECT userId, promo, email FROM users WHERE active = ?';
$rsActivation = $db->prepare($query);
$rsActivation->bind_param('s', $actv);
$rsActivation->execute();
$rsActivation->store_result();
$totalRows = $rsActivation->num_rows;
This code manages to get me the number of rows. The problem is that if I do this I cannot use fetch() on $rsActivation. If I use fetch and not use store_result I cannot get the number of rows.
How can I accomplish both things?
Thanks
SOLVED:
Turns out my problem was I was trying to fetch the results as an associative array. Instead I used bind_result to assign values to variables. Then I was able to use store_result and num_rows to get the count and after that I used fetch() together with the variables I assigned in bind_result.
$query = 'SELECT userId, promo, email FROM users WHERE active = ?';
$rsActivation = $db->prepare($query);
$rsActivation->bind_param('s', $actv);
$rsActivation->execute();
$rsActivation->bind_result($userId, $promo, $email);
$rsActivation->store_result();
$totalRows = $rsActivation->num_rows;
while($rsActivation->fetch()){
echo "<p>". $userId ."</p>";
...
}
You can try using
...
$rsActivation->execute();
$results = $rsActivation->get_results();
$totalRows = $results->num_rows;
and you should be able to fetch using something like
$results->fetch_assoc(), $results->fetch_row(), etc.
Here's the doc for it: http://php.net/manual/en/class.mysqli-result.php

Fetching single row, single column with PDO

I have a mysql query that targets a single column in a single row
"SELECT some_col_name FROM table_name WHERE user=:user"
After I execute the statement $stmt->execute(); how do I get this single cell directly placed into a variable with no loops? In other words how to get
from $stmt->execute();
to $col_value = 100;
I tried the 2 below, but neither worked.. The column is number 4 in the original table, but I'm assuming since in my select statement I'm selecting it only, it should be 1 when I specify the parameter for fetchColumn.
$col_value = $stmt->fetchColumn();
$col_value = $stmt->fetchColumn(0);
As you can see, I'm trying to do it in as few lines as possible.
Are you sure it's returning any rows?
$stmt->fetchColumn()
is correct way to fetch a single value, so either you probably didn't bind the :user parameter or it simply returned no rows.
$sql='SELECT some_col_name FROM table_name WHERE user=?';
$sth=$pdo_dbh->prepare($sql);
$data=array($user);
$sth->execute($data);
$result=$sth->fetchColumn();
I'm not sure why so many people mess this up:
$stmt = $dbh->prepare("SELECT `column` FROM `table` WHERE `where`=:where");
$stmt->bindValue(':where', $MyWhere);
$stmt->execute();
$SingleVar = $stmt->fetchColumn();
Make sure that you are selecting a specific column in the query and not * or you will need to specify the column order number in fetchColumn(), example: $stmt->fetchColumn(2); That usually isn't a good idea because the columns in the database may be reorganized by, someone...
This will only work properly with unique 'wheres'; fetchColumn() will not return an array.
When you want to get the last insert you add the DESC Limit 1 to the sql statement.
$sql = "SELECT `some_col_name` FROM table_name\n"
. "ORDER BY `some_col_name` DESC\n"
. "LIMIT 1";
$stmt = $conn->prepare($sql);
$result = $stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
//convert the array content to string and store in variable
$col = implode(" ", $row);
echo $col;
Have you prepared the statement first? (Before $stmt->execute())
$stmt = $db->prepare("SELECT some_col_name FROM table_name WHERE user=:user");
You could use this:
$stmt->fetch(PDO::FETCH_COLUMN, $number_of_column);

Categories