convert sql add update and delete function in to mysqli - php

I created function in php for save select update and delete.
Plz tell me how to make this function more stronger to prevent mysql injection.
Bcoz I call this function many times in different files.
Plz suggest.
Below is my function and class.
class DB
{
var $host = 'localhost';
var $user = 'root';
var $password = '';
var $database = 'bhaskar_hindi_dbs';
function __construct($host = '', $user = '', $password = '', $database = '')
{
if($host != '') $this->host = $host;
if($user != '') $this->user = $user;
if($password != '') $this->password = $password;
if($database != '') $this->database = $database;
$con = mysql_connect($this->host, $this->user,$this->password) OR die('Couldnot connect to mysql Server');
mysql_select_db($this->database) OR die('Couldnot connect to mysql database '.$this->database);
}
function save($table, $fields, $condition = '')
{
mysql_set_charset('utf8');
$sql = "INSERT INTO $table SET ";
if($condition != '')
$sql = "UPDATE $table SET ";
$table_fields = $this->get_table_fields($table);
foreach($fields as $field=>$value)
{
if(in_array($field,$table_fields))
$sql .= "$field = '".mysql_real_escape_string(trim(htmlspecialchars($value)))."', ";
}
$sql = substr($sql, 0 ,-2);
if($condition !='')
$sql .="modified = NOW()";
else
$sql .="created = NOW(), modified = NOW()";
if($condition != '')
$sql .= " WHERE $condition";
$result = mysql_query($sql);
if(mysql_affected_rows())
return true;
else
return false;
}
function select($table, $fields = array(), $condition = '',$order = '')
{
$data = array();
mysql_set_charset('utf8');
$sql = "SELECT ";
if(is_array($fields) && count($fields) > 0)
{
$sql .= implode(", ",$fields);
}
else
{
$sql .= "*";
}
$sql .= " FROM $table";
if($condition != '')
$sql .= " WHERE $condition";
if($order != '')
$sql .= " ORDER BY $order";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result,MYSQL_ASSOC))
{
$data[] = $row;
}
return $data;
}
function get_table_fields($table)
{
$fields = array();
$result = mysql_query("SHOW COLUMNS FROM $table");
while($row = mysql_fetch_array($result,MYSQL_ASSOC))
{
$fields[] = $row['Field'];
}
return $fields;
}
}
Below is my code to Call The functions like wise...
<?php
require_once('includes/config.php');
$Admin = new admins;
$cond = "send_top = 'Active'";
$ord = "top_priority ASC";
$top2 = $Admin->select($Admin->news_table,'',$cond,$ord);
?>

Converting to MySQLi will not prevent XSS attacks, please post a detailed
description of the attack.

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;
}

mysqli::__construct() expects parameter 5 to be integer

I am trying to upload my website to a web hosting but i need phpmyadmin so i went to phpmyadmin.co with the username, password and server then when i tried to add that to my php file it came up with this error
mysqli::__construct() expects parameter 5 to be integer
this is the code of my website
<?php
class User{
private $dbServer = "";
private $dbHost = "http://www.phpmyadmin.co/";
private $dbUsername = "";
private $dbPassword = "";
private $dbName = "sql12168044";
private $userTbl = "users";
public function __construct(){
if(!isset($this->db)){
// Connect to the database
$conn = new mysqli($this->dbHost, $this->dbServer, $this->dbUsername, $this->dbPassword, $this->dbName);
if($conn->connect_error){
die("Failed to connect with MySQL: " . $conn->connect_error);
}else{
$this->db = $conn;
}
}
}
/*
* Returns rows from the database based on the conditions
* #param string name of the table
* #param array select, where, order_by, limit and return_type conditions
*/
public function getRows($conditions = array()){
$sql = 'SELECT ';
$sql .= array_key_exists("select",$conditions)?$conditions['select']:'*';
$sql .= ' FROM '.$this->userTbl;
if(array_key_exists("where",$conditions)){
$sql .= ' WHERE ';
$i = 0;
foreach($conditions['where'] as $key => $value){
$pre = ($i > 0)?' AND ':'';
$sql .= $pre.$key." = '".$value."'";
$i++;
}
}
if(array_key_exists("order_by",$conditions)){
$sql .= ' ORDER BY '.$conditions['order_by'];
}
if(array_key_exists("start",$conditions) && array_key_exists("limit",$conditions)){
$sql .= ' LIMIT '.$conditions['start'].','.$conditions['limit'];
}elseif(!array_key_exists("start",$conditions) && array_key_exists("limit",$conditions)){
$sql .= ' LIMIT '.$conditions['limit'];
}
$result = $this->db->query($sql);
if(array_key_exists("return_type",$conditions) && $conditions['return_type'] != 'all'){
switch($conditions['return_type']){
case 'count':
$data = $result->num_rows;
break;
case 'single':
$data = $result->fetch_assoc();
break;
default:
$data = '';
}
}else{
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
$data[] = $row;
}
}
}
return !empty($data)?$data:false;
}
/*
* Insert data into the database
* #param string name of the table
* #param array the data for inserting into the table
*/
public function insert($data){
if(!empty($data) && is_array($data)){
$columns = '';
$values = '';
$i = 0;
if(!array_key_exists('created',$data)){
$data['created'] = date("Y-m-d H:i:s");
}
if(!array_key_exists('modified',$data)){
$data['modified'] = date("Y-m-d H:i:s");
}
foreach($data as $key=>$val){
$pre = ($i > 0)?', ':'';
$columns .= $pre.$key;
$values .= $pre."'".$val."'";
$i++;
}
$query = "INSERT INTO ".$this->userTbl." (".$columns.") VALUES (".$values.")";
$insert = $this->db->query($query);
return $insert?$this->db->insert_id:false;
}else{
return false;
}
}
}
You are passing the fifth parameter of the mysqli object as the $dbName, but that should be the $dbPort which is optional, and must be an integer. You have to reorganize your parameters to match this:
mysqli::__construct ([ string $host = ini_get("mysqli.default_host") [,string $username = ini_get("mysqli.default_user") [, string $passwd = ini_get("mysqli.default_pw") [, string $dbname = "" [, int $port = ini_get("mysqli.default_port") [, string $socket = ini_get("mysqli.default_socket") ]]]]]] )
In order: $host, $username, $passwd, $dbname and $port. I don't see any room there for your $dbserver.
UPDATE:
Just use this:
public function __construct(){
if(!isset($this->db)){
// Connect to the database
$conn = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName);
if($conn->connect_error){
die("Failed to connect with MySQL: " . $conn->connect_error);
}else{
$this->db = $conn;
}
}
}
And get rid of that $dbServer.

want to return the user roleid after successful login

below is my MySQLDao.php
<?php
class MySQLDao {
var $dbhost = null;
var $dbuser = null;
var $dbpass = null;
var $conn = null;
var $dbname = null;
var $result = null;
function __construct() {
$this->dbhost = Conn::$dbhost;
$this->dbuser = Conn::$dbuser;
$this->dbpass = Conn::$dbpass;
$this->dbname = Conn::$dbname;
}
// function to open connection
public function openConnection() {
$this->conn = new mysqli($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname);
if (mysqli_connect_errno())
echo new Exception("Could not establish connection with database");
}
// function to return the connection
public function getConnection() {
return $this->conn;
}
// function to close the connection
public function closeConnection() {
if ($this->conn != null)
$this->conn->close();
}
// function to get user email
public function getUserDetails($email)
{
$returnValue = array();
$sql = "select * from ap_users where user_email='" . $email . "'";
$result = $this->conn->query($sql);
if ($result != null && (mysqli_num_rows($result) >= 1)) {
$row = $result->fetch_array(MYSQLI_ASSOC);
if (!empty($row)) {
$returnValue = $row;
}
}
return $returnValue;
}
// get user details using email and password
public function getUserDetailsWithPassword($email, $userPassword, $roleid)
{
$returnValue = array();
$sql = "select id,user_email from ap_users where user_email='" . $email . "' and user_password='" .$userPassword . "' and user_roleid='" . $roleid . "'";
$result = $this->conn->query($sql);
if ($result != null && (mysqli_num_rows($result) >= 1)) {
$row = $result->fetch_array(MYSQLI_ASSOC);
if (!empty($row)) {
$returnValue = $row;
}
}
return $returnValue;
}
// register user with all fields
public function registerUser($email, $password, $username, $fname, $lname, $mobile, $roleid)
{
$sql = "insert into ap_users set user_email=?, user_password=?, user_username=?, user_fname=?, user_lname=?, user_mobile=?, user_roleid=?";
$statement = $this->conn->prepare($sql);
if (!$statement)
throw new Exception($statement->error);
$statement->bind_param("sssssss", $email, $password, $username, $fname, $lname, $mobile, $roleid);
$returnValue = $statement->execute();
return $returnValue;
}
}
?>
and my UserLogin.php is as under:
<?php
require("Conn.php");
require("MySQLDao.php");
$email = htmlentities($_POST["email"]);
$password = htmlentities($_POST["password"]);
$returnValue = array();
if(empty($email) || empty($password))
{
$returnValue["status"] = "error";
$returnValue["message"] = "Missing required field";
echo json_encode($returnValue);
return;
}
$secure_password = md5($password);
$dao = new MySQLDao();
$dao->openConnection();
$userDetails = $dao->getUserDetailsWithPassword($email,$secure_password);
if(!empty($userDetails))
{
$returnValue["status"] = "Success";
$returnValue["message"] = "User is logged in";
$returnValue["role"] = "'" .$roleid. "'";
echo json_encode($returnValue);
} else {
$returnValue["status"] = "error";
$returnValue["message"] = "User is not found";
echo json_encode($returnValue);
}
$dao->closeConnection();
?>
problem here is when i push the $roleid value always it shows null.
result is like this: {"status":"Success","message":"User is logged in","role:"""}
added MySqlDao getUserDetailsWithPassword() method
$sql = "select id,user_email,user_roleid from ap_users where user_email='" . $email . "' and user_password='" .$userPassword . "' and user_roleid='" . $roleid . "'";
and in user login changed
$returnValue["role"] = "'" .$roleid. "'"; line to $returnValue['user_roleid'] = $userDetails['user_roleid'];
this accomplish my desired result!

How to connect to database using mvc in php [duplicate]

This question already has an answer here:
PHP simple DB connection class for MVC
(1 answer)
Closed 1 year ago.
dbconnect.php
class dbconnect
{
public function connect()
{
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'demo';
$connection = mysqli_connect($host, $user, $pass, $db);
return $connection;
}
}
dao.php
include 'dbconnect.php';
class dao extends dbconnect
{
private $conn;
function __construct()
{
$dbcon = new dbconnect();
$conn = $dbcon->connect();
}
function select($table, $where = '', $other = '')
{
if (!$where = '') {
$where = 'where' . $where;
}
$sele = mysqli_query($this->conn, "SELECT * FROM $table $where $other") or die(mysqli_error($this->conn));
echo $sele;
return $sele;
}
}
controller.php
include 'dao.php';
$d = new dao();
if (isset($_POST['btn_login'])) {
extract($_POST);
$username = $_POST['user_name'];
$pswd = $_POST['pswd'];
$sel = $d->select("users", "email_id = '" . $username . "'AND password='" . $pswd . "'") or die('error from here');
$result = mysqli_fetch_array($sel);
if ($result['email_id'] == $username && $result['password'] == $pswd) {
SESSION_START();
$_SESSION['user_name'] = $result['email_id'];
$_SESSION['message'] = 'Invalid Username Or Password';
header("location:index.php");
} else {
$_SESSION['error'] = 'Invalid Username Or Password';
}
}
I got an error
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in /opt/lampp/htdocs/ankit_demo/dao.php on line 13
Warning: mysqli_error() expects parameter 1 to be mysqli, null given in /opt/lampp/htdocs/ankit_demo/dao.php on line 13
Please help me to solve this.
Try this out, there was issues with if condition as well as the where condition. and we can't echo a object or can't convert object to string.
dbconnect.php:
<?php
class dbconnect{
public function connect(){
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'demo';
$connection = mysqli_connect($host,$user,$pass,$db);
return $connection;
}
}
dao.php:
<?php
include 'dbconnect.php';
class dao extends dbconnect {
private $conn;
public function __construct() {
$dbcon = new parent();
// this is not needed in your case
// you can use $this->conn = $this->connect(); without calling parent()
$this->conn = $dbcon->connect();
}
public function select( $table , $where='' , $other='' ){
if($where != '' ){ // condition was wrong
$where = 'where ' . $where; // Added space
}
$sql = "SELECT * FROM ".$table." " .$where. " " .$other;
$sele = mysqli_query($this->conn, $sql) or die(mysqli_error($this->conn));
// echo $sele; // don't use echo statement because - Object of class mysqli_result could not be converted to string
return $sele;
}
}
?>
controller.php:
<?php
include 'dao.php';
$d = new dao();
if(isset($_POST['btn_login'])){
extract($_POST);
$username = $_POST['user_name'];
$pswd = $_POST['pswd'];
$sel = $d->select("users" , "email_id = '" . $username . "' AND password='" . $pswd . "'" ) or die('error from here');
$result = mysqli_fetch_array($sel) ;
if($result['email_id'] == $username && $result['password'] == $pswd){
SESSION_START();
$_SESSION['user_name'] = $result['email_id'];
$_SESSION['message'] = 'Invalid Username Or Password';
header("location:index.php");
}
else{
$_SESSION['error'] = 'Invalid Username Or Password';
// header("Location:login.php");
}
}
?>
Change name of your constructor from __dao() to __construct().
Replace your line 6-th line of code by:
$this->conn = $dbcon->connect();
try this :
include 'dbconnect.php';
class dao extends dbconnect{
private $conn;
function __construct(){
$dbcon = new dbconnect();
$this->conn = $dbcon->connect();
}
function select( $table , $where='' , $other='' ){
if(!$where = '' ){
$where = 'where' . $where;
}
$sql = "SELECT * FROM ".$table." " .$where. " " .$other";
$sele = mysqli_query($this->conn, $sql) or die(mysqli_error($this->conn));
echo $sele;
return $sele;
}
}
Connection file:
class dbconnect{
public function connect(){
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'demo';
$connection = mysqli_connect($host,$user,$pass,$db);
return $connection;
}
}
dao file:
include 'dbconnect.php';
class dao extends dbconnect {
private $conn;
public function __construct() {
$dbcon = new parent(); // this is not needed in your case
// you can use $this->conn = $this->connect(); without calling parent()
$this->conn = $dbcon->connect();
}
public function select( $table , $where='' , $other='' ){
if(!$where = '' ){
$where = 'where' . $where;
}
$sele = mysqli_query($this->conn,"SELECT * FROM $table $where $other") or die(mysqli_error($this->conn));
echo $sele;
return $sele;
}
}
But I think it would be better to use PDO or much better a ORM system like laravel eloquent.

MySQLI LOOP DATA

I want to get all the records from the while loop. I'm unable to get all the rows from the query. It shows only the first row.
Is there anything I was going wrong in my code.
function Connect($DB_HOST = 'localhost', $DB_USER = 'root', $DB_PASS = '', $DB_NAME = 'bodhilms')
{
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
return $mysqli;
}
function GetCoeficient($coeficient = false, $con)
{
if(!$con)
return 0;
$result = array();
$sql[] = "SELECT * FROM users ";
if($coeficient != false)
$sql[] = "WHERE username = '".$coeficient."' ORDER BY u.id";
//print_r($coeficient);
$query = $con->query(implode(" ",$sql));
//print_r($query);
while($row = $query->fetch_assoc())
{
$result[] = $row;
}
return (!empty($result))? $result : 0;
}
$con = Connect();
$result = GetCoeficient($coeficient,$con);
$username = $result[0]['username'];
$firstname = $result[0]['firstname'];
$lastname = $result[0]['lastname'];
$email = $result[0]['email'];
First of all,to make sure the infomation of mysql is right,like port.
and I wonder the code of you $result = Getcourse($coeficient,$con);, how the var coeficient come from.Then
You can try the code below:
$mysqli=new mysqli("localhost","root","root","123");
$query="select * from test";
$result=$mysqli->query($query);
if ($result) {
if($result->num_rows>0){
while($row =$result->fetch_array() ){
echo ($row[0])."<br>";
echo ($row[1])."<br>";
echo ($row[2])."<br>";
echo ($row[3])."<br>";
echo "<hr>";
}
}
}else {
echo 'failure';
}
$result->free();
$mysqli->close();

Categories