1

Below is the code in my model, I'm using Codeigniter, I'm sure there's a simple problem with it but I've been trying for a long time, any ideas?

<?php
    class Users_model extends CI_Model {

    public function __construct() {
        parent::__construct();
        $this->load->database();
    }

    public function checkLogin($username, $pass) {
        $sql = "SELECT COUNT(*) FROM Users WHERE username=? AND password=?;";
        $query = $this->db->query($sql, $username, sha1($pass));

        if ($query -> num_rows() == 1) {
            return True;
        } else {
            return False;
        }
    }
    }
?>

Error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? AND password=?' at line 1

9
  • Can you be more precise about the problem you have ? What PHP error do you see ? Commented Nov 11, 2016 at 21:28
  • Sure, see edit @lovasoa Commented Nov 11, 2016 at 21:30
  • Although it won't solve the problem, why not do SELECT COUNT(*) FROM Users WHERE username=? AND password=?;? Commented Nov 11, 2016 at 21:31
  • What is the type of your $this->db object ? Commented Nov 11, 2016 at 21:32
  • That would make more sense yes! Commented Nov 11, 2016 at 21:33

2 Answers 2

2

If $this->db is a PDO object, than its query method doesn't allow you to use argument binding.

You will have to use a prepared statement. Your code would then look like:

$sql = "SELECT COUNT(*) as count FROM Users WHERE username=:user AND password=:pass";
$sth = $this->db->prepare($sql);
$sth->execute(array(':user' => $username, ':pass' => sha1($pass)));
$count = $sth->fetch(PDO::FETCH_COLUMN, 'count');
Sign up to request clarification or add additional context in comments.

2 Comments

For what it's worth, using named parameter placeholders is not mandatory in PDO. You can use positional parameters (? placeholders). But you cannot use both styles in the same SQL query.
This is not appropriate in a CodeIgniter application. CodeIgniter has its own database interacting methods.
1

Today I found that the below worked, the parameters for the SQL statement just needed to be in a array.

$query = $this->db->query($sql, array($username, sha1($pass)));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.