Returning an Object In a PHP Class - php

I want to make a the following thing happen in PHP PDO OOP
$conn = mysqli_connect("localhost", "root", "blogger.g", "test");
$query = mysqli_query($conn, "SELECT * FROM users WHERE username='sandeep'");
$row = mysqli_fetch_assoc($query);
echo $row['password'];
The code which I use in the OOP way is as follows
class getResults{
public $results;
public function start(){
try {
$DTH = new PDO("mysql:host=127.0.0.1;dbname=test", "root", "blogger.g");
$STH = $DTH->query("SELECT * FROM users WHERE username='sandeep'");
$results = $STH->fetchAll(PDO::FETCH_OBJ);
return $results;
} catch (PDOException $e){
return $e->getMessage();
}
}
}
var_dump(getResults::start());
I got the following output
array(1) { [0]=> object(stdClass)#3 (3) { ["id"]=> string(1) "1" ["username"]=> string(7) "sandeep" ["password"]=> string(8) "password" } }
And How Should I access each of the properties ??

You can access each row if you loop through the object with a while()-loop, for example.
while($row = getResults::start()) {
echo $row->id;
}
One last tip: If you're already using PDO, use Prepared Statements. For your safety.

Since your query yields a single row, don't use fetchAll:
$results = $STH->fetch(PDO::FETCH_OBJ);
would suffice. Now, store the returned value inside a variable:
$x = getResults::start();
Since, $x is a class object, you can access its members by -> operator:
echo $x->username . "\n" . $x->password;
Alternatively, you can use PDO::FETCH_ASSOC:
$results = $STH->fetch(PDO::FETCH_ASSOC);
$x = getResults::start();
echo $x['username'] . "\n" . $x['password'];

Related

Selecting data from mysql php

I'm using this to select data from mysql in php
<?php
error_reporting(E_ALL);
$servername = "localhost";
$username = "******";
$password = "******";
$database = "*******";
// Create connection
$conn2 = new mysqli($servername, $username, $password, $database);
$stmt = $conn2->prepare('SELECT id, title, views from `blog_main`');
$stmt->execute();
var_dump($stmt);
$result = $stmt->get_result();
while($r=$result->fetch_assoc())
{
echo "id: " . $r["id"]. " - Name: " . $r["title"]. " " . $r["views"]. "<br>";
}
$conn->close();
?>
However no result is shown, but if I run this query on phpmyadmin interface it returns rows.
This code worked fine on localhost but when I shifted it to godaddy's server, I'm facing this problem only in prepared statement.
When I'm using normal query method it displays rows, only prepared statements are not working.
This is the value of var dump:
object(mysqli_stmt)#2 (10) { ["affected_rows"]=> int(-1) ["insert_id"]=> int(0) ["num_rows"]=> int(0) ["param_count"]=> int(0) ["field_count"]=> int(3) ["errno"]=> int(0) ["error"]=> string(0) "" ["error_list"]=> array(0) { } ["sqlstate"]=> string(5) "00000" ["id"]=> int(1) }
Is there any kind of extension I need to enable or what might be the problem?
here is my answer for your question,
create file db.php
$dbInfo = array(
'host' => "localhost",
'user' => "******",
'pass' => "******",
'dbname' => "******"
);
create dbcon.php
class database{
protected $databaseLink;
function __construct(){
include "db.php";
$this->database = $dbInfo['host'];
$this->mysql_user = $dbInfo['user'];
$this->mysql_pass = $dbInfo['pass'];
$this->databaseName = $dbInfo['dbname'];
$this->openConnection();
return $this->get_link();
}
function openConnection(){
$this->databaseLink = mysqli_connect($this->database, $this->mysql_user, $this->mysql_pass, $this->databaseName);
}
function get_link(){
return $this->databaseLink;
}
}
create func.php
include "dbcon.php";
function selectData(){
$db = new database();
$selectQuery = "SELECT id, title, views FROM blog_main";
$selectQuery = mysqli_query($db->get_link(), $selectQuery) or die(mysqli_error());
while($r = mysqli_fetch_assoc($selectQuery)) {
$rows[] = $r;
}
return $result = json_encode(($rows));
mysqli_close($db->get_link());
}
and in for example index.php you can get data from which SQL return
include "func.php";
$data = selectData();
$dataJson = json_decode($data, TRUE);
foreach ($dataJson as $key => $value) {
echo "id: " . $value['id']. " - Name: " . $value['title']. " " . $value['views']. "<br>";
}
good luck
Seems like it was the disable driver issue. I enabled the stmt_mysqli driver and it worked.

Type definition string doesn't match number of bind

I have an error in php and I have no idea how to fix this. By the way this is my school lesson example so I don't really know what's happening there. This is supporsed to be master/detail navigation.
<?php
$mysqli = new mysqli("localhost", "root", "", "base");
$stmt = $mysqli->prepare('SELECT * FROM aeromiting WHERE id = ":id"');
echo $mysqli->error;
$stmt->bind_param(':id', $_GET['id']);
var_dump($stmt);
$data = $stmt->execute();
?>
Warning: mysqli_stmt::bind_param(): Number of elements in type
definition string doesn't match number of bind variables in
C:\xampp\htdocs\test1\detail.php on line 20 object(mysqli_stmt)#2 (10)
{ ["affected_rows"]=> int(0) ["insert_id"]=> int(0) ["num_rows"]=>
int(0) ["param_count"]=> int(0) ["field_count"]=> int(4) ["errno"]=>
int(0) ["error"]=> string(0) "" ["error_list"]=> array(0) { }
["sqlstate"]=> string(5) "00000" ["id"]=> int(1) }
If you want to do it in PDO, try this...
<?php
$host = 'localhost'; $db = 'base'; $user = 'root'; $pw = '';
$conn = new PDO('mysql:host='.$host.';dbname='.$db.';charset=utf8', $user, $pw);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$id = $_GET['id'];
$sql = "SELECT * FROM aeromiting WHERE id=:id";
$query = $conn->prepare($sql);
$query->bindValue(':id', $id, PDO::PARAM_INT);
$query->execute();
$row = $query->fetch(PDO::FETCH_ASSOC);
$totalRows = $query->rowCount();
} catch (PDOException $e) {
die("Could not get the data: " . $e->getMessage());
}
?>
Have a look at pdo_mysql for more information.
You're mixing APIs here. MySQLi can't accept strings or the likes as parameters.
$stmt = $mysqli->prepare('SELECT * FROM aeromiting WHERE id = ":id"');
$stmt->bind_param(':id', $_GET['id']);
Should be
$stmt = $mysqli->prepare('SELECT * FROM aeromiting WHERE id = ?');
$stmt->bind_param('i', $_GET['id']);
This is of course assumed that $_GET['id'] is an integer (hence the 'i' in the bind_param. If it's a string, replace the i with s.
You should probably get a bind_result as well, so you actually bind the results from the database to some variables. Take a look at the MySQLi documentation.

PDO Statement returning false

I am running 2 queries, the first one goes through correctly and returns the desired value, but the second one returns false.
I have set $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); so I should be getting an exception over false, so I am guessing that my $stmt->execute(); is the culprit here.
As that's the only function that can return false now that I've set the error attribute.
I have also tried setting $stmt->closeCursor();, $stmt = null;, and unset($stmt); with no avail.
This executes two queries (both "darkrp" and "pointshop" in the fetch_wallet() function.
if($this->pdo) {
foreach($this->methods as $method => $bool) {
if($bool) { $array[$method] = $this->fetch_wallet($method); }
}
}
This is the fetch_wallet() function:
public function fetch_wallet($type) {
if($type == "darkrp") {
$query = "SELECT `wallet` FROM `darkrp_player` WHERE uid=:uid LIMIT 1";
}
elseif ($type == "pointshop") {
$query = "SELECT `points` FROM `pointshop_data` WHERE uniqueid=:uid LIMIT 1";
}
try {
$stmt = $this->pdo->prepare($query);
$stmt->execute(array(":uid" => $this->uniqueid));
$result = $stmt->fetchColumn();
return $result;
}
catch (PDOException $e) {
return $e->getMessage();
}
}
When I run var_dump($stmt->errorInfo()); I get this, which means that both queries runs fine, although the last one returns false when it should return 440. No exception is thrown.
array(3) {
[0]=> string(5) "00000"
[1]=> NULL
[2]=> NULL
}
array(3) {
[0]=> string(5) "00000"
[1]=> NULL
[2]=> NULL
}
Printed screen of the pointshop_data table in phpMyAdmin (I want the 440 value there):
Value returned from var_dump($this->uniqueid); is 3266928646
I have debugged everything, and I get no errors whatsoever, just a false.
PHP Version: 5.3.10
MySQL Version: 5.5.38
OS: Ubuntu 12.04 LTS
I think there must be some other error in your class that makes this code does not work.
I've imported your tables structure and created the following testing code:
<?php
class A
{
private $pdo;
private $uniqueid;
private $methods = ['darkrp' => true, 'pointshop' => true];
public function __construct($pdo, $uniqueid)
{
$this->pdo = $pdo;
$this->uniqueid = $uniqueid;
}
public function fetch_wallet($type)
{
if ($type == "darkrp") {
$query = "SELECT `wallet` FROM `darkrp_player` WHERE uid=:uid LIMIT 1";
} elseif ($type == "pointshop") {
$query = "SELECT `points` FROM `pointshop_data` WHERE uniqueid=:uid LIMIT 1";
}
try {
$stmt = $this->pdo->prepare($query);
$stmt->execute(array(":uid" => $this->uniqueid));
$result = $stmt->fetchColumn();
return $result;
} catch (PDOException $e) {
return $e->getMessage();
}
}
public function run()
{
if ($this->pdo) {
foreach ($this->methods as $method => $bool) {
if ($bool) {
$array[$method] = $this->fetch_wallet($method);
var_dump($array[$method]);
}
}
}
}
}
$pdo = new PDO('mysql:host=localhost;dbname=tests', 'root', '');
$a = new A($pdo, 3266928646);
$a->run();
The result I get for this is:
string(4) "2075" string(3) "440"
So it is working as it should.
Please try this code (that's the whole file - of course you need to change your db name, user and password) and check if it gets you the same results. If yes, probably you have other errors in your class.
Change
$stmt->execute(array(":uid" => $this->uniqueid));
to
$stmt->bindValue(':uid', $this->uniqueid);
$stmt->execute();

php function doesn't return a value

I have a class which works fine with php 5.3 (XAMPP 1.7.3, windows 7) but doesn't work in my server(php 5.2.17 - Safe mode On):
<?php
class MYSQL_DB {
var $connection;
function MYSQL_DB() {
$this->connection = mysql_connect(S, U, P) or die('Can\'t connect to MySQL server.');
mysql_select_db(DB, $this->connection) or die(mysql_error());
}
function getJobs($wid) {
$q = "SELECT * FROM " . TB_PREFIX . "joblist where owner = {$wid} order by ID ASC";
$result = mysql_query($q, $this->connection);
$ret = $this->mysql_fetch_all($result);
mysql_free_result($result);
return $ret;
}
function mysql_fetch_all($result) {
$all = array();
if ($result) {
while ($row = mysql_fetch_assoc($result)) {
$all[] = $row;
}
return $all;
}
}
}
$db=new MYSQL_DB();
?>
And in another file, I used getjobs function:
<?php
$tempbJobs=$db->getJobs(1368);
var_dump($tempbJobs);
?>
when I use var_dump right before return $ret; in getjobs function, it shows me correct values, but var_dump($tempbJobs); will print NULL.
P.S: I simplified the code, it works on my localhost but not on production server.
P.S: If I change return $ret; to return 'DUMPED'; , returned value would be string(6) "DUMPED"
var_dump($ret ); output:
array(2) {
[0]=>
array(5) {
["id"]=>
string(5) "10755"
["owner"]=>
string(5) "23626"
["field"]=>
string(1) "6"
["type"]=>
string(1) "2"
["expi"]=>
string(10) "1372144648"
}
[1]=>
array(5) {
["id"]=>
string(5) "10756"
["owner"]=>
string(5) "23626"
["field"]=>
string(1) "5"
["type"]=>
string(1) "2"
["expi"]=>
string(10) "1372144654"
}
}
Based on the fact that you only return $all from the function mysql_fetch_all($result) if $result is true I have to assume that the mysql_query() is returning false.
After the call to
$result = mysql_query($q, $this->connection);
Can you add this
$result = mysql_query($q, $this->connection);
if ( ! $result ) {
echo "ErrorNo: " . mysql_errno() . " Error Message: " . mysql_error();
}
This might help identify what the problem actually is as it has to be a database error of some sort.
Could you check that your constants S, U, P, TB_PREFIX are defined() and they have values.
Also modify your function mysql_fetch_all to return response anyway:
function mysql_fetch_all($result) {
$all = array();
if ($result) {
while ($row = mysql_fetch_assoc($result)) {
$all[] = $row;
}
}
return $all;
}
I reviewed all your comments.
In one of your comments you said that return is not working but I think it is working properly because you already said in one of your comments that when you print out the result before return $ret it gives you the correct result.
fact : mysql_fetch_all($result) also returning result.
checkout the sql code : $q = "SELECT * FROM " . TB_PREFIX . "joblist where owner = {$wid} order by ID ASC"; I do not know {$wid} what it is.
Test it
$q = "SELECT * FROM " . TB_PREFIX . "joblist where owner = '$wid' order by ID ASC";
try after defining array for $ret in the function getjobs()
$ret=array(); //try
I know this is a little bit rusty question but yet still interesting. Are you able to found solution on that ?
If same code doesn't work on different server i would have suspected in that case memory limit. Try to increase php memory limit.
And it could be wise to check phpinfo(); on both servers to compare differences.

Use array in mysql insert query

I got a Bash/PHP script that retrieves records from a table called 'assess_2012' and stores records that need to be written to a table called 'assess_2012_err' in a multidimensional array:
#!/usr/bin/php -q
<?php
$host = "localhost";
$user = "username";
$pass = "password";
$name = "reassess";
$conn = mysqli_connect($host, $user, $pass, $name) OR die ("Could not connect to database: " . mysqli_error($conn) . "\n");
$q = "SELECT su_id, ass_date, ind_d FROM assess_2012";
$r = mysqli_query ($conn, $q);
if ($r) {
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
// Check for errors:
if ($row['ind_d'] == 'Y') {
// Add to the array:
$sql[] = array('su_id' => $row['su_id'], 'err_code' => 1);
}
}
var_dump($sql);
}
else {
// SELECT query failed:
echo "Error: " . mysqli_error($conn) . "\n";
}
?>
The 'var_dump' looks like this (shortened version - the actual query returns hundreds of records):
array(1) {
[0]=>
array(2)
["su_id"]=>
string(1) "5"
["err_code"]=>
int(1)
}
[1]=>
array(2) {
["su_id"]=>
string(4) "1492"
["err_code"]=>
int(1)
}
}
What I can't figure out is how I can use the array to produce a query like this:
INSERT INTO assess_2012_err (su_id, err_code) VALUES (5, 1), (1492, 1)
Use a foreach loop to loop through data as you enter the values into the database.
Like:
foreach($sql as $key=>$value){
foreach($value as $key_p=>$value_p){
//Implement Query here
//R.g
//$key will have 'su_id'
//$value_p will have 1
}
}
You'll be better off doing one by one, like so
foreach($sql as $variables)
{
// Insert here:
INSERT INTO asses_2012_err (su_id, err_code) VALUES ($variables['su_id'], $variables['err_code']);
}
Some important things to bear in mind:
Treat those inputs as user inputs, sanitise them!
Try to use PDO as mysql_* functions are going to be deprecated
Consider a data abstraction layer (so all your queries are hidden away inside nice functions)

Categories