Using two SELECT queries in php database connection - php

here is my_sqli database connection
class FbChatMock {
// Holds the database connection
private $dbConnection;
private $_dbHost = 'localhost';
private $_dbUsername = 'root';
private $_dbPassword = '';
public $_databaseName = 'erp5_temp2';
public function __construct() {
$this->dbConnection = new mysqli($this->_dbHost, $this->_dbUsername,
$this->_dbPassword, $this->_databaseName);
if ($this->dbConnection->connect_error) {
die('Connection error.');
}
}
i am getting two parameters in the getchat function:
public function getchat($userId, $id){
$meesage = array();
$query = "SELECT u.user_id FROM `users` u where u.id='$id'";
$resultObj = $this->dbConnection->query($query);
$user = $resultObj->fetch_assoc())
$userid = $user;
}
I am getting the $userid variable from the query and using it inside this query:
$query = "SELECT u.id,c.message,c.sent_on FROM `chat` c JOIN
`users` u ON c.user_id=u.user_id where u.id='$id' AND c.user_id='$userid'";
// Execute the query
$resultObj = $this->dbConnection->query($query);
// Fetch all the rows at once.
while ($rows = $resultObj->fetch_assoc()){
$meesage[] = $rows;
}
return $meesage;
And the problem is that my first sql query is not working correctly . i have tested it by showing $userid value from echo.

Chage this line
$userid = $user;
To this
$userid = $user['user_id'];
Because $user it is array with all columns you have selected, and you need get only ID from it.

Your problem lies here :
$user = $resultObj->fetch_assoc())
$userid = $user;
because mysqli::fetch_assoc() with retrieve an associative array. Thus you have to access it like so (given the column name in your select):
$userid = $user["user_id"];

Related

PHP script only display one row of data in android studio

I would like to ask how can I display many rows of data instead of only one row. The following code will only display one row of record instead of multiple records are available. I'm using mysqli_prepare statements here. Or the problem is on my android studio coding? My application is implemented with login function and coding as below.
<?php
$host="DB_HOST";
$user="DB_USER";
$password="DB_PASSWORD";
$db="DB_NAME";
$con = mysqli_connect($host,$user,$password,$db);
$parentic=$_POST["ParentIC"];
$password=$_POST["Password"];
$selectquery = mysqli_prepare($con, "SELECT Parents_Data.Name, Student_List.StudName, Student_List.StudIC, Student_List.Form,Student_List.Class,discipline_record.Date,discipline_record.RulesCode, discipline_record.TypesofMistakes,discipline_record.Punishment FROM discipline_record LEFT JOIN Student_List ON discipline_record.StudIC = Student_List.StudIC LEFT JOIN Parents_Data ON Student_List.ParentIC = Parents_Data.ParentIC WHERE Parents_Data.ParentIC = ? AND Parents_Data.Password = ? ");
mysqli_stmt_bind_param ($selectquery, "ss", $parentic, $password);
mysqli_stmt_execute($selectquery);
mysqli_stmt_store_result($selectquery);
mysqli_stmt_bind_result($selectquery,$name,$studname,$studic,$form,$classs,$ddate,$code,$mistakes,$punishment);
$user = array();
while(mysqli_stmt_fetch($selectquery))
{
$user[name]=$name;
$user[studname]=$studname;
$user[studic] = $studic;
$user[form]=$form;
$user[classs]=$classs;
$user[ddate]=$ddate;
$user[code]=$code;
$user[mistakes]=$mistakes;
$user[punishment]=$punishment;
}
echo json_encode($user);
mysqli_stmt_close($selectquery);
mysqli_close($con);
?>
I would go with something like that:
$userGroup = array();
$user = array();
while(mysqli_stmt_fetch($selectquery))
{
$user[name]=$name;
$user[studname]=$studname;
$user[studic] = $studic;
$user[form]=$form;
$user[classs]=$classs;
$user[ddate]=$ddate;
$user[code]=$code;
$user[mistakes]=$mistakes;
$user[punishment]=$punishment;
array_push($userGroup,$user);
}
echo json_encode($userGroup);
It might be easier to use 2-dimensional array
$users = array();
while(mysqli_stmt_fetch($selectquery))
{
$users[] = array();
$users[][name]=$name;
$users[][studname]=$studname;
$users[][studic] = $studic;
$users[][form]=$form;
$users[][classs]=$classs;
$users[][ddate]=$ddate;
$users[][code]=$code;
$users[][mistakes]=$mistakes;
$users[][punishment]=$punishment;
}
foreach ( $users as $user )
echo json_encode($user);
It looks like you are doing correct query, but when fetching results using one flat array instead two dimension.
Also, try to avoid publishing your DB credentials in public :) It is quite dangerous.
So you should do something like that:
<?php
$host="YOUR_DB_HOST";
$user="YOUR_DB_USER";
$password="YOUR_DB_USER_PASSWORD";
$db="YOUR_DB_NAME";
$con = mysqli_connect($host,$user,$password,$db);
$parentic=$_POST["ParentIC"];
$password=$_POST["Password"];
$selectquery = mysqli_prepare($con, "SELECT Parents_Data.Name, Student_List.StudName, Student_List.StudIC, Student_List.Form,Student_List.Class,discipline_record.Date,discipline_record.RulesCode, discipline_record.TypesofMistakes,discipline_record.Punishment FROM discipline_record LEFT JOIN Student_List ON discipline_record.StudIC = Student_List.StudIC LEFT JOIN Parents_Data ON Student_List.ParentIC = Parents_Data.ParentIC WHERE Parents_Data.ParentIC = ? AND Parents_Data.Password = ? ");
mysqli_stmt_bind_param ($selectquery, "ss", $parentic, $password);
mysqli_stmt_execute($selectquery);
mysqli_stmt_store_result($selectquery);
mysqli_stmt_bind_result($selectquery,$name,$studname,$studic,$form,$classs,$ddate,$code,$mistakes,$punishment);
$user = array();
$users = array();
while(mysqli_stmt_fetch($selectquery))
{
$user[name]=$name;
$user[studname]=$studname;
$user[studic] = $studic;
$user[form]=$form;
$user[classs]=$classs;
$user[ddate]=$ddate;
$user[code]=$code;
$user[mistakes]=$mistakes;
$user[punishment]=$punishment;
$users[] = $user;
}
mysqli_stmt_close($selectquery);
mysqli_close($con);
echo json_encode($users);

fetch database data with singleton design pattern

I'm using singleton design pattern for connect to database.In below I run a query on my database and I want to fetch data from this query :
$db = Db::connect();
$query = $db->query("SELECT * FROM myTable");
while ($row = ???) {
// echo 'myTable' fields here. like = echo $row['someField']
}
my Db class:
class Db
{
private $connection;
private static $instance;
private function __construct()
{
$host = "localhost";
$user = "root";
$pass = "";
$name = "dictionary";
$this->connection = new mysqli($host, $user, $pass, $name);
}
public static function connect()
{
if (self::$instance == null) {
self::$instance = new Db();
}
return self::$instance;
}
public function query($sql)
{
$result = $this->connection->query($sql);
$records = array();
while ($row = $result->fetch_assoc()) {
$records[] = $row;
}
return $records;
}
}
What should I write instead of ??? in my code ?
Replace
while ($row = ???) {
// echo 'myTable' fields here. like = echo $row['someField']
}
with
foreach($query as $row)
echo $row['someField'];
Note : You may want to rename $query to $rows, for example, since this is a more appropriate name.
In each iteration of while loop, use array_shift() function to get the current row from the result set, like this:
while ($row = array_shift($query)) {
echo $row['someField'] . "<br />";
}
Here's the reference:
array_shift()
Your call to your Database class's ->query() method returns an array of result rows. So all you need to do is process that array like any other
$db = Db::connect();
$rows = $db->query("SELECT * FROM myTable");
foreach ($rows as $row ) {
echo $row['someField'];
}

selecting table from other database codeigniter

How can I make this function
public function get_all_summary($year_dummy){
$current_year = $this->session->userdata('curr_year');
$new_db = $this->load->database('budget_db', TRUE);
$q = "select * from budget where sy=$current_year
AND sy_dummy=$year_dummy";
$query = $new_db->query($q);
return $query->result();}
to somewhat like this.
public function get_all_summary($year_dummy){
$current_year = $this->session->userdata('curr_year');
$new_db = $this->load->database('budget_db', TRUE);
$this->db->select('*');
$this->db->from('budget');
$this->db->where("sy",$current_year);
$this->db->where("sy_dummy",$year_dummy);
$query = $this->db->get();
return $query->result();}
The top function is correct but the bottom function is obviously wrong(I don't know how to select table from other db). I'm also connecting to other database and I'm selecting table from the other database(budget_db).
Hope you understand my problem.
I think you just need to use $new_db which is instance of budget_db.
public function get_all_summary($year_dummy){
$current_year = $this->session->userdata('curr_year');
$new_db = $this->load->database('budget_db', TRUE);
$new_db->select('*');
$new_db->from('budget');
$new_db->where("sy",$current_year);
$new_db->where("sy_dummy",$year_dummy);
$query = $new_db->get();
return $query->result();
}
Hope this might be useful for you.
Supposedly, 'budget_db' is the other database you are trying to connect to, make sure it has its own group defined in the database config. Otherwise, you can connect to it using
public function get_all_summary($year_dummy){
$current_year = $this->session->userdata('curr_year');
$config['hostname'] = "hostname";
$config['username'] = "db_user";
$config['password'] = "db_pass";
$config['database'] = "budget_db";
$config['dbdriver'] = "mysql";
$new_db = $this->load->database($config, TRUE);
$new_db->select('*');
$new_db->from('budget');
$new_db->where("sy", $current_year);
$new_db->where("sy_dummy", $year_dummy);
$query = $new_db->get();
return $query->result();
}
By adding the parameter TRUE to the load database method, $new_db becomes the database object of budget_db.

Returning array from simple function is empty

I have the following function:
function getUser($user_id){
$mysqli = dbConnect();
$gu = "select * from users where user_id = '$user_id'";
$ru = $mysqli->query($gu);
$user = $ru->fetch_array();
return $user;
}
Which is called eg:
$user_id = $_SESSION[user_id];
getUser($user_id);
Then I want to simply echo fields i want, e.g. name. But, when I try the following, it returns empty
echo "users name is $user['name']"; // returns: users name is
Is there a better way to do this?
UPDATE Also tried the following but still empty:
function getUser($user_id){
$mysqli = dbConnect();
$gu = "select * from users where user_id = '$user_id'";
$ru = $mysqli->query($gu);
$user = array();
while($row = $ru->fetch_array()) {
$user[] = $row;
}
return $user;
}
your line:
getUser($user_id);
should be:
$user=getUser($user_id);
This way you'll be setting $user to the array the getUser returns, then you can use it.
Remove the single quotes when printing an array, you echo may needed to be like:
echo "users name is $user[name]";

Unable to print a passed array in PHP

I have 3 files:
DB.class.php - which handles all the databases.
Site.class.php - contains a function to return the latest entries in a database.
index.php - trying to print the array passed.
I am trying to pass an array into index.php from Site.class.php which is using a function from DB.class.php to put the mysql results into an associative array.
index.php:
<?php
// index.php
include 'classes/Site.class.php';
$site = new Site();
print_r($site->latestBookmarks());
?>
Site.class.php:
<?php
// Site.class.php
require_once 'DB.class.php';
class Site {
function latestBookmarks() {
$result = mysql_query("SELECT url, title FROM site ORDER BY id DESC");
$db = new DB();
return $db->processRowSet($result);
}
}
?>
DB.class.php:
<?php
// DB.class.php
class DB {
protected $db_name = "project";
protected $db_user = "root";
protected $db_pass = "root";
protected $db_host = "localhost";
// Open up a connection to the database.
public function connect() {
$connection = mysql_connect($this->db_host, $this->db_user, $this->db_pass);
mysql_select_db($this->db_name);
return true;
}
// Takes a MySQL row and returns an associative array where the keys in the array are the column names in the row set.
public function processRowSet($rowSet, $singleRow=false) {
$resultArray = array();
while ($row = mysql_fetch_assoc($rowSet)) {
array_push($resultArray, $row);
}
if ($singleRow === true)
return $resultArray[0];
return $resultArray;
}
// Select rows from the database.
public function select($table, $where) {
$sql = "SELECT * FROM $table WHERE $where";
$result = mysql_query($sql);
if (mysql_num_rows($result) == 1)
return $this->processRowSet($result, true);
return $this->processRowSet($result);
}
// Update a current row in the database.
public function update($data, $table, $where) {
foreach ($data as $column => $value) {
$sql = "UPDATE $table SET $column = $value WHERE $where";
mysql_query($sql) or die(mysql_error());
}
return true;
}
// Insert a new row into the database.
public function insert($data, $table) {
$columns = "";
$values = "";
foreach ($data as $column => $value) {
$columns .= ($columns == "") ? "" : ", ";
$columns .= $column;
$values .= ($values == "") ? "" : ", ";
$values .= $value;
}
$sql = "INSERT INTO $table ($columns) VALUES ($values)";
mysql_query($sql) or die(mysql_error());
return mysql_insert_id();
}
}
?>
A few problems I noticed:
You run a query in function latestBookmarks before you connect to the db;
In your function connect you connect to a database, but the result is discarded immediately, $connection is lost as soon as the function finishes.
You have no connection to the database when you run this line:
$result = mysql_query("SELECT url, title FROM site ORDER BY id DESC");
You will need to adjust your code to send the query string to the DB instance for processing. You can add a method to DB to execute mysql_query, and pass the query in like from Site:: latestBookmarks() like this:
$db = new DB();
$db->executeQuery("SELECT url, title FROM site ORDER BY id DESC");
return $db->processRowSet();

Categories