How to execute a query multiple time in mysqli Connection using PHP - php

only work when $i=0;
<?php
include 'db.php';
$con = new db();
$db = $con->getConnection();
$i = 0;
while($i <= 10){
$query = "call rep_summary('$date')";
$result = $db->query($query);
while ($data = $result->fetch_assoc()) {
$user = $data['username'];
$id = $data['id'];
echo $user;
}
$i++;
}
$db->close();
?>
the following code work fine but its take too much time and for that I want to reuse connection
<?php
include 'db.php';
$i = 0;
while($i <= 10){
$con = new db();
$db = $con->getConnection();
$query = "call rep_summary('$date')";
$result = $db->query($query);
while ($data = $result->fetch_assoc()) {
$user = $data['username'];
$id = $data['id'];
echo $user;
}
$i++;
}
$db->close();
?>
and db class
<?php
class db {
var $_host = "localhost";
var $_user = "root";
var $_password = "";
var $_database = "test";
var $db;
public function __construct() {
$this->db = new mysqli($this->_host, $this->_user, $this->_password, $this->_database);
$this->db->set_charset("utf8");
}
public function getConnection() {
if ($this->db->connect_errno > 0) {
die('Unable to connect to database [' . $this->db->connect_error . ']');
}
return $this->db;
}
}
How I can execute query in a single connection

you should instantiate the db object outside of the loop, and close it after:
$con = new db();
$i = 0;
while($i <= 10){
$db = $con->getConnection();
$query = "call rep_summary('$date')";
$result = $db->query($query);
while ($data = $result->fetch_assoc()) {
$user = $data['username'];
$id = $data['id'];
echo $user;
}
$i++;
}
$db->close();

Try moving the db connection and close functions outside the while loop. You can execute multiple queries on same connection.
include 'db.php';
$con = new db();
$db = $con->getConnection();
$date = date('Y-m-d');
$i = 0;
while($i <= 10){
$query = "call rep_summary('$date')";
$result = $db->query($query);
while ($data = $result->fetch_assoc()) {
$user = $data['username'];
$id = $data['id'];
echo $user;
}
$i++;
}
$db->close();

Related

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");
}
?>

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();

Querying two databases with PDO

I'm trying to change my queries from mysql to PDO because I need to query at the same time two different databases on different servers.
I've done these classes so far
class Db extends PDO {
public $db;
public function __construct($dbhost = 'host1', $dbname = 'db1', $dbuser = 'user1', $dbpass = 'user2', $dbtype = 'mysql') {
PDO::__construct($dbtype . ':host=' . $dbhost . ';dbname=' . $dbname, $dbuser, $dbpass);
}
function sql_query($sql) {
$result = PDO::query($sql);
return $result;
}
function sql_fetcharray($result) {
$rs = $result->fetch(PDO::FETCH_ASSOC);
return $rs;
}
function sql_numrows($result) {
$rs = $result->rowCount();
return $rs;
}
}
class Db2 extends Db {
public $db;
public function __construct($dbhost = 'host2', $dbname = 'db2', $dbuser = 'user2', $dbpass = 'pass2', $dbtype = 'mysql') {
PDO::__construct($dbtype . ':host=' . $dbhost . ';dbname=' . $dbname, $dbuser, $dbpass);
}
function sql_query($sql) {
parent::sql_query($sql);
$result = PDO::query($sql);
return $result;
}
function sql_fetcharray($result) {
$rs = $result->fetch(PDO::FETCH_ASSOC);
return $rs;
}
function sql_numrows($result) {
$rs = $result->rowCount();
return $rs;
}
}
and then
$db = new Db2;
$sql = "query";
$result = $db->sql_query($sql);
but the query affects only the second database.
Anyone can help?
Thanks a lot
you had to run your query twice against two databases. don't expect the inheritance to do that for you
$db = new Db2();
$sql = "query";
$result = $db->sql_query($sql);
$db1 = new Db();
$sql = "query";
$result1 = $db1->sql_query($sql);
I don't think you needed another child class, you can easily switch database using :
USE DATABASENAME
So for example you can do:
$db = new Db;
$sql = "query";
$result = $db->sql_query($sql);
$db->sql_query('USE DB2');
$sql2 = "query2";
$result2 = $db->sql_query($sql2);
or perhaps create a function to select db:
function select_db($db) {
$result = PDO::query('USE $db');
return $result;
}
then use it:
$db = new Db;
$sql = "query";
$result = $db->sql_query($sql);
$db->select_db('DB2');
$sql2 = "query2";
$result2 = $db->sql_query($sql2);

Simple mySQLi select to an array

Building from a tutorial I found online.
I m trying to select all items from the 'items' table and create an array. Not sure how this is suppose to work. This $result = $this->connection->query($q); is what is causing the problem.
<?php
//DB.class.php
class DB {
protected $db_name = 'dbname';
protected $db_user = 'user';
protected $db_pass = 'pass';
protected $db_host = 'localhost';
protected $connection;
public function connect() {
$connection = new mysqli($this->db_host, $this->db_user, $this->db_pass, $this->db_name);
// check connection
if ($connection->connect_error) {
trigger_error('Database connection failed: ' . $connection->connect_error, E_USER_ERROR);
}
}
public function resultToArray($result) {
$rows = array();
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
public function sel($table) {
$q = "SELECT * FROM $table";
$result = $this->connection->query($q);
$rows = $this->resultToArray($result);
return $rows;
$result->free();
}
}
make a construct function like
public $mysqli;
public function __construct()
{
$mysqli = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
$this->mysqli = $mysqli;
}
public function sel($table,$whr)
{
$query = "SELECT * FROM ".$table." where id='$whr'";
$result = $this->mysqli->query($query);
$total = array();
while($row = $result->fetch_assoc()){
//print_r($row);die;
$total[] = $row;
}//print_r($total);die;
return $total;
}
I think you should set a constructor, but if you don't want, just return an instance of it first and set your $this->connection property instead of $connection (the normal variable):
class DB {
protected $db_name = 'test';
protected $db_user = 'test';
protected $db_pass = 'test';
protected $db_host = 'localhost';
protected $connection;
public function connect() {
$this->connection = new mysqli($this->db_host, $this->db_user, $this->db_pass, $this->db_name);
// ^^ this one, not $connection
// check connection
if ($this->connection->connect_error) {
trigger_error('Database connection failed: ' . $connection->connect_error, E_USER_ERROR);
}
return $this->connection; // then return this
}
public function resultToArray($result) {
$rows = array();
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
public function sel($table) {
$q = "SELECT * FROM $table";
$result = $this->connection->query($q);
// ^ so that if you call this, you have the mysqli object
$rows = $this->resultToArray($result);
return $rows;
$result->free();
}
}
$db = new DB(); // instantite,
$db->connect(); // then connect, shouldn't have to have this if you put the connection automatically on construct
$result = $db->sel('users'); // feed a valid existing table name
echo '<pre>';
print_r($result);

Multi URL paramaters with PHP and SQL

<?php
$username = "username";
$password = "password";
$hostname = "localhost";
$database = "database";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$selected = mysql_select_db($database,$dbhandle)
or die("Could not select database");
$id = 0;
if(isset($_GET['Day'])){ $id = (int)$_GET['Day']; }
if(!$id){
$query = "SELECT * FROM `TimeTable`";
} else {
$query = "SELECT * FROM `TimeTable` WHERE `Day`='".$id."'";
}
$result = mysql_query($query);
$rows = array();
while($r = mysql_fetch_assoc($result)) {
$rows[] = $r;
}
or die(mysql_error());
print json_encode($rows);
?>
This code worked previously, but has now stopped, and is producing Parse error: syntax error, unexpected T_LOGICAL_OR in /Directory/TimeTable.php on line 27
I am also looking to add more parameters, (eg: Where Day = $id and Year = $Year )
while($r = mysql_fetch_assoc($result)) {
$rows[] = $r;
}
or die(mysql_error());
This is a syntax error, doesn't know what to do with that or die() statement. Change to this:
$result = mysql_query($query);
if (!$result) {
die('Error');
}
while(...) {
}
I have looked up the new mysql functions an have changed to mysqli.
<?php
$username = "username";
$password = "password";
$hostname = "localhost";
$database = "database";
$link = mysqli_connect($hostname, $username, $password, $database);
if(mysqli_connect_errno()){
echo mysqli_connect_error();
}
$id= 0;
if(isset($_GET['Day'])){ $id=(int)$_GET['Day']; }
$year = 0;
if(isset($_GET['Year'])){ $year=(int)$_GET['Year'];}
if(!$id){
$query = "SELECT * FROM TimeTable";
} else {
if (!year) {
$query = "Select * FROM TimeTable";
} else {
$query = "SELECT * FROM TimeTable WHERE Day=$id AND Year=$year";
}
}
$rows = array();
//Perform JSON encode
if($result = mysqli_query($link, $query)){
while($r = mysqli_fetch_assoc($result)){
$rows[] = $r;
}
}
print json_encode($rows);
?>

Categories