I am having an ios app and I am calling a script from my online server, in order to insert a value into a table.
In this code:
//try to register the user
$result = query("INSERT INTO login(username, pass) VALUES('%s','%s')", $user, $pass);
if (!$result['error']) {
//success
login($user, $pass);
} else {
//error
errorJson($result['error']);
}
I always get into the else clause and it is printed Database error.
Note: errorJson is a function that makes a json output from a string in order to send it back to the iphone app.
A normal select from where plays normally, so there is no chance that I am not connected to the DB.
The whole code is here:
function register($user, $pass) {
//check if username exists
$login = query("SELECT username FROM login WHERE username='%s' limit 1", $user);
if (count($login['result'])>0) {
errorJson('Username already exists');
}
//try to register the user
$result = query("INSERT INTO login(username, pass) VALUES('%s','%s')", $user, $pass);
if (! $result['error']) {
//success
login($user, $pass);
} else {
//error
errorJson($result['error']);
}
}
If the username exists the NSLog above is printed normally, so I guess I can connect to the DB.
and this is my query function:
//executes a given sql query with the params and returns an array as result
function query() {
global $link;
$debug = false;
//get the sql query
$args = func_get_args();
$sql = array_shift($args);
//secure the input
for ($i=0;$i<count($args);$i++) {
$args[$i] = urldecode($args[$i]);
$args[$i] = mysql_real_escape_string($link, $args[$i]);
}
//build the final query
$sql = vsprintf($sql, $args);
if ($debug) print $sql;
//execute and fetch the results
$result = mysql_query($link, $sql);
if (mysql_errno($link)==0 && $result) {
$rows = array();
if ($result!==true)
while ($d = mysql_fetch_assoc($result)) {
array_push($rows,$d);
}
//return json
return array('result'=>$rows);
} else {
//error
return array('error'=>'Database error');
}
}
Your syntax is wrong, should be:
mysql_query($sql, $link):
Right syntax: mysql_query ( string $query [, resource $link_identifier = NULL ] )
Related
Problem: so whenever i try to login it returns the following error:
Notice: Trying to get property 'user_id' of non-object in /butler/Classes/users/users.php on line 191
This happens cause the fetch method where I try to retrieve the user_id from the table comes empty, although the fetchColumn() functions shows that 1 row is found in the query.
I already checked the database table and the naming is correct. Also the html form is passing the parameters correctly that why I didn't posted that part of the code.
login page php
if (!empty($_POST['btnLogin'])) {
$username = trim($_POST['username']);
$password = trim($_POST['password']);
if ($username == "") {
$login_error_message = 'Username field is required!';
} else if ($password == "") {
$login_error_message = 'Password field is required!';
} else {
$user_id = $app->Login($username, $password); // check user login
if($user_id > 0)
{
$_SESSION['user_id'] = $user_id; // Set Session
header("Location: dashboard/layout.php"); // Redirect user to the profile.php
}
else
{
$login_error_message = 'Invalid login details!';
}
}
}
function login
public function Login($username, $pass)
{
try {
$db = DB();
$query = $db->prepare("SELECT user_id FROM start_users WHERE (user_start= :username) AND (psw= :pass) ");
$query->bindParam("username", $username, PDO::PARAM_STR);
//$enc_password = hash('sha256', $password);
$query->bindParam("pass", $pass, PDO::PARAM_STR);
$query->execute();
if ($query->fetchColumn() > 0) {
$result = $query->fetch(PDO::FETCH_OBJ);
echo 'resultado'.$result.' ';
print_r($query->errorInfo());
return $result->user_id;
} else {
return false;
}
} catch (PDOException $e) {
exit($e->getMessage());
}
}
Your call to
if ($query->fetchColumn() > 0) {
is retrieving the row and so the next call to
$result = $query->fetch(PDO::FETCH_OBJ);
is trying to read the another row, which I assume doesn't exist.
You should instead just make the one call
if ($result = $query->fetch(PDO::FETCH_OBJ)) {
I would also suggest the you look into How to use password_hash as your current method is using plain passwords which aren't recommended.
I'm using this method to get make a login Web Service:
function redeem() {
if (isset($_POST["user"]) && isset($_POST["pass"]) && isset($_POST["computer"])) {
$user = $_POST['user'];
$pass = $_POST['pass'];
$computer = $_POST['computer'];
$galNumb = "SELECT COUNT(*) FROM Useres WHERE username = ? AND password = ?";
$stmt = $this->db->prepare($galNumb);
$stmt->bind_param('ss', $user, $pass);
$gNumb = $stmt->execute();
$result = array(
"success" => "true",
);
$this->sendResponse(200, $gNumb);
return true;
}
$this->sendResponse(400, 'Invalid request');
return false;
}
The problem is that $gNumb always return 1 even when the sql table not contain the username and the password. Any idea what can be the problem?
You forgot to fetch results:
...
$stmt->bind_param('ss', $user, $pass);
if ($stmt->execute()) {
$stmt->bind_result($gNumb);
$stmt->fetch();
} else {
$gNumb = 0;
}
...
How can I fix the following code?
function userExists($pdow, $login)
{
$userQuery = "SELECT * FROM login u WHERE login=:user;";
$stmt = $pdow->prepare($userQuery);
$stmt->execute(array(':user' => $login));
return !!$stmt->fetch(PDO::FETCH_ASSOC);
}
$login = 'user';
$exists = userExists($pdow, $login);
if('$login')
$user= var_dump((bool) 'Exists');
{
echo "Login exsists!";
}
I have two problems with my code.
First error:
Error with echoing 'login exsists!'. I see this echo all the time in browser.
Second error:
When I get echo 'login exsists!' my code still inserts data to database.
Simply:
$servername = '';
$dbname = '';
$username = '';
$password = '';
$dbh = new PDO("mysql:host={$servername};dbname={$dbname}", $username, $password);
function user_exists($dbh, $Login) {
$Q = $dbh->prepare("SELECT * FROM login WHERE login = :Login");
$Q->bindParam(':Login', $Login);
$Q->execute();
return $Q->fetch(PDO::FETCH_ASSOC);
}
//Lets try:
$user = user_exists($dbh, 'email#example.com');
if ($user) {
echo 'User: ' . $user['login'] . ' was found in the database.';
} else {
echo 'The user was NOT found.';
}
if($login)
// this line doesnt make any sense!
// $user= var_dump((bool) 'Exists');
// so this is not a valid if clause
{
echo "Login exsists!";
}`
try {
$pdow = new PDO('mysql:host=localhost;dbname=log_cdr', 'root', 'slawek132');
$pdow -> query ('SET NAMES utf8');
$pdow -> query ('SET CHARACTER_SET utf8_unicode_ci');
$pdow->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sqlw = "INSERT INTO login (login, pass, pass_v, email, email_v)
VALUES ('".$_POST["login"]."','".$_POST["pass"]."','".$_POST["pass_v"]."','".$_POST["email"]."','".$_POST["email_v"]."')";
function user_exists($login) {
$Q = pdow()->prepare("SELECT * FROM login WHERE login = :Login");
$Q->bindParam(':login', $Login);
$Q->execute();
if ($Q->rowCount() != 0) {
//User exist:
return $Q->fetch(PDO::FETCH_ASSOC);
} else {
//User doesn't exist.
return false;
}
}
i have a simple login system and i get nothing when trying to fetch the number of rows, the same method used to work all the time, i dont know what is going on today.
Code:
<?php
class LoginClass {
public $User;
public $Pass;
public $Query;
function Init() {
$User = $this->User;
$Pass = $this->Pass;
if($User != '')
{
if($Pass != '')
{
$this->HashPass();
}
else
{
echo 'Please Enter A Password.';
}
}
else
{
echo 'Please Enter A Username or E-Mail.';
}
}
function HashPass() {
$Pass = $this->Pass;
$this->Pass = hash('sha256', $Pass);
$this->CheckUser();
}
function CheckUser() {
$User = $this->User;
if(!filter_var($User, FILTER_VALIDATE_EMAIL))
{
$this->Query = 'SELECT * FROM Users WHERE User = "'.$User.'" AND Pass = "'.$this->Pass.'"';
}
else
{
$this->Query = 'SELECT * FROM Users WHERE EMail = "'.$User.'" AND Pass = "'.$this->Pass.'"';
}
$this->CheckDB();
}
function CheckDB() {
$Query = $this->Query;
$Connect = new mysqli("127.0.0.1", "root", "", "Data");
$Stmt = $Connect->prepare($Query)
$Stmt->execute();
$Stmt->store_result();
echo $Stmt->num_rows;
$Stmt->close();
$Connect->close();
}
function SetupSession() {
echo 'Test';
}
}
the Check DB is the problem here and im able to echo out the query variable in that function everything is fine, here is exactly what i get
SELECT * FROM Users WHERE User = "Test" AND Pass = "532eaabd9574880dbf76b9b8cc00832c20a6ec113d682299550d7a6e0f345e25"
I also checked my DB and all my tables are setup correctly and there is no password.
OK, need more space than the comments area, the issue is clearly in this block:
function CheckDB() {
$Query = $this->Query;
$Connect = new mysqli("127.0.0.1", "root", "", "Data");
$Stmt = $Connect->prepare($Query)
$Stmt->execute();
$Stmt->store_result();
echo $Stmt->num_rows;
$Stmt->close();
$Connect->close();
}
I think it's because you aren't binding parameters to the prepared statement, you've already included them inline in your earlier statement. Therefore, you probably want to:
Switch to non-prepared statement
The easy option here will be to switch to a non-prepared statement. Replace your block with:
function CheckDB() {
$Query = $this->Query;
$Connect = new mysqli("127.0.0.1", "root", "", "Data");
$Stmt = $Connect->query($Query)
echo $Stmt->num_rows;
$Stmt->close();
$Connect->close();
}
A word of caution with this approach: you need to sanitize your user input in the block which defines $User, otherwise you're leaving yourself open to mysql injection. In that block, change this line:
$User = $this->User;
To the following:
$User = mysql_real_escape_string($this->User);
I have an earlier post here
But NONE of those answers worked. So here's my entire class code:
<?php
session_start();
class Mysql {
private $conn;
function __construct() {
$this->conn = new PDO('mysql:host=***;dbname=***;charset=UTF-8','***','***') or
die('There was a problem connecting to the database.');
}
function verify_Username_and_Pass($un, $pwd) {
$query = "SELECT Username
FROM Conference
WHERE Username = :un AND Password = :pwd";
$stmt = $this->conn->prepare($query);
$stmt->bindParam(':un', $un);
$stmt->bindParam(':pwd', $pwd);
$stmt->execute();
if ($stmt->rowCount() > 0) {
// User exist
$stmt->bindColumn('First Name', $firstName);
$_SESSION["FirstName"] = $firstName;
die($_SESSION["FirstName"]);
return true;
$stmt->close();
}
else {
// User doesn't exist
//die("failure");
return false;
$stmt->close();
}
}
}
?>
I've tried fetch, i've tried bind_result, etc and none of them print the correct value on the die statement. Now this worked when i stored username in session and tried to print that. What is wrong with the code?
You aren't calling the code in the snippet. What's the call procedure?
You aren't retrieving Conference.First Name only Conference.Username so you should be getting a warning unless you're not displaying errors. You probably want
"SELECT * FROM Conference...."
or
"SELECT FirstName From Conference WHERE Username = :un AND Password = :pwd";
It's possibly Conference.FirstName.
die(); is not very useful for debugging. Try var_dump($_SESSION["FirstName"]); die();
I have looked at your code, and made a working version on my own server. If you have any questions, feel free to ask.
class Mysql
{
private $conn;
public $error;
public $username;
function __construct()
{
try {
$this->conn = new PDO( 'mysql:host=localhost;dbname=****', 'root', '****' );
$this->conn->setAttribute( PDO::ATTR_EMULATE_PREPARES, false );
}
catch ( Exception $e ) {
$this->error = $e->getMessage();
}
}
function verify_Username_and_Pass( $un, $pwd )
{
$query = "SELECT Username
FROM Conference
WHERE Username = :un AND Password = :pwd";
$stmt = $this->conn->prepare( $query );
if( !$stmt ) {
$this->error = $this->conn->errorInfo();
return false;
}
$stmt->bindParam( ':un', $un );
$stmt->bindParam( ':pwd', $pwd );
$stmt->execute();
if ( $stmt->rowCount() > 0 ) {
// User exist
$this->username = $stmt->fetchColumn();
return true;
}
else {
// User doesn't exist
return false;
}
}
}
session_start();
$db = new Mysql();
if( !$db->error ) {
if( $db->verify_Username_and_Pass ( 'user', 'test' )) {
$_SESSION["FirstName"] = $db->username;
}
else
echo 'Unknown user';
}
var_dump( $db );
The script will output this:
Unknown user
object(Mysql)#1 (3) {
["conn":"Mysql":private]=> object(PDO)#2 (0) { }
["error"]=> array(3)
{ [0]=> string(5) "42S02"
[1]=> int(1146)
[2]=> string(39) "Table 'xxxx.Conference' doesn't exist" }
["username"]=> NULL }