Jump to content

Pdo Conditional Select Statement


Landslyde

Recommended Posts

Hello Forum:

 

I'm just now trying to learn PHP and read that using PDO was a better way to utilize online databases. I have my Registration page completed, storing client info in a MySQL db, all done using PDO. However, I'm having a little trouble with the Login page. I don't know if I'm using the PDO stuff the right way.

 

    $stmt = $db->prepare('SELECT (username, password) FROM members WHERE (username) LIKE ? AND (password) LIKE ?');
    $stmt->bindValue(1, "%$uname%", PDO::PARAM_STR);
    $stmt->bindValue(2, "%$pwd1%", PDO::PARAM_STR);
    $stmt->execute();
    echo $affected_rows = $stmt->rowCount();
I'm not sure if I have the bindValue statements right, and I'm only assuming (hence the echo statement) that, if this is a valid username and password, one row will be affected. Like I said, I'm new to PHP, and this is my second day. So I imagine I have this code all wrong. Can someone set me on the right track? Much appreciated.

 

~Landslyde

Link to comment
Share on other sites

I don't have a huge amount of experience with PDO... but the place to start with is checking your work against the documentation: http://php.net/manual/en/pdostatement.bindvalue.php

 

You should also check http://php.net/manual/en/pdostatement.rowcount.php: "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." See example #2 in the link for a sample.

 

I would also suggest that you be checking for exact matches, not "like", because you might accidentally match something that shouldn't be matched. For example, if someone enters "password" as their password, you don't want the query to also match for "password1" and "1password2" (which I believe currently happens, due to the "%" before and after your variables. You'd what to use "=" instead.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...