Outputting a select count(name) value in php pdo with mySql - php

$stmt = $conn->prepare('select count(names) as names from names where names = :name');
$stmt->bindParam(':name', $name);
$stmt->execute();
How do I output the value of names when doing a select count() using PDO without having to use a while loop or something similar?
I need the count value of names (1, 3 or 5 or whatever it is).

$count = $stmt->fetchColumn();
fetchColumn()

The select count(..) from ..-Statement always only outputs this column (the count of rows), so you cannot access the names. You will have to execute a statement only for getting the names, OR you can actually output the name by yourself, because you already have it in $name ;)

Related

PHP MYSQL query WHERE statement - Returns also rows where the condition is not met

I am trying to query the mysql database with the following statement:
SELECT form_data.*, forms.orderId, forms.eType
FROM form_data
LEFT JOIN forms ON form_data.fieldId = forms.id
WHERE form_data.submitId='somehashedid'
ORDER BY forms.orderId ASC
If I use this statement within phpmyadmin the output returns only rows containing the submitId which is handed over. Which is exactly what I want.
But trying to use the same query in php returns also rows not containing the correct submitId
function getReportDetails($reportId) {
$stmt = $this->prepare("SELECT form_data.*, forms.orderId, forms.eType FROM form_data LEFT JOIN forms ON form_data.fieldId = forms.id WHERE form_data.submitId=? ORDER BY forms.orderId ASC");
$stmt->bind_param("i", $reportId);
$stmt->execute();
return $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
}
// $_REQUEST['id'] is checked not to by empty
$data = $dao->getReportDetails($_REQUEST['id']);
// $data is checked to have an array of results
submitId is a varchar(35) utf8_general_ci
submitIds look like this f89cf0bc3660424b017f9bfe0d8c0252
My workaround for now is to check in my loop again if the db id matches the requested id and limit the output of only intended information. But why do I get wrong results?
If you do also have other improvements to my code please let me know.
Thanks for your help!
because submitId is a varchar, you should use character 's' instead of 'i' for bind_param method(character 's' uses for bind string data type or varchar while 'i' uses for integers)
so try something like below..
$stmt->bind_param("s", $reportId);

PHP MySQL Query don't deliver multidimensional Array

SOLVED: Reason Can I parameterize the table name in a prepared statement?
I have a very simple Query to collect data from a two column table in MySQL. Normally it worked but for some reason I know receive the error: Undefined offset: 1
$query_select = ("SELECT ?, ? FROM _HOOFDRUBRIEK");
$stmt = $mysqli->prepare($query_select);
$stmt->bind_param("ss", $column1, $column2);
$stmt->execute();
$stmt->store_result();
//$count = $stmt->num_rows;
//echo $count;
/die();
$stmt->bind_result( $key_hoofdrubriek ,
$descr_hoofdrubriek );
$stmt->fetch();
$hoofdrubriek[] = array('key' =>$key_hoofdrubriek ,
'descr' =>$descr_hoofdrubriek );
//Here I request the variable, what occurs the error
$var = $hoofdrubriek[1]['descr'];
echo 'Show here what's in the var: '.$var ;
Does anyone know why I get this error, because from my point of view, a multidimensional array can be called by $array_name[row][column];
You are mistinpreting how that works. Result bind parameters are just bound in order to the selected field. You still need to select normal fields as usual.
Moreover, you cannot specify field names as input parameters. In your situation, you select two constant values, namely the strings you pass as input parameters. This is why you get the field names in the result instead of the values of those fields. The parameters are just string values, so the query that is executed would look like this:
SELECT 'key_hoofdrubriek', 'descr_hoofdrubriek' FROM FROM RGS_HOOFDRUBRIEK
So, skip the question marks and the input bind parameters altogether and build the query like so:
$query_select = ("SELECT key_hoofdrubriek, descr_hoofdrubriek FROM RGS_HOOFDRUBRIEK");
Or, if you must, by using PHP variables in the statement:
$query_select = ("SELECT $column1, $column2 FROM RGS_HOOFDRUBRIEK");
For reading, you can of course still use bind_result.
You can't use placeholders for column names, they're always treated as expressions. So your prepared query is equivalent to writing:
SELECT 'key_hoofdrubriek', 'descr_hoofdrubriek' FROM RGS_HOOFDRUBIEK
This just returns those literal strings for each row in the table, not the values in the columns with those names.
If you need to determine the column names dynamically, you have to use variable substitution or concatenation, you can't use placeholders:
$query_select = "SELECT $column1, $column2 FROM RGS_HOOFDRUBRIEK";

MySQLi prepare result not as expected

I am trying to retrieve one result from my database table 'members' using a prepared call.
$favid = 1;
$type = "favdeal";
$action = 1;
$user_id = 1;
$stmt = $mysqli->prepare("SELECT ? FROM members WHERE id=?");
$stmt->bind_param('ss', $type, $user_id);
$stmt->execute();
$stmt->bind_result($favs);
while ($stmt->fetch()) {
print($favs);
}
$stmt->close();
This is the only way i managed to get any kind of result.
The table has a column called 'favdeal' which has a value of '2' in it.
The result printed returns the name of the column not the value.
So my question is how do i get the value '2' instead of the name of the column?
You can't bind columns (or tables) from doing a SELECT as you have in SELECT ?.
Select an actual column.
Or, if you want to do it dynamically, you need to use a variable.
Example: SELECT $type <= that is allowed.
However, column names can be binded when using a WHERE clause.
Example: SELECT column FROM table WHERE column=?
which you are presently using => WHERE id=?
Consult the manual on bind_param()
http://www.php.net/manual/en/mysqli-stmt.bind-param.php
Footnotes:
If you happen to use an MySQL reserved word (it could happen), you will need to wrap your column's variable with backticks.
For example: (if using $type="from";) "from" being a reserved word.
SELECT `$type` FROM members WHERE id=?
For a list of MySQL reserved words, visit the following page:
http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html

Can I use name of the column as parameter in PDO?

I'm trying to execute this:
$colparam = 'abcd';
$stmt = $db->prepare("SELECT DISTINCT ? AS kol FROM katalog ORDER BY kol ASC");
$stmt->execute(array($colparam));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
and it's not working (no errors, just empty array as result).
Instead this works fine:
$stmt = $db->prepare("SELECT DISTINCT abcd AS kol FROM katalog ORDER BY kol ASC");
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
So is there any catch with the use of parameter as a name of the column in PDO?
No, you can't use parameter replacements for any database objects (tables, columns, etc.) in MySQL.
When you think about what a prepared statement actually is, this makes complete sense. As how can MySQL prepare a query execution plan when it does not even know the database objects involved.
I certainly wish that more documentation would actually cover what a prepared statement actually does (beyond it's obvious use for parametrization).
Here is link to MySQL prepared statement documentation for more reading:
https://dev.mysql.com/doc/refman/5.6/en/sql-syntax-prepared-statements.html

MySQL & php PDO how to fetch: SELECT EXISTS (SELECT 1 FROM x WHERE y = :value)

I'm using this syntax instead of count (*) because it's supposed to be faster but I dont know how to fetch the resulting output
$alreadyMember = $dataBase->prepare('SELECT EXISTS ( SELECT 1
FROM TheCommunityReachLinkingTable
WHERE communityKey = :communityKey
AND userID = :userID)');
$alreadyMember->bindParam(':communityKey', $_POST['communityKey'], PDO::PARAM_STR);
$alreadyMember->bindParam(':userID', $_POST['userID'], PDO::PARAM_INT);
$alreadyMember->execute();
if($alreadyMember->fetch()) {do code here}
But it doesn't seems to return something correct, any idea?
The use of EXISTS seems wrong here. Just execute this query instead:
SELECT 1
FROM TheCommunityReachLinkingTable
WHERE communityKey = :communityKey
AND userID = :userID
The proper usage is just like normal, capture the return value of fetch()
$row = $alreadyMember->fetch();
print_r($row); // you may have numeric or string indices depending on the FETCH_MODE you set, pick one, consider a column alias and associative
//or the easy way
$alreadyMember->execute();
if ($alreadyMember-fetchColumn()) {
//column 0 contained a truthy value
}

Categories