Getting record from database that has empty field - php

I have the following lines of code to retrieve records from a database:
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname; charset=utf8;", $username, $password);
$sql = $dbh->prepare("SELECT * FROM usa WHERE code = :code AND window1 = :oldrepeat AND spare <> :americinn AND url IS NOT NULL ORDER BY user ASC");
$sql->execute(array(':code' => $code, ':oldrepeat' => $oldrepeat, ':americinn' =>$americinn));
/*** fetch the results ***/
$result = $sql->fetch();
Amongst other criteria, this query is supposed to return records that only have some content in the field called url, but this is not happening. It is returning records that also have an empty url field.
I assume that I am doing something fundamentally wrong but cannot see what it is.
Can anyone shed some light please?
Best wishes

Well, write your query in following way:
SELECT * FROM usa WHERE code = :code AND window1 = :oldrepeat AND spare <> :americinn AND !ISNULL(url) ORDER BY user ASC
ISNULL is an inbuilt MySQL function that checks if value of a column is null. By using ! (negation), you will get only required rows.
In case if a column has blank value, you can try url!=''.

Related

PDO fetch me a fake result

I'm working on a function that compare two price.
I have a table called 'PRODUCT' that has 3 column: ID, REFERENCE, PRICE.
I get a price from a FORM that i will compare with the column PRICE. If the number that i get with the form, is different by PRICE from the table, i want get the REFERENCE. So i work in this way:
$pdo = new PDO ("mysql:host=$hostname;dbname=$dbname", $user, $pass);
$sql = "SELECT count(1) as NB
FROM ww_ps_product
WHERE reference = :reference AND SUBSTR(wholesale_price , 1, INSTR(wholesale_price ,'.')+2) != :price" ;
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':reference', **$referenza**, PDO::PARAM_STR);
$stmt->bindValue(':price', **$prezzoAggiornato**);
$stmt->execute();
$product = $stmt->fetch(PDO::FETCH_ASSOC);
The value that i get from the form : $referenza is FIN 260482300000 and the $prezzoAggiornato is 6.90 . Normalli, in my $product, i should have 0 but i get 1.
This data are store in DB with the same values:
When i go to compare with my function, i get NB = 1 but that's is impossible. If i check with the same values in phpMyAdmin i get NB = 0.
There is something wrong in my code?

How to find out how many rows match a rule?

I want to find out how many rows in a table of my database meet a certain rule, specifically that "category" matches another variable and "published" is today or earlier. Then I want to simply echo that number.
I have no idea how to go about doing this, though.
I thought I could use count() but I'm not sure how to call just a single column and put the results of each row in an array.
Thanks!
Do this using SQL:
Try this in your database (your columns/tables may be different):
SELECT count(*) FROM blog_posts WHERE category = 'hot_stuff' and published <= NOW();
Then to execute this in PHP, depending on your framework and connection to the database:
$myCategory = 'hot_stuff';
$myTable = 'blog_posts';
$sql = "SELECT count(*) FROM {$myTable} WHERE category = '{$myCategory}' and published <= NOW();";
$rowCount = $db->query($sql);
echo $rowCount;
Connect to your database.
$pdo = new PDO($dsn, $user, $password);
Create a prepared statement. This is essential because you need to pass a value for category from your application to the query. It is not necessary to pass a value for the current date because the database can provide that for you. The ? is a placeholder where the parameter you pass will be bound.
$stmt = $pdo->prepare("SELECT COUNT(*) FROM your_table
WHERE category = ? AND published <= CURDATE()");
Do not concatenate the parameter into your SQL string (like WHERE category = '$category') because this will create an SQL injection vulnerability.
Execute the prepared statement using your specified value for category.
$stmt->execute([$category]); // assuming you have already defined $category
Use fetchColumn to return a single value, the count of rows that matched your criteria.
echo $stmt->fetchColumn();

PDO selects row with id=6 with statement such as WHERE id=6ff

I have a SQL statement using PDO that pulls based on the id from $_GET. It works correctly if the $_GET equals a number and if that number does not exist, it gives the correct error. What happens is that when the $_GET is something like 6ff, it still pulls the data for id 6 and ignores the ff. I want it to display an error.
Does anyone know why it would do that?
$sql = "SELECT players.*, users.*
FROM players JOIN users ON players.member_id=users.user_id
WHERE players.player_id = :playerid";
$stmt = $db->prepare($sql);
$stmt->execute(array(':playerid' => $playerID));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if $playerID = 6, I get player 6.
if $playerID = 6gjopj, i still get player 6
The intiger validation should be done before you pass the value for query.
Happy coding😊

PDO fetch() returning one row, and PDO fetchAll() returning troubleshooting

I am attempting to add a query that joins two tables where their 'id(s)' are equal to one another, and from there I am wanting to display information from the two. (The first table being 'sign_in' consisting of basic account credentials, and the second being 'account' containing the user's personal information)
The example below seems to only display information from the first row, but does not return anything further.
$id = $_SESSION['user_session'];
$information = $db_connection->prepare(
"SELECT sign_in.id, sign_in.username, sign_in.email_address, account.id, account.first_name, account.last_name
FROM sign_in
INNER JOIN account
WHERE sign_in.id = account.id"
);
$information->execute(array(
'id' => $id
));
$userRow = $information->fetch(PDO::FETCH_ASSOC);
Using fetchAll(PDO::FETCH_ASSOC) returns all rows and the specified information; however, when trying to get the associated account information(username, email address, etc), nothing is returned.
For example, var_dump($userRow['first_name']); die; returns NULL.
Any explanation or help is greatly appreciated.
Example database structure:
After running the query:
You are not using $id in your query. In the code below I use a regular placeholder ? as they are simpler to use.
$id = $_SESSION['user_session'];
$information = $db_connection->prepare(
"SELECT sign_in.id, sign_in.username, sign_in.email_address, account.id, account.first_name, account.last_name
FROM sign_in
INNER JOIN account
WHERE sign_in.id = ?"
);
$information->execute(array(
'id' => $id
));
$userRow = $information->fetch(PDO::FETCH_ASSOC);

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);

Categories