I'm totally new to programming (normally I'm a sysadmin) but now I have to do a project where you can register and logon, with PHP and SQLite (there's no alternative).
I need to get a statement where I can do a query:
is there a user with the name from
$_POST['username']
with SQLite. I just don't get it... I found some articles but none of them really helped me.
This is my code:
$db = new PDO('sqlite:mysqlitedb.db');
$sql_create_table_users = 'CREATE TABLE IF NOT EXISTS users (
user_id INTEGER PRIMARY KEY,
user_name TEXT,
user_password TEXT
)';
$db->execute($sql_create_table_users);
$username = $_POST['username'];
$sql_checkuserexist = 'SELECT * FROM users WHERE user_name = :user_name';
$stmt = $db->prepare($sql_checkuserexist);
$stmt->execute(array(':user_name'=>$username));
$result = $stmt->fetchAll();
if (count($result) > 0) {
echo 'Exists';
} else {
echo 'Does not exist';
}
But here I get this error:
Fatal error: Call to undefined method SQLite3Stmt::exec()
This error shows to the line where I have
$stmt->execute(array(':user_name'=>$username));
Does anyone know why? My table is called "users" and has got 3 rows: user_id, user_name and user_password.
@Kostas: This is my current code you gave me (I'm only working with this code atm):
try {
//Make your connection handler to your database
$db = new PDO('sqlite:mysqlitedb.db');
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql_create_table_users = 'CREATE TABLE IF NOT EXISTS users (
user_id INTEGER PRIMARY KEY,
user_name TEXT,
user_password TEXT
)';
$stmt->execute($sql_create_table_users);
$sql = "SELECT * FROM users WHERE user_name = :username";
//Prepared statements so no SQL Injection occurs
$stmt = $db->prepare($sql);
//Execute your query
$stmt->exec(array(':username'=>$_POST['username']));
$result = $stmt->fetchAll();
if (count($result) > 0) {
echo 'Exists';
} else {
echo 'Does not exist';
}
} catch(PDOException $e) {
echo $e->getMessage();
die();
}
'; print $row['user_name'] . '
'; print $row['user_password'] . '
'; } But there's a problem with the line where i do the while () : Fatal error: Call to undefined method PDOStatement::fetchArray() Do you know why? – MichelleH Nov 21 '15 at 16:47
'; print $row['user_name'] . '
'; print $row['user_password'] . '
'; } - But what's wrong? – MichelleH Nov 21 '15 at 16:59
'; print $row['user_name'] . '
'; print $row['user_password'] . '
'; } – Kostas Mitsarakis Nov 21 '15 at 17:02