Help with IF THEN breaking when comparing results from MYSQL query - php

I'm have a problem with an invite system. The if statement seems to break. It shows the message "Fail" but the UPDATE statement still executes. Why do both the THEN and the ELSE excute?
$dbConn = new dbConn();
// Check if POST user_username and user_hash are matching and valid; both are hidden for fields
$sql = "SELECT user_username "
. "FROM table_users "
. "WHERE user_id=".mysql_real_escape_string($_POST["user_id"])." "
. "AND user_hash='".mysql_real_escape_string($_POST["user_hash"])."' "
. "AND user_enabled=0;";
$objUser = $dbConn->query($sql);
// If result contains 1 or more rows
if( mysql_num_rows($objUser) != NULL ){
$objUser = mysql_fetch_assoc($objUser);
$ssnUser->login( $objUser["user_username"] );
$sql = "UPDATE table_users SET "
. "user_enabled=1, "
. "user_first_name='".mysql_real_escape_string($_POST["user_first_name"])."', "
. "user_last_name='".mysql_real_escape_string($_POST["user_last_name"])."', "
. "user_password='".mysql_real_escape_string( md5($_POST["user_password"]) )."' "
. "WHERE user_id=".mysql_real_escape_string($_POST["user_id"]).";";
$dbConn->query($sql);
echo "Success";
header( "Refresh: 5; url=/account/?action=domains" );
} else {
echo "Fail";
}
This dbConn Class is as follows:
class dbConn{
var $username = "xxxx_admin";
var $password = "xxxxxxxx";
var $server = "localhost";
var $database = "xxxx";
var $objConn;
function __construct(){
$conn = mysql_connect( $this->server, $this->username, $this->password, true );
if( !$conn ){
die("Could not connect: ".mysql_error() );
} else {
$this->objConn = $conn;
}
unset($conn);
}
function __destruct(){
mysql_close( $this->objConn );
unset( $this );
}
function query( $query, $db = false ){
mysql_select_db( $db != false ? $db : $this->database, $this->objConn );
$result = mysql_query( $query );
unset($query,$db);
return $result;
}
}

I don't see anything really weird in your code. Could there be a "Fail" call in your login() method? Either way, I would change the line:
if( mysql_num_rows($objUser) != NULL ){
to:
$rowCount = mysql_num_rows($objUser);
if($rowCount and $rowCount > 0){
And, put an exit(); call after your header() line.

Related

how to find email id is registered in db or not in php?

Here is my code:
<?php
class Db
{
private $servername = 'localhost';
private $username = 'root';
private $password = '';
private $dbname = 'emp';
function __construct()
{
$this->db = new mysqli(
$this->servername,
$this->username,
$this->password,
$this->dbname
);
if ($this->db->connect_error) {
die("Connection failed: " . $this->db->connect_error);
}
}
public function insert_record($table, $fields)
{
$sql = "";
$sql .= "INSERT INTO " . $table;
$sql .= " (" . implode(",", array_keys($fields)) . ")values";
$sql .= " ('" . implode("','", array_values($fields)) . "')";
$query = mysqli_query($this->db, $sql);
if ($query) {
return true;
}
}
}
//making object of the class
$crudobj = new Db;
//insert code for adding data in to the db
if (isset($_POST['submit'])) {
$myArray = array(
"username" => $_POST["unm"],
"email" => $_POST["eid"],
"password" => $_POST["pass"]
);
//inserting data
if($crudobj->insert_record("users", $myArray))
{
header("location: login.pho")
}
}
?>
Call it with your input email.
if($crudobj->is_email_exists($_POST["eid"]))
{
echo "Email Already Exist";
}
Add below function in your DB class:
public function is_email_exists($email)
{
if(filter_var($email, FILTER_VALIDATE_EMAIL))
{
$email = mysqli_real_escape_string($this->db, $email);;
$sql = "SELECT email FROM users WHERE email='".$email."';";
if($result = mysqli_query($this->db, $sql))
{
return mysqli_num_rows($result);
}
}
return true;
}

I am trying to connect to a db

I am trying to connect to a db but I keep getting an error that pops up every chance I get to change the db or connection string . I am currently using php mysqli and wamp will not show any error with the connection itself .
calc.php:
class Login {
var $con;
function __construct($con){
$this->con = $con;
}
function try_connecting(){
$connecting = true;
if($connecting){
if(!$this->con){
die ("Could not connect") . $this->con->connect_errno;
} else {
echo "connected";
}
} else {
return $connecting;
}
}
function try_login(){
if(try_connecting()){
$q = "SELECT username, password FROM persons WHERE username = " . $_POST["username"] . " AND password = " . $_POST['pwd'];
$rows = $this->con->num_rows;
if($rows == 1){
echo "true";
} else {
echo "not user";
}
}
}
}
Here is the test.php:
<?php
include("calc.php");
$u = $_POST['username'];
$p = $_POST['pwd'];
$con = mysqli_connect("localhost","root","","rdb");
$form = new Login($con);
$form->try_connecting();
$form->try_login();
?>
connection string error Unknown database
You forgot to run this query
$q = "SELECT username, password FROM persons WHERE username = " . $_POST["username"] . " AND password = " . $_POST['pwd'];
$rows = $this->con->num_rows;
Try to add
$this->con->query($q)
between the lines above

multi_query() has an error

I need some help finding my error on the enclosed code. When I run either of the two queries using the if ($conn->query($sql) === TRUE) { method each works correctly. But when I try to combine them with the if ($conn->multi_query($sql) === TRUE) { method. No records are uploaded. What am I doing wrong here.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "practice";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connection made...";
$payload_dump = $_POST['payload'];
echo $payload_dump;
$payload_array = json_decode($payload_dump,true);
if(is_array($payload_array)){
foreach($payload_array as $row){
//get the data_payload details
$device = $row['device'];
$type = $row['data_type'];
$zone = $row['zone'];
$sample = $row['sample'];
$count = $row['count'];
$time = $row['date_time'];
$epoch = $row['epoch_stamp'];
$sql = "INSERT INTO data(device, type, zone, sample, count, date_time, epoch_stamp) VALUES('$device', '$type', '$zone', '$sample', '$count', '$time', '$epoch');";
$sql . = "UPDATE data SET date_time = FROM_UNIXTIME(epoch_stamp);";
if ($conn->multi_query($sql) === TRUE) {
//if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
}
$conn->close();
?>
... and yes I realize this code is not secure but it's ok for my testing purposes.
Intrinsically the code below is the same until we get to the loop where we build up an array of queries to be executed and execute the multi_query() once at the end once we leave the loop. I have removed some of the comments and statements that echo out info at the start for brevity. I hope this looks ok and works....
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "practice";
$conn = new mysqli($servername, $username, $password, $dbname);
if( $conn->connect_error ) die("Connection failed: " . $conn->connect_error);
$payload_dump = $_POST['payload'];
$payload_array = json_decode($payload_dump,true);
if( is_array( $payload_array ) ){
$queries=array();
foreach( $payload_array as $row ){
//get the data_payload details
$device = $row['device'];
$type = $row['data_type'];
$zone = $row['zone'];
$sample = $row['sample'];
$count = $row['count'];
$time = $row['date_time'];
$epoch = $row['epoch_stamp'];
/*note: we do not need to add the semi-colon here as it gets added later when we implode the array */
$queries[]="INSERT INTO `data` ( `device`, `type`, `zone`, `sample`, `count`, `date_time`, `epoch_stamp` ) VALUES ('$device', '$type', '$zone', '$sample', '$count', '$time', '$epoch')";
}
/*
Previously the below query was being execute on every iteration
~ because $epoch is now the last one encountered in the array,
the value that is updated in ALL records is as it would have been
previously.
*/
$queries[]="UPDATE `data` SET `date_time` = from_unixtime( $epoch );";
$sql=implode( ';', $queries );
if ( $conn->multi_query( $sql ) === TRUE ) {
echo "New records created and updated successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
?>

Fetching a result from selection query in php function

I have a php function of selection from mySql database:
function Master_file($name, $latin ){
$HOST_DB ="localhost";
$NAME_DB="nom";
$USER_DB ="utilisaeur";
$PWD_DB="K3Pud1";
$connect = mysql_connect($HOST_DB,$USER_DB,$PWD_DB);
$db=mysql_select_db($NAME_DB);
$qry = "SELECT tax_id FROM master where name =".$name." and latin =".$latin;
echo $qry;
$result = mysql_query($qry);
while ($Res_user = mysql_fetch_assoc($result) ) {
return $Res_user['tax_id'];
}
}
an error is shown Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in /home/admin/public_html/hitlist/include/fg_membersite.php on line 446 and the line is while ($Res_user = mysql_fetch_assoc($result)
So what is the problem ? How can i fix it?
Try this
function Master_file($name, $latin ){
$dsn = 'mysql:host=localhost;dbname=nom';
$username = 'utilisaeur';
$password = 'K3Pud1';
try {
$db = new PDO($dsn, $username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo $e->getMessage();
exit;
}
$result = $db->prepare("SELECT tax_id FROM master where name =:name");
$result->bindValue(':name', $name);
$result->execute();
foreach($result->fetchAll(PDO::FETCH_ASSOC) as $row){
echo $Res_user['tax_id'] . '<br />';
}
}
EDIT
The function above has just been updated to use PDO, display any errors, and output the tax_id value to the browser
You may try this, since your returning here return $Res_user['tax_id']; so I think you need a single row instead
function Master_file($name, $latin ){
$HOST_DB ="localhost";
$NAME_DB="nom";
$USER_DB ="utilisaeur";
$PWD_DB="K3Pud1";
$connect = mysql_connect($HOST_DB,$USER_DB,$PWD_DB);
if (!$connect) {
die("Could not connect: " . mysql_error());
}
$db=mysql_select_db($NAME_DB, $connect);
if (!$db) {
die ("Can't use " . $NAME_DB . " : " . mysql_error());
}
$qry = "SELECT tax_id FROM master where name ='" . $name . "' and latin = '" . $latin . "'";
$result = mysql_query($qry);
if( $result ){
$row = mysql_fetch_assoc($result);
return $row['tax_id'];
}
}

PHP returning "undefined" variable to flash

I don't know what's wrong but the moment i've logged in, i wanted it to display hello + username that i log in with. But currently it only displays Helloundefined
This is my flash code:
var myurl2:String = "http://localhost:8888/storyboards/check_auth.php";
var scriptLoader2:URLLoader = new URLLoader();
var scriptRequest2:URLRequest = new URLRequest();
scriptRequest2.url = myurl2+"?ck=" + new Date().getTime();
scriptLoader2.addEventListener(Event.COMPLETE, handleLoadSuccess2);
scriptLoader2.addEventListener(IOErrorEvent.IO_ERROR, handleError2);
// turn off right click so that user cannot control the movie
stage.showDefaultContextMenu = false;
scriptRequest2.method = URLRequestMethod.POST;
scriptLoader2.load(scriptRequest2);
function handleLoadSuccess2(evt:Event):void
{
var variables2:URLVariables = new URLVariables( evt.target.data );
for (var prop in variables2) {
trace(prop+" is: "+variables2[prop]);
}
if (variables2.authenticated == "y") {
// if login details OK, load protected page
nextFrame();
display_txt.text ="Hello" + variables2.username;
} else {
// if login details OK, load protected page
var url:String = "http://localhost:8888/storyboards/login.html";
var request2:URLRequest = new URLRequest(url);
try {
navigateToURL(request2, '_self'); // second argument is target
} catch (e:Error) {
trace("Error occurred!");
}
}
}
function handleError2(evt:IOErrorEvent):void
{
}
stop();
//------------------and here's my php code for process_login.php----------------------//
<?php
$host = 'localhost';
$user = 'root';
$password = 'root';
// check correct variables have been received through the POST array
if (isset($_POST['username']) && isset($_POST['pwd'])){
session_start();
// base url
$baseURL = 'http://localhost:8888/storyboards/';
// include info for db connection
//require_once("connection.php");
// escape quotes
if (!get_magic_quotes_gpc()) {
foreach($_POST as $key => $value) {
$temp = addslashes($value);
$_POST[$key] = $temp;
}
}
// connect to mysql
$connection = mysql_connect($host, $user, $password) ;
if (!$connection) {
echo '&error=' . mysql_error() . '&';
die('Could not connect ' . mysql_error());
}
//echo 'Connected successfully.';
// connect to db
$database = 'registerform';
$db = mysql_select_db($database, $connection);
if (!$db) {
echo '&error=' . mysql_error() . '&';
die ('Not connected : ' . mysql_error());
}
//echo 'Selected successfully.';
// query
$query = 'SELECT user_name, pwd FROM users WHERE user_name = "' . $_POST['username'] . '" AND pwd = "' . sha1($_POST['pwd']) . '"';
$result = mysql_query($query, $connection);
if (!$result) {
echo '&error=' . mysql_error() . '&';
die ('Invalid query: ' . mysql_error());
}
// count the number of records
$numrows = mysql_num_rows($result);
if ($numrows > 0) {
$_SESSION['authenticated'] = $_POST['username'];
echo 'authenticated=y' . '&page=' .'pass.php&user_name='.$_SESSION['authenticated'];
} else {
echo 'authenticated=n&error=' . urlencode('Sorry, access denied.');
}
}
?>
//-----------and my php code for check_auth.php----//
<?php
// access to the current session
session_start();
$_SESSION['username'] = $_POST['username'];
// if session variable authenticated is not set
if (!isset($_SESSION['authenticated'])) {
echo 'authenticated=n';
} else {
echo 'authenticated=y';
}
?>
Is there anywhere in the above codes that I went wrong? Can someone out there pls help me :(

Categories