Getting no database selected message. PHP,mysql - php

I have a database at local server. I am trying to access this database. I have table of venueTypeMaster in the database. I tried to get all the venuetypes from database. But when I run the script message I get is - 'No database selected'.
I have a class in which I have created two functions in php script. For createVenue it dose not send any message and the query has been executed successfully. But for getVeunueTypes it is showing this message. Connection for both is same.
DB Script:
<?php
include_once("config.php");
include_once("exceptions.php");
class DB {
static $con;
public static function getConnection() {
try {
if ( DB::$con == null ) {
DB::$con = mysqli_connect(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD);
if ( DB::$con) {
$status = mysqli_select_db(DB::$con,DB_NAME);
if (! $status ) throw new DBSelectionExcpetion(mysqli_error());
return DB::$con;
} else {
$e = new DBConnectionException(mysqli_error());
throw $e;
}
}
return DB::$con;
} catch(DBConnectionException $e) {
throw $e;
} catch(DBSelectionExcpetion $de) {
throw $de;
}
return null;
}
?>
venueTypes script
<?php
include("exceptions.php");
include("DB.php");
include("config.php");
class VenueTypes {
public function getVenueTypes() {
try {
$con = DB::getConnection();
$query = "select * from venueTypeMaster";
$rs = mysql_query($query) or die (json_encode(array("result"=>-1, "message"=>mysql_error())));
$n = mysql_num_rows($rs);
$vt = array();
if ( $n > 0 ) {
while ( $row = mysql_fetch_assoc($rs)) {
$vt[] = $row;
}
$result = array("result"=>1, "message"=>"success", "venueTypes" => $vt);
return json_encode($result);
} else {
$result = array("result"=>-1, "message"=>"Venue types list is empty");
return json_encode($result);
}
} catch(DBConnectionException $e) {
$result = array("result"=>-1, "message"=> $e -> getMessage());
return json_encode($result);
}
return null;
}
public function createVenueType($fields) {
try {
$required = array("venuetype", "active", "entry_by", "entry_date", "entry_time", "last_modify_date", "ip_addr","venue_name");
$actual = array_keys($fields);
$intersection = array_intersect($required, $actual);
$n1 = sizeof($required);
$n2 = sizeof($intersection);
if ( $n1 != $n2 ) {
throw new MissingParameterException();
}
$con = DB::getConnection();
$keys = array_keys($fields);
$values = array_values($fields);
$columns = implode(",", $keys);
$n = sizeof($values);
for($i=0;$i<$n; $i++) {
$values[$i] = "'" . mysqli_real_escape_string($con,$values[$i]) . "'";
}
$columnValues = implode(",", $values);
$query = "insert into venuetypemaster($columns) values($columnValues)";
mysqli_query($con,$query) or die (json_encode(array("result"=>-1, "message"=>mysqli_error())));
$af = mysqli_affected_rows($con);
if ( $af == 1 ) {
$venuetypeId = mysqli_insert_id($con);
$result = array("result"=>1, "message"=>"success", "venuetypeId" => $venuetypeId);
return json_encode($result);
} else {
$result = array("result"=>-1, "message"=>"Failed to register");
return json_encode($result);
}
} catch(DBConnectionException $e) {
$result = array("result"=>-1, "message"=> $e -> getMessage());
return json_encode($result);
}
return null;
}
?>
getVenueType script
<?php
header("Content-type: application/json");
if ( $_SERVER['REQUEST_METHOD']=='GET') {
include_once ("../include/VenueTypes.php");
try {
$v = new VenueTypes();
$response = $v -> getVenueTypes();
//$response is null means something went wrong as a result we got null result from above statement
if ( $response == null ) {
$response = json_encode(array("result" => -2, "message" => "Empty result"));
echo $response;
} else {
echo $response;
}
} catch(Exception $e) {
$result = array("result" => -1, "message" => $e -> getMessage());
echo json_encode($result);
}
} else {
$result = array("result" => -3, "message" => "Unsupported method : " . $_SERVER['REQUEST_METHOD']);
echo json_encode($result);
}
?>
Can anyone help please.. Thank you..

The problem is that you are mixing between the mysqli_xxx() and mysql_xxx() functions. These two libraries are not compatible with each other; you must only use one or the other throughout your code.
Since the mysql_xxx() functions are obsolete and deprecated, that means you should only use mysqli_xxx().
Change all occurrences of mysql_ in your code to mysqli_.
You will also need to make other changes to these lines of code -- notably this will include adding the DB reference variable (ie the variable returned by getConnection()), but some other syntax changes may also be necessary.

Related

PHP, not display all inside my array, but only first resulting

$projects = array('1' => $link1, '2' => $link2);
function server_status($projects) {
foreach ($projects as $server) {
$api_status = ping_api($server);
if ($api_status == 1) {
$json = json_decode(file_get_contents($server), true);
foreach ($json as $obj) {
if ($obj['online'] < 1) {
// OFFLINE
return -1;
}
else {
// ONLINE
return $obj['online'];
}
}
} else {
// MAINTENANCE
return 0;
}
}
}
function cache_status($data) {
echo $data;
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=test", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
foreach ($data as $status) {
// server id + status
$sql = "UPDATE projects SET status=:status WHERE id=:server_id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':status', $status, PDO::PARAM_INT);
$stmt->bindParam(':server_id', 1, PDO::PARAM_INT);
$stmt->execute();
}
}
$problem = array(server_status($projects));
print_r($problem);
My problem is, when I print_r the variable $problem it should return two results in array, since there are two results but it only returning the first result from array as an .. example: Array ( [0] => 260 )
IF anyone is kind enough to look at my code and tell me what I am doing wrong, I would be very greatful
You are using return statement inside your loop that is why it breaks your loop on first iteration and returns what ever you have mentioned to the original call of function. To resolve this issue you need to collect the response from each iteration in array and in the end of function return your response for each iteration something like
function server_status($projects) {
$response= array();
$status = 0; // default status
foreach ($projects as $server) {
$api_status = ping_api($server);
if ($api_status == 1) {
$json = json_decode(file_get_contents($server), true);
foreach ($json as $obj) {
if ($obj['online'] < 1) {
// OFFLINE
$status= -1;
}
else {
// ONLINE
$status = $obj['online'];
}
}
}
$response[] = array('server'=>$server,'status'=>$status);
}
return $response;
}

Undefined index:session LOOP NOT WORKING php, pdo oop

I make users online page using PHP - OOP - PDO
include_once '../database.php';
$db = new database();
$getRows = $db->getRows('select * from visitors_online');
$gr = $db->rowCount();
$online = '';
$getRow = $db->getRow('select * from user_online');
$gr2 = $db->rowCount();
if(!empty($gr2)) {
try {
while ($getR = $getRow){
$getRow = $db->getRow('select * from users where id = ?',[$getR['session']]);
echo ', &nbsp '.$getRow['username'].' &nbsp ';
}
} catch (PDOException $e) {
die('Error :'. $e->getMessage());
}
$total = $gr + $gr2;
The problems is:
* Not show any users except Admin, also I got this :
ONLINE
admin
Notice: Undefined index: session in /Applications/MAMP/htdocs/baws/admin/online.php on line 56
,
.Users = 0 ,Member = 2 , Register = 2
Who is online list
Here is the function from Database class
// Get row by id, username, or email etc..
public function getRow($query, $para = []){
try {
$this->stmt = $this->datab->prepare($query);
$this->stmt->execute($para);
return $this->stmt->fetch();
} catch (PDOException $e) {
throw new Exception($e->getMessage());
}
}
Any Help
Thanks
I tried to simplify a bit your code as I do not know your class details and it s messy.
The problem is you are not binding stuff properly neither fetching them properly too. Also, you are preparing the second query, each time you loop inside the query 1 results , that is useless. prepare both (withyour class or not) and just bind and execute.
$stmt1 = $db->prepare('select * from user_online where id= ?');
$result1 = getRows($stmt1, "1");
$gr1 = $db->rowCount();
if (!empty($gr1)) {
$stmt2 = $db->prepare('select * from users where id = ?');
foreach ($result1 as $key1 => $h1) {
$stmt2->bindParam(1, $h1['session'], PDO::PARAM_INT);
$stmt2->execute();
$result2 = $stmt2->fetchAll(PDO::FETCH_ASSOC);
if (count($result2) !== 0) {
foreach ($result2 as $key2 => $r2) {
echo ', &nbsp ' . $r2['username'] . ' &nbsp ';
}
}
}
}
function getRow($query, $para) {
$stmt1->bindParam(1, $para, PDO::PARAM_INT);
try {
$stmt1->execute($para);
$result1 = $stmt1->fetchAll(PDO::FETCH_ASSOC);
return $result1;
} catch (PDOException $e) {
throw new Exception($e->getMessage());
}
}
Please find the database class here
class database {
public $isConn;
protected $datab;
private $stmt;
public function __construct() {
$this->connect();
}
// connect to database
private function connect(){
$host = 'localhost';
$db = 'baws';
$user = 'root';
$pass = 'root';
$option = [];
$this->isConn = TRUE;
try {
$this->datab = new PDO('mysql:host='.$host.';dbname='.$db.';charset=utf8', $user, $pass, $option);
$this->datab->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->datab->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
} catch (PDOException $e) {
echo '<h3>Not connected</h3>' . $e->getMessage();
}
}
// Disconnected from database
private function disconnect(){
$this->isConn = NULL;
$this->datab = FALSE;
}
//insert to database
public function insertRow($query, $para = []){
try {
$this->stmt = $this->datab->prepare($query);
$this->stmt->execute($para);
return TRUE;
} catch (PDOException $e) {
throw new Exception($e->getMessage());
}
}
//update row to database
public function updateRow($query, $para = []){
$this->insertRow($query, $para);
}
//Delete row from database
public function deleteRow($query, $para = []){
$this->insertRow($query, $para);
}
// Get row by id, username, or email etc..
public function getRow($query, $para = []){
try {
$this->stmt = $this->datab->prepare($query);
$this->stmt->execute($para);
return $this->stmt->fetch();
} catch (PDOException $e) {
throw new Exception($e->getMessage());
}
}
}
online.php Page
ob_start();
echo "ONLINE <br>";
include_once '../database.php';
$db = new database();
try {
$session=$_COOKIE['id'];
$time=time();
$time_check=$time-300; //SET TIME 10 Minute
$getRow = $db->getRow("SELECT * FROM user_online WHERE session = ?", [$session]);
$count =$db->rowCount($getRow);
if($count == '0'){
$insertRow = $db->insertRow("INSERT INTO user_online(session, time)VALUES(? , ?)",[$session, $time ]);
}
elseif($count != '0'){
$updateRow = $db->updateRow("UPDATE user_online SET time = ? WHERE session = ?", [$time, $session]);
}else{
$deleteRow = $db->deleteRow("DELETE FROM user_online WHERE time < ? ", [$time_check]);
}
} catch (PDOException $e) {
die('Error :'. $e->getMessage());
}
try {
$ip=$_SERVER['REMOTE_ADDR'];
$session=$ip;
$time=time();
$time_check=$time-300; //SET TIME 10 Minute
$deleteRow = $db->deleteRow("DELETE FROM visitors_online WHERE time < ? ", [$time_check]);
} catch (PDOException $e) {
throw new Exception($e->getMessage());
}
$getRows = $db->getRows('select * from visitors_online');
$gr = $db->rowCount();
$online = '';
$getRow = $db->getRow('select * from user_online');
$gr2 = $db->rowCount();
if(!empty($gr2)) {
try {
while ($getR = $getRow){
$getRow = $db->getRow('select * from users where id = ?',[$getR['session']]);
echo ', &nbsp '.$getRow['username'].' &nbsp ';
}
} catch (PDOException $e) {
die('Error :'. $e->getMessage());
}
$total = $gr + $gr2;
} //end

Unable to get error info with PDO in PHP

I am in the process of learning PDO and am trying to implement it in my current project. When I used mysqli, I could get detailed info about any error using mysqli_error($connection). I googled at what the comparable for PDO would be and found this post, and decided to implement it in my code. However, I am unable to get any error messages even when I know there is an obvious error in the sql statement.
Relevant code:
class Database {
public $connection;
function __construct() {
$this->open_database_connection();
}
public function open_database_connection() {
try {
$this->connection = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USER, DB_PASSWORD);
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->connection->setAttribute( PDO::ATTR_EMULATE_PREPARES, false);
} catch(PDOException $e) {
echo $e->getMessage();
die('Could not connect');
}
} // end of open_database_connection method
public function query($sql, $params = []) {
try {
$query = $this->connection->prepare($sql);
} catch (Exception $e) {
var_dump('mysql error: ' . $e->getMessage());
}
foreach($params as $key => $value) {
if ($key === ':limit') {
$query->bindValue($key, $value, PDO::PARAM_INT);
} else {
$query -> bindValue($key, $value);
}
}
try {
$query->execute();
} catch(Exception $e) {
echo 'Exception -> ';
var_dump($e->getMessage());
}
/*
DID NOT WORK:
if (!$query->execute()) {
print_r($query->errorinfo());
}*/
$result = $query->fetchAll(PDO::FETCH_ASSOC);
$this->confirm_query($result);
return $result;
} // end of query method
function confirm_query($query) {
if (!$query) {
die('mysql error: ');
}
}
When I run the code, I do get the "mysql error", but I do not get any details about it. What am I doing wrong?
Update: As requested, I am providing additional details below.
What I am trying to do is get the user's login detail to be verified. To that end, once the user inputs his credentials , this code runs:
if (isset($_POST['submit'])) {
$username = trim($_POST['username']);
$password = trim($_POST['password']);
//check the database for the user
$user_found = User::verify_user($username, $password);
Relevant code from the User class:
public static function verify_user($username, $password) {
global $db;
$username = $db->escape_string($username);
$password = $db->escape_string($password);
$values = [ ":username" => $username,
":password" => $password,
":limit" => 1
];
$result_array = self::find_this_query("SELECT * FROM users WHERE username=:username AND password=:password LIMIT :limit", true, $values);
return !empty($result_array)? array_shift($result_array) : false;
}
public static function find_this_query($sql, $prepared = false, $params = []) {
global $db;
$the_object_array = array();
$result = $db->query($sql, $params);
$arr_length = count($result);
for ($i = 0; $i < $arr_length; $i++) {
$the_object_array[] = self::instantiation($result[$i]);
}
return $the_object_array;
}
public static function instantiation($the_record) {
$the_object =new self; //we need new self because $the_record corresponds to one user!
foreach($the_record as $the_attribute => $value) {
if ($the_object->has_the_attribute($the_attribute)) {
$the_object->$the_attribute = $value;
}
}
return $the_object;
}
public function has_the_attribute($attribute) {
$object_properties = get_object_vars($this);
return array_key_exists($attribute, $object_properties);
}
You have to use PDO::errorInfo():
(...)
public function query($sql, $params = []) {
try {
$query = $this->connection->prepare($sql);
if( !$query )
{
$error = $this->connection->errorInfo();
die( "mysql error: {$error[2]}" );
}
} catch (Exception $e) {
var_dump('mysql error: ' . $e->getMessage());
}
(...)
}
PDO::errorInfo returns an array:
Element 0: SQLSTATE error code (a five characters alphanumeric identifier defined in the ANSI SQL standard);
Element 1: Driver-specific error code;
Element 2: Driver-specific error message.

Mysqli query function insert duplicate lines

I have been trying to insert a new line to mysql db but insert(){...} function has inserted duplicate lines.
I also have tried several methods to insert but it doesn't works. All of the methods have inserted duplicate rows .
How can I fix the problem? Do you have any idea?
Thank you for your help & advice.
protected $db;
public function __construct() {
try {
$this->db = new mysqli('localhost', 'root', '', 'trigger');
$this->db->set_charset("utf8");
} catch (mysqli_sql_exception $e) {
throw new SmartyException('Mysql Resource failed: ' . $e->getMessage());
}
}
public function select($table, $rows = "", $where = "", $return_type = "") {
if (empty($rows)) {
$rows = "*";
}
if (empty($where)) {
$where = "";
} else {
$where = "where " . $where;
}
try {
$query = $this->db->query("SELECT $rows FROM $table $where");
if ($return_type == "json") {
return json_encode($query);
} else {
return $query;
}
} catch (mysqli_sql_exception $exc) {
return $exc->getMessage();
}
}
public function insert($table, $params) {
$_keyArr = array();
$_valueArr = array();
foreach ($params as $key => $value) {
$_keyArr[] .= $key;
$_valueArr[] .= $value;
}
$keys = implode("`,`", $_keyArr);
$values = implode("','", $_valueArr);
$query = $this->db->query("INSERT INTO `$table` (`$keys`) VALUES('$values')");
try {
return $query;
} catch (mysqli_sql_exception $ex) {
return $ex->getMessage();
}
}
-------------Answer to matt-------------
I call with following code:
if ($this->db->insert("table_name", array("path" => "test", "flow_name" => "test"))) {
echo 'ok';
} else {
echo 'not ok';
}
-------------Answer to Pavel-------------
"REPLACE INTO" didn't work. The problem occured again.
Just use REPLACE INTO instead INSERT INTO
$query = $this->db->query("REPLACE INTO `$table` (`$keys`) VALUES('$values')");

PDO do not work when i check ip

Today i tired pass from the mysql connection to PDO. And i met a problem.
require('config.php');
function GetAll($query, $params) {
global $db;
try {
$sth = $db->prepare($query);
}
catch (PDOException $e) {
return null;
}
try {
$sth->execute($params);
}
catch (PDOException $e) {
return null;
}
$result = $sth->fetchAll();
return $result;
}
if ($fetch = GetAll("SELECT `loggedip` FROM `ipcheck` WHERE `loggedip`=':ipcheck'", array(":ipcheck" => $iptocheck))) {
$resultx = $db->prepare("SELECT `failedattempts` FROM `ipcheck` WHERE `loggedip`='$iptocheck'");
$resultx->execute();
while ($rowx = $resultx->fetch()) {
;
}
$loginattempts_total = $rowx['failedattempts'];
echo "$loginattempts_total";
if ($loginattempts_total > $maxfailedattempt) {
header(sprintf("Location: %s", $forbidden_url));
exit;
}
}
this is my script. in PDO and his don't work. when my ip is banned should not see, but i see the page. PLEASE HELP ((

Categories