-1

I am having trouble with pdo and php because I am a php noob and dont know much. I am trying to connect to a database(which I did)then search the query (or something) for a matching string. Basically so a user cant make a account with the same username. This is the connection code.

$conn = new PDO("mysql:host=localhost;dbname=users;","root","");

and here is the confirmation code that is not working :(

                $sql = 'SELECT username FROM users ORDER BY username';
            foreach ($con->query($sql) as $row) {
                if($username1 !== $row['username']) {
                    $acceptCounter++;
                    $username = $_GET['username'];
                }
            }

please help me :)

kevincrab
  • 74
  • 1
  • 7
  • Did you try reading the manual ? it has some pretty simple examples for exactly what you need: http://www.php.net/manual/en/book.pdo.php – Nir Alfasi Jan 24 '14 at 23:59
  • 1
    First of all, define a `UNIQUE` on the `username` column in the table to prevent if from happening. You then have the option to try an `INSERT` and just catch an exception, or do your query with a `WHERE username='desired username'` (use a prepared statement), if that has 0 rows, you're good to go. – Wrikken Jan 25 '14 at 00:01

1 Answers1

0

I have several suggestions to you.

  1. First of all, add a unique index to your users table, like this:
    ALTER TABLE users ADD UNIQUE(username)
    After this you won't need to worry about name duplication: mySQL will throw an error (but please be careful and handle errors properly).
  2. Use the WHERE clause as suggested in a comment. So you won't need to loop through a large number of rows to find one single row.
  3. Use parameterized queries and prepared statements. As you're using PDO (which is, I believe, one of the best things you could do with PHP and MySQL), this shouldn't be a hard thing to do. So you'll be secure from (most of the) SQL injections.
  4. Use PDO->fetch() and PDO->fetchAll(). Queries in loops are a really bad thing to do because this slows down your whole website.
Andre Polykanine
  • 3,291
  • 18
  • 28