Putting data from database into variable using PHP (PDO, MVC) - php

Today I have looked all over the internet for a good answer. I almost got the answer from this site but that solution didn't work.
Here is what I need to do:
In the database there is a token stored that is going to be used for qr codes. I have already made something to generate the qr code when hardcoded:
$token_qr = "a86ad6352e939eea67da45b8731c3a8d62dcas1r";
$url_qr = some url;
$qr_code = array(
"token" => $token_qr,
"url" => $url_qr
); // end array
$qr_code_encoded = json_encode($qr_code, JSON_UNESCAPED_SLASHES);
$smarty->assign('qr_code_encoded', base64_encode($qr_code_encoded));
The base64 string is put in a url so the qr image can be generated.
Now I need to make it dynamically, the url is always the same but the token is always different. In the model where all the database statements are present I made this:
Class Webservices {
public function GetToken($token) {
$pdo = Database::Get();
$query = "SELECT `site__webservice`.* FROM `site__webservice` WHERE `token` = :token"; // SQL select statement
$params = array(":token" => $token); // bind params
$result = $pdo->Select($query, $params); // run query
// fetch token
if($result) {
$row = PDO::FETCH_ASSOC($result);
return $row[$token];
} else {
return false;
}
}
}
With this function I try to get the token from the database and store this in the $token_qr variable which stand in the controller. To call this I use this:
$webservices = new Webservices();
$token_qr = $webservices->GetToken($token);
The output of this function is now always false. Is there something wrong with my statement or is it in the loop that I created?
Maybe it is something really easy but I can't see the problem and find a solution for it. Thanks in advance for the response!

You need fetch the result before return, use fetch() or fetchAll(). Seems Select() works likes pdo execute() so it's return PDOStatment, fetch it to get the results.
if($result) {
$row = $result->fetchAll(PDO::FETCH_ASSOC);
return $row;

Related

What kind of object can I send to this view in order to get this PHP code to work?

I am terrible at PHP and I need to retrieve data from a database and give it to an index.php view. The view is pre-made and has this code:
//This is simplified - it has error handling that is not shown
$results = getAll($tableName);
//This is the line where it is failing
//Undefined Offset
$columns = empty($results) ? array() : array_keys($results[0]);
$idColumn = $columns[0];
There is all the rest of it but I just need to know what on earth it is that this bit of code is expecting. I have not even got the first clue what is supposed to be sent to this thing. I just need to get it to work.
This is what I have tried so far:
function getAll($tablename)
{
$mysqlConnection = getDbConnection();//Just the normal PDO db connection
$sql = "SELECT * FROM ".$tablename;
$sth = $mysqlConnection->prepare($sql);
$sth->execute();
$resultSet = $sth->fetch(PDO::FETCH_ASSOC);
return $resultSet;
}
I have tried various different PDO::FETCH_... types but nothing is working. There is no information about what it is that I am supposed to send that part of the view.
If you want all the rows from fetch(), you will need to loop through the result set because it will return a single row. In the loop you can place them in an array.
You can use fetchAll() instead. It will return all the results as an array.

phpunit testing ???? how shall i compare to xml files before and after api function call(the function contains the stored procedure)

after searching for a long time got this great article its really very nice
but i am facing a bit problem here in my stuff as u have used direct mysql query in api i have used stored procedure in here and every time i have to compare two XML before and after even for a single short and sweet query so is there any alternative for this process but which is this secure
please chk this out u will get i more clearly
database testing in php using phpunit,simpletest on api haveing stored procedure
or how shall i compare to xml files before and after api function call(the function contains the stored procedure)
means i am able to get the before state with mysql-dump but the after but not getting the instant after xml state
sorry for the English but tried my best
thanks for the help friend
have to write an unit test test for the api function
public function delete($userId)
{
// this function calls a stored procedure
$sql = "CALL Delete_User_Details(:userId)";
try {
$db = parent::getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("userId", $userId);
$stmt->execute();
$id = $stmt->fetchObject();
if ($id == null) {
$delete_response->createJSONArray("DATABASE_ERROR",0);
} else {
$delete_response->createJSONArray("SUCCESS",1);
}
} catch (PDOException $e) {
$delete_response->createJSONArray("DATABASE_ERROR",0);
}
return $delete_response->toJSON();
}
i have writen this unit test for it now want to write an dbunit for it
public function testDeleteUser()
{
$decodedResponse = $response->json();
$this->assertEquals($response->getStatusCode(), 200);
$this->assertEquals($decodedResponse['status']['StatusMSG'], 'SUCCESS');
$this->assertEquals($decodedResponse['status']['Code'], '1');
}
help guyss
u can just simply test it before by calling the query like
$sql = "select * from user";
and compare it with BeforeDeleteUser.xml
And the Call Ur stored procedure
$sql = "CALL Delete_User_Details(:userId)";
And for the after case just repeat the before one again
$sql = "select * from user";
and compare it with AfterDeleteUser.xml
see the logic is very simple if u have 5 Users in BeforeDeleteUser.xml and it results true and after the call of CALL Delete_User_Details(:userId) stored procedure , the AfterDeleteUser.xml should contain only 4 user (or maybe idDelete field to 0 that depends on ur implementation)

This result is a forward only result set, calling rewind() after moving forward is not supported - Zend

In Zend app, I use Zend\Db\TableGateway and Zend\Db\Sql to retrieve data data from MySQL database as below.
Model -
public function getCandidateEduQualifications($id)
{
$id = (int) $id;
$rowset = $this->tableGateway->select(function (Sql\Select $select) use ($id)
{
$select->where
->AND->NEST->equalTo('candidate_id', $id)
->AND->equalTo('qualification_category', 'Educational');
});
return $rowset;
}
View -
I just iterate $rowset and echo in view. But it gives error when try to echo two or more times. Single iteration works.
This result is a forward only result set, calling rewind() after
moving forward is not supported
I can solve it by loading it to another array in view. But is it the best way ? Is there any other way to handle this ?
$records = array();
foreach ($edu_qualifications as $result) {
$records[] = $result;
}
EDIT -
$resultSet->buffer(); solved the problem.
You receive this Exception because this is expected behavior. Zend uses PDO to obtain its Zend\Db\ResultSet\Resultset which is returned by Zend\Db\TableGateway\TableGateway. PDO result sets use a forward-only cursor by default, meaning you can only loop through the set once.
For more information about cursors check Wikipedia and this article.
As the Zend\Db\ResultSet\Resultset implements the PHP Iterator you can extract an array of the set using the Zend\Db\ResultSet\Resultset:toArray() method or using the iterator_to_array() function. Do be careful though about using this function on potentially large datasets! One of the best things about cursors is precisely that they avoid bringing in everything in one go, in case the data set is too large, so there are times when you won't want to put it all into an array at once.
Sure, It looks like when we use Mysql and want to iterate $resultSet, this error will happen, b/c Mysqli only does
forward-moving result sets (Refer to this post: ZF2 DB Result position forwarded?)
I came across this problem too. But when add following line, it solved:
$resultSet->buffer();
but in this mentioned post, it suggest use following line. I just wonder why, and what's difference of them:
$resultSet->getDataSource()->buffer();
This worked for me.
public function fetchAll()
{
$select = $this->tableGateway->getSql()->select();
$resultSet = $this->tableGateway->selectWith($select);
$resultSet->buffer();
$resultSet->next();
return $resultSet;
}
$sql = new Zend\Db\Sql($your_adapter);
$select = $sql->select('your_table_name');
$statement = $sql->prepareStatementForSqlObject($select);
$results = $statement->execute();
$resultSet = new ResultSet();
$resultSet->initialize($results);
$result = $resultSet->toArray();

php function save result at array

hello i want to create function with returning data, for example when i have the function advert i want to make it every time show what i need, i have the table id, sub_id, name, date, and i want to create the function that i can print every time what i need advert(id), advert(name), i want to make it to show every time what i need exactly and i want to save all my result in array, and every time grab the exactly row that i want
<?php
function advert($data){
$id = $_GET['id'];
$query = mysql_query("SELECT *FROM advertisement WHERE id = $id");
while($row = mysql_fetch_assoc($query)){
$data = array(
'id' => $row['id']
);
}
return $data;
}
echo advert($data['id']);
?>
but my result every time is empty, can you help me please?
There are so many flaws in this short piece of code that the only good advice would be to get some beginners tutorial. But i'll put some effort into explaining a few things. Hopefully it will help.
First step would be the line function advert($data), you are passing a parameter $data to the method. Now later on you are using the same variable $data in the return field. I guess that you attempted to let the function know what variable you wanted to fill, but that is not needed.
If I understand correctly what you are trying to do, I would pass in the $id parameter. Then you can use this function to get the array based on the ID you supplied and it doesnt always have to come from the querystring (although it could).
function advert($id) {
}
Now we have the basics setup, we want to get the information from the database. Your code would work, but it is also vulnerable for SQL injection. Since thats a topic on its own, I suggest you use google to find information on the subject. For now I'll just say that you need to verify user input. In this case you want an ID, which I assume is numeric, so make sure its numeric. I'll also asume you have an integer ID, so that would make.
function advert($id) {
if (!is_int($id))
return "possible SQL injection.";
}
Then I'll make another assumption, and that is that the ID is unique and that you only expect 1 result to be returned. Because there is only one result, we can use the LIMIT option in the query and dont need the while loop.
Also keep in mind that mysql_ functions are deprecated and should no longer be used. Try to switch to mysqli or PDO. But for now, i'll just use your code.
Adding just the ID to the $data array seems useless, but I guess you understand how to add the other columns from the SQL table.
function advert($id) {
if (!is_int($id))
return "possible SQL injection.";
$query = mysql_query("SELECT * FROM advertisement WHERE id = $id LIMIT 1");
$row = mysql_fetch_assoc($query);
$data = array(
'id' => $row['id']
);
return $data;
}
Not to call this method we can use the GET parameter like so. Please be advised that echoing an array will most likely not give you the desired result. I would store the result in a variable and then continue using it.
$ad = advert($_GET['id']);
if (!is_array($ad)) {
echo $ad; //for sql injection message
} else {
print_r($ad) //to show array content
}
Do you want to show the specific column value in the return result , like if you pass as as Id , you want to return only Id column data.
Loop through all the key of the row array and on matching with the incoming Column name you can get the value and break the loop.
Check this link : php & mysql - loop through columns of a single row and passing values into array
You are already passing ID as function argument. Also put space between * and FROM.
So use it as below.
$query = mysql_query("SELECT * FROM advertisement WHERE id = '".$data."'");
OR
function advert($id)
{
$query = mysql_query("SELECT * FROM advertisement WHERE id = '".$id."'");
$data = array();
while($row = mysql_fetch_assoc($query))
{
$data[] = $row;
}
return $data;
}
Do not use mysql_* as that is deprecated instead use PDO or MYSQLI_*
try this:
<?php
function advert($id){
$data= array();
//$id = $_GET['id'];
$query = mysql_query("SELECT *FROM advertisement WHERE id = $id");
while($row = mysql_fetch_assoc($query)){
array_push($data,$row['id']);
}
return $data;
}
var_dump($data);
//echo advert($data['id']);
?>

Get JSON data FROM a PHP/MySQL query into a html tag using jquery

Hi guys I´m new at stackoverflow and also new at Jquery
Well hope I can make myself understandable. Here is what I want: I have made a query to my MySQL db, using a class with PHP
public function User($id) {
$this->connect_db_web($conn);
$sql = mysql_query("SELECT * FROM users WHERE id='".$id."'");
while ($values = mysql_fetch_array($sql)) {
$arr[]=array(
'id'=>$values['idUsers'],
'name'=>$values['name'],
'name2'=>$values['name2'],
'lname'=>$values['lname'],
'lname2'=>$values['lname2'],
'email'=>$values['email'],
'phone'=>$values['phone'],
'address'=>$values['address'],
'bday'=>$values['bday'],
'password'=>$values['password']
);
}
echo '{"user":'.json_encode($arr).'}';
}
Then I have a php code where I call this function
$name = $user->User($id);
I think this works ok (if I´m wrong please help). Now what I´m really trying to do is getting the values from the JSON array into specific divs, example:
$.getJSON("user.php",function(data){
$.each(data.user, function(i,user){
name = user.name;
$(name).appendTo('#getname');
});
});
And inside my HML i Have a <p id="getname"></p>wich is the tag I want the value to be displayed
But no value is displayed, why?, what am I doing wrong?
Thanks for the help I apreciate it
Your JSON is malformed. You are appending a bunch of objects {.1.}{.2.}{.3.}. Instead, try {"users":[{.1.},{.2.},{.3.}]}.
In PHP you'll do something like this (note that I've changed the response type to JSON-P rather than JSON by adding a callback parameter):
public function User($id) {
$users = array();
$this->connect_db_web($conn);
$sql = mysql_query("SELECT * FROM users WHERE id='".$id."'");
while ($values = mysql_fetch_array($sql)) {
$users[] = array(
'id'=>$values['idUsers'],
'name'=>$values['name']
// etc.
);
}
$obj['users'] = $users;
$callback = (empty($_GET["callback"])) ? 'callback' : $_GET["callback"];
echo $callback . '(' . json_encode($obj) . ');';
}
Then you'll be able to do:
$.getJSON("user.php?callback=",function(data){
$.each(data.users, function(i,user){
$('#getname').append(user.name);
});
});
probably safer to do like this:
echo json_encode(array("user" => $arr));
on the other end you would receive an object which, I would suggest iterating like this:
var k;
for (k in data.user){
$("#getname").append($("<span></span>").html(data.user[k].name));
}
Given that you are fetching information for one user only, following I would suggest
$id = (int) $_GET["id"]; // or wherever you get it from.
if ($r = $db->mysql_fetch_assoc()){
$response = array(
"name" => $r["name"];
);
echo json_encode($response);
} else {
echo json_encode(array("error" => "Could not get name for user " . $id));
}
Then, on front-end, all you need to do is:
if (typeof(data.name) != "undefined"){
$("#getname").html(data.name);
} else if (typeof(data.error) != "undefined"){
$("#getname").html(data.error); //or handle otherwise
}
You've misinterpreted your JSON structure. You're appending your DB rows to an array, and embedding that inside an object. If you'd do a console.log(user) inside your .getJSON call, you'd see you'll have to do:
user[0].name
instead. As well, your code assumes that the user ID exists, and returns data regardless of how many, or how few, rows there actually are in the result set. At minimum your JS code code should check users.length to see if there ARE are any rows to begin with. Beyond that, unless you're doing it in another section of code somewhere, that $id value is probably coming from the web page, which means your query is vulnerable to SQL injection attacks.
OK got it,
was a php code error and JSON structre as marc said, here I´m gonna post what finally I had
PHP Class
public function User() {
$users = array();
$this->connect($conn);
$sql = mysql_query("SELECT * FROM users WHERE id='1'");
$values = mysql_fetch_array($sql);
$users[] = array(
'id'=>$values['id'],
'name'=>$values['name'],
'name2'=>$values['name2'],
'lname'=>$values['lname'],
...//rest of values
);
echo json_encode($users);
}
PHP module to get class
include"class.php";
$user = new Users();
$user->User();
Now how did I got the values using JQuery
$.getJSON('user.php', function(data){
$('wherever_you_want_to_point_at').text(data[0].name);
});
Hope it helps someone,
Thanks again guys, very very helpful
Take care you all

Categories