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

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.

Related

last_insert:_id always returns 0

In PHP the MySQL method (like the PDO::lastInertID()) always returns 0 whereas MySQL returns in properly.
I tried try-catch, object initialization, but didn't work.
abstract class Database
{
private static $host = "localhost";
private static $dbname = "loquor";
private static $charset = "utf8";
private static $dbType = "mysql";
private static $dbUsername = "root";
private static $dbPassword = "";
private static function connect ()
{
$dsn = self::$dbType . ":host=" . self::$host . ";dbname=" . self::$dbname . ";charset=" . self::$charset;
$connex = new PDO( $dsn, self::$dbUsername, self::$dbPassword );
$connex->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $connex;
}
public static function query ($query, $params = [], $lastInsertID = false)
{
if(!$lastInsertID)
{
$statement = self::connect()->prepare($query);
$statement->setFetchMode(\PDO::FETCH_OBJ);
$statement->execute( $params );
}
else
{
if (explode ( " ", $query )[0] === "INSERT")
{
$statement = self::connect()->query($query);
$x = self::connect()->query("SELECT LAST_INSERT_ID() AS L")->fetch()['L'];
echo $x; //always 0
}
}
if (explode (" ", $query )[0] === "SELECT")
return $statement;
}
}
Database::query("INSERT INTO test(name) VALUES ('test_name') ", [], true));
Returns 0.

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

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.

convert sql add update and delete function in to mysqli

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.

Get results from from MySQL using PDO

I'm trying to retrieve data from my table using PDO, only I can't seem to output anything to my browser, I just get a plain white page.
try {
// Connect and create the PDO object
$conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
$conn->exec("SET CHARACTER SET utf8"); // Sets encoding UTF-8
$lastIndex = 2;
$sql = "SELECT * FROM directory WHERE id > :lastIndex AND user_active != '' LIMIT 20"
$sth = $conn->prepare($sql);
$sth->execute(array(':lastIndex' => $lastIndex));
$c = 1;
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
echo 'ALL STYLING ETC RESULTS HERE';
$c++;
}
$conn = null; // Disconnect
}
EXAMPLE.
This is your dbc class
<?php
class dbc {
public $dbserver = 'server';
public $dbusername = 'user';
public $dbpassword = 'pass';
public $dbname = 'db';
function openDb() {
try {
$db = new PDO('mysql:host=' . $this->dbserver . ';dbname=' . $this->dbname . ';charset=utf8', '' . $this->dbusername . '', '' . $this->dbpassword . '');
} catch (PDOException $e) {
die("error, please try again");
}
return $db;
}
function getAllData($qty) {
//prepared query to prevent SQL injections
$query = "select * from TABLE where qty = ?";
$stmt = $this->openDb()->prepare($query);
$stmt->bindValue(1, $qty, PDO::PARAM_INT);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $rows;
}
?>
your PHP page:
<?php
require "dbc.php";
$getList = $db->getAllData(25);
foreach ($getList as $key=> $row) {
echo $row['columnName'] .' key: '. $key;
}

Categories