I have a PDO select statement which executes successfully, rowCount is 1 but if I do fetchAll it returns []. Also fetch returns false.
Here's the code
$st = $this->prepareQuery(
"select table.* from table where
type = 'OFFER' and
active = true and
platform = ? and
id not in (select users_table. table id from users_table where users_table.user_id = ?)");
if($st->execute([$platform, $user["user_id"]])){
echo "success";
echo $st->rowCount(); // 1
echo json_encode($st->errorInfo()); //["00000",null,null]
echo json_encode($st->errorCode()); //00000
echo json_encode($st->fetchAll()); // []
echo json_encode($st->fetch()); // false
} else echo "failure";
return $st->fetchAll(PDO::FETCH_NAMED);
This works on local machine (MacOS php 7.3) but on production server(php 5.x).
That is because some database drivers with PDO have no natural row count function (rowCount() is only for INSERT, UPDATE or DELETE queries), so you have to use another method. Here is what I use:
$sql = 'select * from table';
$data = $PDO->query($sql);
$rows = $data->fetchAll();
$num_rows = count($rows);
So, based on your fetchAll() there are no actual rows.
Related
I am trying to create a page where I can get the record values of a Database. My query is like this:
So I need to get the number of the values 1 on status (as count) from the tableexample if they exist and count them, if they do not exist, I need to get the value as 0 from it. To get the values I use this code and it works great, but I cannot seem to have the value return 0 on my PHP code if no results are found. I am a bit lost.
$user = $_SESSION["user"];
$systems = mysqli_connect("localhost", "root", "", "testdatabase");
$query = "SELECT SUM(count) AS value_sum FROM tableexample WHERE user = '$user' AND status = '1'";
$request = mysqli_query($systems, $query);
if (mysqli_num_rows($request) > 0) {
while ($row = mysqli_fetch_array($request)) {
echo '' . $row["value_sum"] . '';
}
} else {
echo '0';
}
So this code gets the values without any issue, but when I place "else" it should give me value 0 but does not give me anything.
Any idea on how I can solve this without changing my code so far as much?
Using PDO would it be something like this:
$dsn = "mysql:host=localhost;dbname=myDatabase;charset=utf8mb4";
$pdo = new PDO($dsn, "username", "password", [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);
$stmt = $pdo->prepare('
SELECT SUM(count)
FROM `table_example`
WHERE `user` = :user
AND `status` = "1"'
);
$stmt->bindParam(':user', $_SESSION["user"], PDO::PARAM_STR);
$stmt->execute();
$sum = $stmt->fetchColumn();
echo $sum;
You don't need to write any loop or previous check in order to get the SUM value.
You are doing a SUM query which will always have a result row.
SELECT SUM(count) AS value_sum FROM tableexample WHERE user = '$user' AND status = '1'
You might want to check the SUM(count) = 0 where you can do it in your while loop
while ($row = mysqli_fetch_array($request)) {
if (!empty($row[0])) {
echo $row[0]; // sum not 0
} else {
echo '0';
}
}
Your are using mysqli_fetch_array which returns array with both numeric and associative indexes instead of just associative array. You should use mysqli_fetch_assoc or mysqli_fetch_array with 2nd parameter resulttype as mentioned in docs.
resulttype This optional parameter is a constant indicating what type of array should be produced from the current row data. The
possible values for this parameter are the constants MYSQLI_ASSOC,
MYSQLI_NUM, or MYSQLI_BOTH.
By using the MYSQLI_ASSOC constant this function will behave
identically to the mysqli_fetch_assoc(), while MYSQLI_NUM will behave
identically to the mysqli_fetch_row() function. The final option
MYSQLI_BOTH will create a single array with the attributes of both.
https://www.php.net/manual/en/mysqli-result.fetch-array.php
https://www.php.net/manual/en/mysqli-result.fetch-assoc.php
As per OP's request.
Here is your code with some changes.
<?php
$user = $_SESSION["user"];
$systems = mysqli_connect("localhost", "root", "", "testdatabase");
$query = mysqli_real_escape_string($systems, "SELECT SUM(count) AS value_sum FROM tableexample WHERE user = '$user' AND status = '1'");
$request = mysqli_query($systems, $query) or die(mysqli_error($systems)); // Added die for dev env. You can choose how you want to deal with db query error.
if (mysqli_num_rows($request) > 0) {
// Just replaced mysqli_fetch_array with mysqli_fetch_assoc
while ($row = mysqli_fetch_assoc($request)) {
echo '' . $row["value_sum"] . '';
}
} else {
echo '0';
}
Also, as you are getting 0 it seems that your if (mysqli_num_rows($request) > 0) is not returning true. Might be due to some error in db query, you may want to check that again.
Edit 04-04-2020:
Updated info about indexes of returned array by mysqli_fetch_array.
Added mysqli_real_escape_string for $query.
I have this php code:
$query = $database->query("SELECT EXISTS(SELECT * FROM contacts WHERE contact_id = '$contactID')";
if($query == 0){
echo "not registered";
}elseif($query == 1){
echo "registered"
}
If I'm not wrong, the query is suppose to return 0 or 1 and it works in my SQLite manager. What is the correct way on getting that value in Php and use it in IF ELSE statement?
If you only need a single value, you can use querySingle:
$result = $database->querySingle("SELECT EXISTS(SELECT * FROM contacts WHERE contact_id = '$contactID'");
Otherwise, with normal queries, the result returned by ->query isn't actually the data itself, but an identifier you would use to get data from the database:
$results = $db->query('SELECT bar FROM foo');
while ($row = $results->fetchArray()) {
var_dump($row);
}
I use the pdo connection to access a sybase database.
when using rowCount the result is -1
$stmt = $dbh->prepare("select .... FROM users u WHERE u.ds_username like '%user%' order by ds_username ASC");
$stmt->execute();
$count = $stmt->rowCount();
As per the rowCount documentation,
PDOStatement::rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object.
If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications.
and
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.
Example
<?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;
?>
I want to check {if row exist} first and then fetch the results. here is my code:
$id = 102;
// connecting to database here
$sth = $dbh->prepare('SELECT * FROM users WHERE id = ?');
$sth->execute(array($id));
$num_rows = $sth->fetchColumn();
// if exist
if($num_rows){
// then fetch
while($end = $sth->fetch())
{
echo $end['id'];
}
}
But the output is blank, Why ?
It should be noted that the row with id = 102 is exist in the database.
As I understood, you have only one row with this ID. You can use fetch():
$id = 102;
// connecting to database here
$sth = $dbh->prepare('SELECT * FROM users WHERE id = ?');
$sth->execute(array($id));
$row = $sth->fetch();
// if record exist
if ($row) {
var_dump($row);
die();
}
PDO also have similar method rowCount but that would return effected rows in some cases.
Quoting from PHP Manual
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.
As suggested, you can query, count and proceed
$id = 102;
// connecting to database here
$sth = $dbh->prepare('SELECT COUNT(*) FROM users WHERE id = ?');
$sth->execute(array($id));
$num_rows = $sth->fetchColumn();
// if exist
if($num_rows > 0){
$sth = $dbh->prepare('SELECT * FROM users WHERE id = ?');
$sth->execute(array($id));
// then fetch
while($end = $sth->fetch())
{
echo $end['id'];
}
}
I'm working with a file and I'm attempting to do multiple select statements one after another and insert some values. So far the insert and the select I've got working together but when attempting to get the last SELECT to work I get no value. Checking the SQL query in workbench and everything works fine. Here's the code:
$id = "SELECT idaccount FROM `animator`.`account` WHERE email = '$Email'";
$result = mysqli_query($dbc, $id) or die("Error: ".mysqli_error($dbc));
while($row = mysqli_fetch_array($result))
{
echo $row[0];
$insert_into_user = "INSERT INTO `animator`.`user` (idaccount) VALUES ('$row[0]')";
}
$select_userid = "SELECT iduser FROM `animator`.`user` WHERE iduser = '$row[0]'";
$results = mysqli_query($dbc, $select_userid) or die("Error: ".mysqli_error($dbc));
while($rows = mysqli_fetch_array($results))
{
echo $rows[0];
}
I do not want to use $mysqli->multi_query because of previous problems I ran into. Any suggestions? And yes I know the naming conventions are close naming... They will be changed shortly.
Your code makes no sense. You repeatedly build/re-build the $insert_int-User query, and then NEVER actually execute the query. The $select_userid query will use only the LAST retrieved $row[0] value from the first query. Since that last "row" will be a boolean FALSE to signify that no more data is available $row[0] will actually be trying to de-reference that boolean FALSE as an array.
Since you're effectively only doing 2 select queries (or at least trying to), why not re-write as a single two-value joined query?
SELECT iduser, idaccount
FROM account
LEFT JOIN user ON user.iduser=account.idaccount
WHERE email='$Email';
I'm not sure what you're trying to do in your code exactly but that a look at this...
// create select statement to get all accounts where email=$Email from animator.account
$id_query = "SELECT idaccount FROM animator.account WHERE email = '$Email'";
echo $id_query."\n";
// run select statement for email=$mail
$select_results = mysqli_query($dbc, $id_query) or die("Error: ".mysqli_error($dbc));
// if we got some rows back from the database...
if ($select_results!==false)
{
$row_count = 0;
// loop through all results
while($row = mysqli_fetch_array($result))
{
$idaccount = $row[0];
echo "\n\n-- Row #$row_count --------------------------------------------\n";
echo $idaccount."\n";
// create insert statement for this idaccount
$insert_into_user = "INSERT INTO animator.user (idaccount) VALUES ('$idaccount')";
echo $insert_into_user."\n";
// run insert statement for this idaccount
$insert_results = mysqli_query($dbc, $insert_into_user) or die("Error: ".mysqli_error($dbc));
// if our insert statement worked...
if ($insert_results!==false)
{
// Returns the auto generated id used in the last query
$last_inisert_id = mysqli_insert_id($dbc);
echo $last_inisert_id."\n";
}
else
{
echo "insert statement did not work.\n";
}
$row_count++;
}
}
// we didn't get any rows back from the DB for email=$Email
else
{
echo "select query returned no results...? \n";
}