I'm trying to create a global variable which contains user specific data from my database. I've been looking over the internet but I couldn't find the right answer. I'm not quite sure how to approach this.
At this point of code, the user has been registered and logged in and his login data is saved inside $s_email and $s_password, which are session variables.
Here's some code (mysql.php) which contains the mysql class:
class mysql {
// Create database connection
private $db;
function __construct() {
$this->db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME) or
die('Database fout.');
}
// Receive user data based on cookie, then fetch this data into an array
function getUserData($s_email, $s_password, $data){
$sql = "SELECT
`id`,
`firstname`,
`lastname`,
`city`,
`country`,
`gender`,
`bio`,
`active`,
`member_since`
FROM `users`
WHERE email = '$s_email'
AND password ='$s_password'";
// perform the query and store the result
$result = $this->db->query($sql);
// if the $result contains at least one row
if ($result->num_rows > 0) {
// output data of each row from $result
$data = array();
global $data;
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
}
}
}
And this is my profile.php which will try to run the function (the echo $data[''] does not work, but that's the kind of approach I would like to take on this system):
<?php
// Receive user data and send it to mysql class
$mysql->getUserData($s_email, $s_password, $data);
echo $data['email'];
?>
Eventually I'm trying to create a simple access method to the array variables.
NOTE: I've only been scripting PHP and MySQL for 2 days, so any advice on my code is really appreciated.
Thank you,
Don't use globals.
In your function (don't use $data as an argument):
function getUserData($s_email, $s_password) {
// code
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
return $data;
}
Then to use it (don't pass $data as an argument):
$data = $mysql->getUserData($s_email, $s_password);
Now you have rows so loop over them:
foreach($data as $row) {
echo $row['email'];
}
And you need to select email in the query.
I will first tell you how to do it and right after will explain why you shouldnt be doing that.
How to do it
To let the getUserData method to alter the value of the $data variable you are giving as argument you need to pass it by reference, like this:
function getUserData($s_email, $s_password, &$data) {
Why you should not be doing this in this situation
Keeping things brief. Because there are by far better approaches (like the one AbraCadaver is suggesting) and you dont really need to pass the $data by reference in the first place.
Related
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;
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']);
?>
I'm trying to create a function that runs a query that returns all of the data located in my MySQL database.
My current code only returns the one row of data (there are 7)
function staff_get() {
$this->load->database();
$sql = 'SELECT * from Staff';
$query = $this->db->query($sql);
$data = $query->row();
$this->response($data, 200);
}
I'd imagine it has something to do with the line "$data = $query->row();" however I've tried switching "row" with "array" but this doesn't work. The text is designed to come out as plaintext so that I can manipulate it using a jQuery template.
Thank you for your help in advance.
You need to encase the results in a while loop. Something along the lines of this.
function staff_get() {
$this->load->database();
$sql = 'SELECT * from Staff';
$query = $this->db->query($sql);
while($data = $query->row()) {
$this->response($data, 200);
}
}
I write a lot of SELECT * FROM... kind of queries in my web sites. I'd like to write a function that looks after this for me so I can call on it more quickly, without using more advanced techniques like PDO and OOP. Im just confused on how I would call the data I retrieve from the database, particularly when looping through the array's results.
I'd love something like this:
function selectAll($tableName, $limitAmount) {
global $dbConnection;
$query = mysql_query("SELECT * FROM $tableName ORDER BY id LIMIT $limitAmount");
$row_result = mysql_fetch_assoc($query);
return $row_result;
}
Say it was a bunch of news posts. Id like to loop through the results in one of the typical ways:
// CALL THE FUNCTION
selectAll('news_table', '10');
// SOMEHOW LOOP THROUGH RESULTS??
do {
echo "<h2>".$row_result['title']."</h2>";
} while ($row_result = mysql_fetch_assoc($query));
Obviously this isn't how I loop through the bespoke results of a function. Im not even sure if my function is correct.
Any help is greatly appreciated.
EDIT: Forgot to return a result inside the function and call the actual function. My bad. Updated now.
There is no point in having such a function called like yours.
Just make it like this
function fetchAll($query) {
$res = mysql_query($query) or trigger_error("db: ".mysql_error()." in ".$query);
$a = array();
if ($res) {
while($row = mysql_fetch_assoc($res)) $a[]=$row;
}
return $a;
}
and use it with whatever query:
$data = fetchAll("SELECT * FROM news_table ORDER BY id LIMIT 10");
foreach ($data as $row) {
echo $row['title'];
}
An SQL query being a powerful program itself. Do not reduce it's power to silly selects.
Use SQL to represent data processing logic and this helper function to avoid repetitions.
I have this method in my db class
public function query($queryString)
{
if (!$this->_connected) $this->_connectToDb(); //connect to database
$results = mysql_query($queryString, $this->_dbLink) or trigger_error(mysql_error());
return mysql_num_rows($results) > 0 ? mysql_fetch_assoc($results) : false;
}
This works great for queries that return 1 row, but how can I get an array returned something like this?
$array[0]['name'] = 'jim'
$array[0]['id'] = 120
$array[1]['name'] = 'judith'
$array[1]['ID'] = 121
Now I know I could use a while loop to insert this data into the array like so, but I was wondering if PHP could do this with an internal function? I havn't been able to find on the docs what I'm after.
The reason I don't want to run the while within the method is because I am going to reiterate back over the array when it's returned, and I'd rather not run through the results twice (for performance reasons).
Is there a way to do this? Do I have a problem with my general query method design?
Thank you muchly!
public function query($queryString)
{
if (!$this->_connected) $this->_connectToDb(); //connect to database
$results = mysql_query($queryString, $this->_dbLink) or trigger_error(mysql_error());
$data = array();
while($row = mysql_fetch_assoc($results))
{
$data[] = $row;
}
return $data;
}
this will always return an array.
EDIT:
I didn't read the question well.
If you realy don't want to use the loop then I would do this:
public function query($queryString)
{
if (!$this->_connected) $this->_connectToDb(); //connect to database
return mysql_query($queryString, $this->_dbLink) or trigger_error(mysql_error());
}
then loop over it, however I would just use the loop.
You might also want to look at the PDO extension. You can load the entire result set into an array or you can loop using foreach.
<?php
$db = new PDO($connection_string, $username, $password);
$result = $db->query($queryString);
foreach($result as $row) {
// do something
}
// or
$result = $db->query($queryString);
$result_array = $result->fetchAll(PDO::FETCH_ASSOC);
?>
Most people use a while() loop in the query to do exactly what you want and then loop over the array to process it.
However, you're right: it wastes memory, which could be a problem with a large dataset. An alternative is for your query method to return the resultset resource. Then your while loop can use that to fetch each row as it requires it.
To abstract that away, I would suggest another class to do that for you. Then your query call would return a new instance of that class which has the MySQL resultset resource as an instance variable and packages up the mysql_fetch_assoc() call.
Look at PEAR::MDB2 (Quickstart Cheatsheet). It provides lots of different functions for doing something like this. It also does not tie you down into using MySQL specific functions because it is a database abstraction layer.
$result = $db->queryRow($query, MDB2_FETCHMODE_ASSOC);
There are other abstraction layers such as ADO as well.
thanks for the ideas. I have a function that returns an associative array from the sql (used in Moodle).
$results = get_records_sql($sql);
//to create a numerically indexed array:
$data = array();
foreach ($results as $row)
{
$data[] = $row;
}
return $data;
}