php function doesn't return a value - php

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.

Related

Data in my DataBase doesn't get updated MySql

The database doesn't get updated for some strange reason, I can get the correct data (I checked it), but the database does not get updated when I click submit. Can you anyone check if there is anything missing?
NB: the "----" are just for security reasons!
<?php
$host = "sql308.-----.com";
$dbUsername = "----_3041----";
$dbPassword = "-----------";
$dbName = "----_3041----_phpmysqli";
$conn = mysqli_connect($host, $dbUsername, $dbPassword, $dbName);
// Check connection
if ($conn-> connect_error) {
die("Connection échouée!".$conn-> connect_error);
}
$rn = $_GET['rn'];
$dt = $_GET['dt'];
$to = $_GET['to'];
$rk = $_GET['rk'];
if(isset($_POST['edit'])) {
$rn = $_POST['rn'];
$dt = $_POST['date'];
$to = $_POST["total"];
$rk = $_POST['remarques'];
$sql = "UPDATE `datab1` SET
`date` = '$dt',
`total` = '$to',
`remarques` = '$rk'
WHERE `datab1`.`id` = '$rn'";
$result = mysqli_query($conn, $sql);
if($result == 1) {
header('location:table.php');
}
else {
die(mysqli_error($conn));
}
}
?>
Most probably the update is executed without finding a match for the where condition.
Just before
if(isset($_POST['edit'])) {
add the following code at line 18
echo "<p>GET: "; var_dump($_GET); echo "<p>POST: "; var_dump($_POST); echo "<p>";
and inspect the values.
Also before
$result = mysqli_query($conn, $sql);
at line 30, please add
echo "<br>$sql<br>"; exit();
And if you could not solve after reviewing both the outputs, please post the same here.
Thank you #Natarajan N Napoleon for the helpful trick, the outputs are correct in both GET and POST as it's shown here:
GET: array(9) { ["rn"]=> string(2) "21" ["dt"]=> string(10) "07-12-2021" ["rk"]=> string(5) "walou" ["to"]=> string(4) "1250" }
POST: array(9) { ["date"]=> string(10) "07-12-2021" ["total"]=> string(4) "1800" ["remarques"]=> string(5) "done" ["edit"]=> string(8) "Modifier" }
the SQL Query is the one making troubles, this is what I get:
UPDATE `datab1` SET `date` = '07-12-2021', `total` = '1800', `remarques` = 'done' WHERE id = ''
I was assigning a null to my "rn" which caused this error, I had to pass the value of "rn" directly to my query without no modification.

Using PHP / MySQLi to loop through json_decoded array not working for Update query

I am using json_decode() to decode an Ajax result which returns the below array (shortened example).
Now I want to loop through this area and to update the rId for each vId as per the values from the array but this part does not work.
Can someone show me how to do the loop part correctly here (the query itself should be ok) ?
My array:
array(3) {
[0]=>
array(2) {
["vId"]=>
string(8) "04567901"
["rId"]=>
string(6) "DE-003"
}
[1]=>
array(2) {
["vId"]=>
string(8) "04567902"
["rId"]=>
string(6) "DE-008"
}
[2]=>
array(2) {
["vId"]=>
string(8) "04567903"
["rId"]=>
string(6) "DE-009"
}
}
My PHP / MySQLi:
$postData = $_POST;
$transferData = $_POST['transferData'];
$json = json_decode($transferData, true);
$conn = new mysqli($host, $username, $password, $database);
if($conn->connect_error) {
die("Connection Error: " . $conn->connect_error);
}
$stmt = $conn->prepare("UPDATE locations l SET l.rId = ? WHERE l.vId = ?");
foreach($json as $vId => $rId) {
$stmt->bind_param('ss', $rId, $vId);
$stmt->execute();
}
$stmt->close();
$conn->close();
In your foreach, the key refers to the index of the array rather than what you consider the key to be. The keys in your case are actually 0, 1, 2, [...].
You return an array of arrays, so get the parts you want as follows:
foreach($json as $key => $value) {
$stmt->bind_param('ss', $value['rId'], $value['vId']);
$stmt->execute();
}

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

Returning an Object In a PHP Class

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'];

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