PHP error in connect.php - php

I am getting the below error. I have copy paste the code. I have very little knowledge of PHP please guide me.
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /home/test_bader/public_html/include/connect.php on line 66
<?php
$DBHOST = "localhost";
$DBUSER = "tese_test";
$DBPASS = "";
$DB = "test_bader";
$default_dbname="test_bader";
*/
$DBHOST = "localhost";$
$Port= "3306";
$DBUSER = "test_test";
$DBPASS = "test#.";
$DB = "test_bader";
$default_dbname="test_bader";
$con=mysql_connect($DBHOST,$DBUSER,$DBPASS) or die(mysql_error());
mysql_select_db($DB);
function db_connect()
{
global $DBHOST, $DBUSER, $DBPASS, $default_dbname, $DB , $MYSQL_ERRNO, $MYSQL_ERROR;
$link_id = mysql_connect("$DBHOST","$DBUSER","$DBPASS");
if (!$link_id)
{
$MYSQL_ERRNO = 0;
$MYSQL_ERROR = "Connection Fail to the host $DBHOST.";
}
else if(empty($DB ) && !mysql_select_db($default_dbname))
{
$MYSQL_ERRNO = mysql_errno();
$MYSQL_ERROR = mysql_error();
return 0;
}
else if(!empty($DB ) && !mysql_select_db($DB ))
{
$MYSQL_ERRNO = mysql_errno();
$MYSQL_ERROR = mysql_error();
return 0;
}
else return $link_id;
}
function sql_error()
{
global $MYSQL_ERRNO, $MYSQL_ERROR;
if(empty($MYSQL_ERROR))
{
$MYSQL_ERRNO = mysql_erron();
$MYSQL_ERROR = mysql_error();
}
return "$MYSQL_ERRNO : $MYSQL_ERROR";
}
function q($st)
{
$r=mysql_query($st);
return $r;
}
function f($st)
{
$r=mysql_fetch_array($st);
return $r;
}
?>

<?php
$DBHOST = "localhost";
$DBUSER = "tese_test";
$DBPASS = "";
$DB = "test_bader";
$default_dbname="test_bader";
*/
$DBHOST = "localhost";$
$Port= "3306";
$DBUSER = "test_test";
$DBPASS = "test#.";
$DB = "test_bader";
$default_dbname="test_bader";
$con=mysql_connect($DBHOST,$DBUSER,$DBPASS) or die(mysql_error());
mysql_select_db($DB);
function db_connect()
{
global $DBHOST, $DBUSER, $DBPASS, $default_dbname, $DB , $MYSQL_ERRNO, $MYSQL_ERROR;
$link_id = mysql_connect("$DBHOST","$DBUSER","$DBPASS");
if (!$link_id)
{
$MYSQL_ERRNO = 0;
$MYSQL_ERROR = "Connection Fail to the host $DBHOST.";
}
else if(empty($DB ) && !mysql_select_db($default_dbname))
{
$MYSQL_ERRNO = mysql_errno();
$MYSQL_ERROR = mysql_error();
return 0;
}
else if(!empty($DB ) && !mysql_select_db($DB ))
{
$MYSQL_ERRNO = mysql_errno();
$MYSQL_ERROR = mysql_error();
return 0;
}
else return $link_id;
}
function sql_error()
{
global $MYSQL_ERRNO, $MYSQL_ERROR;
if(empty($MYSQL_ERROR))
{
$MYSQL_ERRNO = mysql_erron();
$MYSQL_ERROR = mysql_error();
}
return "$MYSQL_ERRNO : $MYSQL_ERROR";
}
function q($st)
{
$r=mysql_query($st);
return $r;
}
function f($st)
{
$r=mysql_fetch_array($st);
return $r;
}
?>

Related

I want to display table rows in same class and difference function in PHP

how to display rows in my users table in PHP
arr() function can't connect with database
class DB {
protected $db_server = 'localhost';
protected $db_username = 'root';
protected $db_password = 'root';
protected $db_name = 'dbname';
public function connect() {
$connect_db = new mysqli($this->db_server, $this->db_username, $this->db_password, $this->db_name);
if(mysqli_connect_errno()) {
printf("Connection failed!", mysqli_connect_error());
exit();
} else {
echo "connected";
}
return true;
}
function arr() {
$conn = $this->connect();
if($query = mysqli_query($conn, "SELECT * FROM users")) {
echo 'row is ' . mysqli_num_rows($query);
}
}
}
$db = new DB();
$db->arr();
result -> "connected row is " not count rows
In the connect() function, change
return true;
to
return $connect_db;
so that it returns the connection object. Then you can use it in your other functions.

php sqlsrv connection by multiple servers to one specific database

So I have 3 servers(192.168.0.21 , 192.168.0.22 and 192.168.0.23) and I would like them to connect to a database called Pensions they are all using sql server (UID and PWD)authentication. Is it possible to achieve this using php and sqlsrv_connect()? This the connect.php:
<?php
#first start session
session_start();
// session time out after no activity for 4 minutes
if ($_SESSION['TimeOut'] + (5 * 60) < time()) {
// session timed out
header("Location: ./sessdestroy.php");
exit;
} else {
// store new request time.
$_SESSION["TimeOut"] = time();
}
function getConnection(){
$db = 0;
if(!$_SESSION['Database']){
$db = 0;
}else{
$db = $_SESSION['Database'];
}
$databaseName = 'Pension';
if ($db == 0)
{ // Country A
$serverName ='192.168.0.21';
$UID ='sa';
$PWD ='pass!';
$databaseName = 'Pension';
}
else if($db ==1)
{ // Country B
$serverName ='192.168.0.22';
$UID ='sa';
$PWD ='pass!';
$databaseName = 'Pension';
}
else
{ //Country C
$serverName ='192.168.0.23';
$UID ='sa';
$PWD ='pass!';
$databaseName = 'Pension';
}
//connection string
//echo "test here...";
//echo " S: ".$serverName." u: ".$UID." P: ".$PWD;
$serverName = "serverName";
$connectionInfo = array( "Database"=>"$databaseName", "UID"=>"$UID", "PWD"=>"$PWD");
$conn = sqlsrv_connect($serverName,$connectionInfo);
//exit();
//phpinfo();
if (!$conn)
{
exit("Connection Failed: " . $conn);
//try local server
if ($db == 1) {
$serverName ='192.168.0.20';
$UID ='fund_user';
$PWD ='fund_user';
$databaseName = 'Pension';
$conn = sqlsrv_connect($serverName,$connectionInfo);
if (!$conn) return 0;
$stmt = sqlsrv_query($databaseName,$conn);
return $conn;
}
return 0;
}
else
{
$stmt = sqlsrv_query($databaseName,$conn);
return $conn;
}
}
?>
Then this is the process.php (when a connection is established it leads the user to a homepage depending on the user role )
<?php
//give no error
ini_set("display warning",0);
#include connection
include('Connections/fundmaster.php');
if(!isset($_SESSION))
{
session_start();
}
//temp store for the database session before destory
$db = 0;
$db = $_SESSION["Database"];
if ($db==""){
$db = 0;
}
if (!isset($_SESSION["Database"]))
{
$_SESSION["Database"] = 0;
}
$_SESSION["Database"] = $db;
if($_POST['subLogin'])
{
$nationalID = $_POST['sname'];
$PWD = $_POST['Memberno'];
$conn = getConnection();
$sql = "select * from netlogin where NationalID = '";
$sql .= $nationalID ."' and vcPassword= '" .$PWD."'";
$sql = stripslashes($sql);
$stmt = sqlsrv_query($sql, $conn);
if($row = sqlsrv_fetch_array($stmt)){
$SchemeNo = $row[0];
$MemberNo = $row[1];
$userRole = $row[6];
session_start();
if (!isset($_SESSION["SchemeNo"]))
{
$_SESSION["SchemeNo"] = $SchemeNo;
}
if (!isset($_SESSION["MemberNo"]))
{
$_SESSION["MemberNo"] = $MemberNo;
}
if (!isset($_SESSION["userRole"]))
{
$_SESSION["userRole"] = $userRole;
}
$_SESSION["SchemeNo"] = $SchemeNo;
$_SESSION["MemberNo"] = $MemberNo;
$_SESSION["userRole"] = $userRole;
$_SESSION["Database"] = $db;
if($userRole == "1"){
header("Location:admin/adminarea.php");
}else{
header("Location:membersarea.php");
}
}else{
header("Location: login.php");
}
}else{
header("Location: login.php");
}
?>

Making a simple to use dynamic MySQL class that can read from and write to a database

I want to create a script that runs any query from through PHP the same way you would run it through the MySQL console just by calling MySQL::query([the query]);.
I have created a good portion of the PHP script already but I think I'm stuck. So far it can pull information just fine but it does not like it when I try to make any changes to the database itself. I would like it to also write to MySQL as well, but I can't figure out how to do it dynamically.
Here is the code I have so far:
<?php
include '..\..\shared\Error_Code.php';
class MySQL {
private static $host;
private static $username;
private static $password;
private static $database;
private static $logged_in = false;
public static function login($host, $username, $password, $database) {
self::$host = $host;
self::$username = $username;
self::$password = $password;
self::$database = $database;
if (self::confirm_login()) {
self::$logged_in = true;
} else {
self::$logged_in = false;
Error_Code::print(107.0); //There was an issue with the login.
}
}
public static function change_database($database) {
if (self::$logged_in) {
$old_database = self::$database;
self::$database = $database;
if (!self::confirm_login()) {
self::$database = $database;
Error_Code::print(107.1); //The database you entered dose not exist.
}
} else {
Error_Code::print(107.2); //You have not logged in yet.
}
}
private static function confirm_login($host = -1, $username = -1, $password = -1, $database = -1) {
$host = (($host != -1) ? $host : self::$host);
$username = (($username != -1) ? $username : self::$username);
$password = (($password != -1) ? $password : self::$password);
$database = (($database != -1) ? $database : self::$database);
if (!(is_null(self::$host) || is_null(self::$username) || is_null(self::$password) || is_null(self::$database))) {
$connection = mysqli_connect($host, $username, $password);
if ($connection) {
$response = mysqli_query($connection, "SHOW DATABASES");
$bg_db = array("information_schema", "mysql", "performance_schema", "phpmyadmin", "test");
if (!in_array(self::$database, $bg_db)) {
while ($row = mysqli_fetch_assoc($response)) {
if($row['Database'] == self::$database) {
return true;
}
}
}
Error_Code::print(107.8); //Login information is wrong.
return false;
} else {
Error_Code::print(107.9); //Login information is wrong.
return false;
}
} else {
Error_Code::print(107.7); //Login information is missing.
return false;
}
}
public static function logged_in() {
return self::$logged_in;
}
public static function query($query, $host = -1, $username = -1, $password = -1, $database = -1) {
$host = (($host != -1) ? $host : self::$host);
$username = (($username != -1) ? $username : self::$username);
$password = (($password != -1) ? $password : self::$password);
$database = (($database != -1) ? $database : self::$database);
$continue = self::confirm_login($host, $username, $password, $database);
if ($continue) {
return new Data($query, $host, $username, $password, $database);
} else {
return new Data($query, $host, $username, $password, $database);
Error_Code::print(107.3); //You have not logged into a database.
}
}
}
class Data {
private $query;
private $host;
private $username;
private $password;
private $database;
public function __construct($query, $host, $username, $password, $database) {
if ($query < 0) {
return $this;
} else {
$this->query = $query;
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->database = $database;
return $this->get();
}
}
//get data from a database using an SQL query
public function get() {
//query database
$connection = mysqli_connect($this->host, $this->username, $this->password, $this->database);
if ($connection) {
$response = mysqli_query($connection, $this->query);
//get data from query
if ($response) {
$rows = array();
while ($row = mysqli_fetch_array($response, MYSQLI_ASSOC)) {
array_push($rows, $row);
}
return $rows;
} else {
if (true) {
//<----- I THINK THIS IS WHERE I WOULD HAVE TO ADD THE CODE FOR MAKING CHANGES TO THE DATABASE
//$prepare = mysqli_prepare($connection, $this->query);
//mysqli_stmt_execute($prepare);
} else {
Error_Code::print(108.0); //Could not run query because there was no response
return -1;
}
}
} else {
Error_Code::print(108.1); //Could not run query because there was no connection
return -1;
}
}
//print the results of the query to a table
public function print_table($table_id = -1) {
$data = $this->get();
if ($data < 0) {
Error_Code::print(108.2); //Could not build table do to an issue with the query.
return -1;
} else {
$th = "<tr>";
foreach ($data[0] as $col => $value) {
$th = "$th<th>$col</th>";
}
$th = "$th</tr>";
$td = "";
foreach ($data as $row) {
$td = "$td<tr>";
foreach ($row as $col => $value) {
$td = "$td<td>$value</td>";
}
$td = "$td</tr>";
}
$table_id = ($table_id < 0) ? "" : " id='$table_id'";
echo "<table class='database_data'$table_id>$th$td</table>";
return 1;
}
}
}
?>
Any ideas on what I can change to get it to INSERT, DELETE, UPDATE and everything else.
Check this out:
https://github.com/indieteq/indieteq-php-my-sql-pdo-database-class
It might be a bit too much for your needs, but is, in my opinion, a great example of how to build a database class

Insert PDO Php - Error SQLSTATE [HY000]: General error -

When I run this php file shows me the error SQLSTATE [HY000]: General error. Why?
function Gethotspots($db) {
$regId = $_GET['regId'];
$sql = $db->prepare("INSERT INTO notificaciones (regId) VALUES ('" . $regId . "')");
$sql->execute();
$i = 0;
$pois = $sql->fetchAll(PDO::FETCH_ASSOC);
if (empty($pois)) {
$response["productos"] = array();
}
else {
foreach ($pois as $poi) {
$poi["actions"] = array();
$response["productos"][$i] = $poi;
$i++;
}
}
return $response["productos"];
}
$dbhost = "localhost";
$dbdata = "anuncios";
$dbuser = "root";
$dbpass = "";
try {
$db = new PDO("mysql:host=$dbhost; dbname=$dbdata", $dbuser, $dbpass, array(
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$response = array();
$response["productos"] = Gethotspots($db);
if (empty($response["productos"])) {
$response["errorCode"] = 20;
$response["errorString"] = "Ningun producto encontrado.";
} // if
else {
$response["errorCode"] = 0;
$response["errorString"] = "Todo correcto";
}
$jsonresponse = json_encode($response);
header('Access-Control-Allow-Origin: *');
echo $jsonresponse;
$db = null;
} catch (PDOException $e) {
echo $e->getMessage();
}
Thanks all!

PHP mySQL connection problems

Ok, I am completely baffled.
I am setting up an OO site. I have a class that defines all my database params, as follows:
$db->host= "localhost";
$db->name= "mydatabase";
$db->user= "user";
$db->pw = "password";
The class is being instantiated correctly and the values show up in pages that appear after this class has been loaded.
BUT, when I try to connect to this database from a different class, it does not connect. Here's how I am connecting:
$dbconn = mysql_connect($db->host, $db->user, $db->pw);
mysql_select_db($db->name, $dbconn);
Everything works fine if I take out the user, pw and name variables and hard code in the correct values, but if any of them is referenced using the db construct, no connection happens. Again, the db construct appears just fine on other pages and I am seeing the variable values being presented correctly. The $db->host variable, however, always works.
Here's is how I am constructing the db class:
class database {
var $host;
var $name;
var $user;
var $pw;
function __construct($host = "localhost", $name = "mydatabase", $user = "user", $pw = "password"){
$this->host = $host;
$this->name = $name;
$this->user = $user;
$this->pw = $pw;
}
}
and then I of course do
$db = new database();
Thanks in advance for any help!
Don't use PHP4
Why don't you just use PDO
What's the point of storing password or username as a object property?
Probably the problem is a $db variable scope
How to fix all of that?
class MyClass {
protected $db;
public function __construct(PDO $db) {
$this->db = $db;
}
public function doSth() {
$this->db->query('..');
}
}
$db = new PDO('mysql:dbname=mydatabase;host=localhost', 'user', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$obj = new MyClass($db);
$obj->doSth();
I think u are not passing parameters when creating object for initializing the database class constructor.
try using
$db=new database("localhost","dbname","user","password");
and then create the class as
class database {
var $host;
var $name;
var $user;
var $pw;
function __construct($host , $name , $user , $pw ){
$this->host = $host;
$this->name = $name;
$this->user = $user;
$this->pw = $pw;
}
Also include this class as file if written separately
and for connection u can now write
$conn=mysql_connect($db->host,$db->user,$db->pw);
mysql_select_db($db->name,$conn);
Hope this helped :)
<?php
/*
link.php
Created By Nicholas English
*/
$link = null;
$connection = null;
$servername = "";
$username = "";
$dbname = "";
$pass = "";
$mysqli = null;
$pdo = null;
$obj = null;
$pr = null;
$type = 3;
if ($type === 1) {
$mysqli = true;
$pdo = false;
$obj = true;
$pr = false;
} else {
if ($type === 2) {
$mysqli = true;
$pdo = false;
$obj = false;
$pr = true;
} else {
if ($type === 3) {
$mysqli = false;
$pdo = true;
$obj = false;
$pr = false;
} else {
$mysqli = null;
$pdo = null;
$obj = null;
$pr = null;
}
}
}
if ($mysqli === true && $obj === true) {
$link = new mysqli($servername, $username, $pass, $dbname);
if ($link->connect_error) {
die("Connection failed: " . $link->connect_error);
}
$connection = true;
} else {
if ($mysqli === true && $pr === true) {
$link = mysqli_connect($servername, $username, $pass, $dbname);
if (!$link) {
die("Connection failed: " . mysqli_connect_error());
}
$connection = true;
} else {
if ($pdo === true && $mysqli === false) {
try {
$link = new PDO("mysql:host=$servername;dbname=$dbname", $username, $pass);
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$connection = true;
}
catch(PDOException $e)
{
$connection = null;
echo "Connection failed: " . $e->getMessage();
}
} else {
$link = null;
$connection = null;
}
}
}
if ($connection == null && $link == null) {
$error = 1;
}
?>
Use mysqli or pdo for a more secure connection

Categories