php function save result at array - php

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

Related

PHP function issues with array

I have a postgres table with four columns labelled dstart which is date data type,
dend which is also a date data type, dcontract which is a date data type and id which is a integer. I am trying to run a php code to get the data using an array and use it in the body of my application. But when I test the array and try to echo some values... My browser just displays the word array... Is there anyway I can be able to retrieve the data or fix this code? Please see code below
<?php
function getLiveDate($campid)
{
global $conn,$agencies;
$return=array(
'livedate'=>'',
'campid'=>'',
'enddate'=>'',
'dateContract'=>'',
);
$sql = "SELECT id, dcontract, dstart, dend
FROM campaigns
WHERE id = '".$campid."' ORDER BY dstart DESC LIMIT 1";
$r = pg_query($conn,$sql);
if ($r)
{
$d = pg_fetch_array($r);
if (!empty($d))
{
$return['livedate'] = $d['dstart'];
$return['campid'] = $d['id'];
$return['enddate'] = $d['dend'];
$return['dateContract'] = $d['dcontract'];
}
}
#pg_free_result($r);
return $return;
}
I am pretty sure, your array $d is "multi-dimensional" and pg_fetch_array() returns an array of arrays, because the result of SQL queries in general may contain multiple rows. You limited it to one row, but you certainly get the correct values by assinging $return['livedata'] = $d[0]['dstart']; or $return['livedata'] = $d['dstart'][0]; and so on (I am not familiar with that particularly function for I usually use MySQL instead of Postgre).
Besides, try echoing your data by means of print_r() instead of echo.
The $return variable is an array, if you want shows the content, you must use print_r or var_dump not echo.

Information regarding SQL queries, stored with php

So let me explain my problem, lets assume that I run query like so:
$myquery = sql_query("SELECT name FROM table WHERE name='example' LIMIT 0,1");
Now.. I want to store the retrieved name into a variable so I would do something like this:
while ($myrow = sql_fetch_assoc($myquery)) {
transfer_row($myrow);
print"Name: $row_name";
}
$stored_name = $row_name;
NOTE: transfer_row() is just a function I wrote that takes $myrow['name'] and stores it in $row_name, for easier reference
Now, all is fine at this stage, here is where it gets interesting. Note that at this stage I still have a name assigned to $row_name. Further down the page I run another query to retrieve some other information from the table, and one of the things I need to retrieve is a list of names again, so I would simply run this query:
$myquery = sql_query("SELECT name, year FROM table WHERE DESC LIMIT 0,10");
while ($myrow = sql_fetch_assoc($myquery)) {
transfer_row($myrow);
$year = $row_year;
$link = "/$year";
print "<li style=\"margin-bottom: 6px;\">$row_name\n";
}
Now, I want to write an if statement that executes something if the $row_name from this query matches the $row_name from the old query, this is why we stored the first $row_name inside the variable.
if ($row_name == $stored_name){
// execute code
}
However as most of you know, this WONT work, the reason is, it simply takes $stored_name again and puts the new $row_name into $stored_name, so therefore the value of the first $row_name is lost, now it is crucial for my application that I access the first $row_name and compare it AFTER the second query has been run, what can I do here people? if nothing can be done what is an alternative to achieving something like this.
Thanks.
EDIT, MY transfer_row() function:
function transfer_row($myrow) {
global $GLOBALS;
if(is_array($myrow)) {
foreach ($myrow as $key=>$value) {
$key=str_replace(":","",$key);
$GLOBALS["row_$key"] = $value;
}
}
}
Without you posting the code for the function transfer_row, we won't be able to give you an answer that exactly matches what you request, but I can give you an answer that will solve the problem at hand.
When matching to check if the names are the same, you can modify the if statement to the following.
if ($row_name == $myrow['name']){
// execute code
}
What I suggest you do though, but since I don't have the code to the transfer_row function, is to pass a second variable to that function. The second variable will be a prefix for the variable name, so you can have unique values stored and saved.
Refrain from using the transfor_row function in the second call so your comparison becomes:
if ($myrow['name'] == $row_name)
If you need to use this function, you could do an assignment before the second database call:
$stored_name = $row_name;
...
transfer_row($myrow);
In your first query you are selecting the name field WHERE name='example' , Why are you quering then? You already have what you want.
Your are querying like:
Hey? roll no 21 what is your roll no?
So perform the second query only and use the if condition as :
if ($row_name == 'example'){
// execute code
}
Does it make sense?
Update
//How about using prefix while storing the values in `$GLOBAL` ??
transfer_row($myrow, 'old_'); //for the first query
transfer_row($myrow, 'new_'); //for the second query
function transfer_row($myrow, $prefix) {
global $GLOBALS;
if(is_array($myrow)) {
foreach ($myrow as $key=>$value) {
$key=str_replace(":","",$key);
$GLOBALS["$prefix"."row_$key"] = $value;
}
}
}
//Now compare as
if ($new_row_name == $old_row_name){
// execute code
}
//You'll not need `$stored_name = $row_name;` any more

Obtain resource from POST php

Lets say I have a database full of info, and I want the user to find his info by inputting his ID. I collect the input of the user with:
'$_POST[PID]'
And want to put it into a resource variable like:
resource $result = '$_POST[PID]';
In order to print out their information like :
while($row = mysql_fetch_array($result))
{
echo all their information
echo "<br>";
}
However I cannot create the resource variable because it is telling me that it is a boolean. How can I fetch that resource in order to print the list?
Several problems with this
First, a resource is something like a database result set, a connection (like fsockopen), etc. You can't just declare or typecast a variable into a result set
Second, you need to do something like SQL to fetch the data based on that ID. That involves connecting to the DB, running your query and then doing your fetch_array
Third, mysql_ functions are depreciated. Consider using mysqli instead.
I think you're having problems displaying the result set.
Try this
$id = $_POST['PID'];
$result = "SELECT * FROM table WHERE id ='.$id.'";
while($row = mysqli_query($result))
{
echo $row[0]; //or whichever column you want to display.
//$row[0] will display your
// PK
}

How do i parse the the value from a string in the function call?

i have function which is something like this
function multiple_delete($entity1,$entity2,$entity2) {
$query = "SELECT * FROM tablename WHERE id = '4' ";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
echo $entity1;
echo $entity2;
echo $entity3;
}
and my function call is
multiple_delete('$row[\'pic_title\']', '$row[\'pic_brief\']', '$row[\'pic_detail\']');
keeping in mind the three value which i am passing through the parameter is the entity name of particular table.
now this function will print it as the string i.e ($row['pic_title'], $row['pic_brief']', $row['pic_detail']) and hence not parse it as the value which i want it to do. if it parse it as the value then i will be able to get the records from the database. i have tried with the combination of single quotes, doubles, with concatenation operator etc. is there any way i tell the script that do not parse it as the string instead treat it as it have been declared to fetch the value from database. does php have any function for this ? or i am going wrong with the logic.
if i skip the parameters and declare in the functions something like this.
echo $row['pic_title'];
echo $row['pic_brief'];
echo $row['pic_detail'];
it works perfectly fine . why is that when i try to achieve the same thing with the help of parameter it refuses to fetch the value from the database, and instead it returns the same declared string from the function call.
Please do not tell me that i dont need that parameter, i need it because i want it to perform the dynamic data manipulation, with regard to different tables and different table entities. and the above function is just the demonstration of my problem not the exact function. if you want to have a look at the exact function you can check here.
What is wrong with my function?
thank you
Just pass the names of the columns:
multiple_delete('pic_title', 'pic_brief', 'pic_detail');
Then you can use them to access the corresponding values in the row array by using the names them as keys:
function multiple_delete($entity1, $entity2, $entity3) {
$query = "SELECT * FROM tablename WHERE id = '4' ";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
echo $row[$entity1];
echo $row[$entity2];
echo $row[$entity3];
}

PHP get result string from PostgreSQL Query

I'm new to PHP and SQL, but I need a way to store the result of an SQL Query into a variable.
The query is like this:
$q = "SELECT type FROM users WHERE username='foo user'";
$result = pg_query($q);
The query will only return one string; the user's account type, and I just need to store that in a variable so I can check to see if the user has permission to view a page.
I know I could probably just do this query:
"SELECT * FROM users WHERE username='foo user' and type='admin'";
if(pg_num_rows($result) == 1) {
//...
}
But it seems like a bad practice to me.
Either way, it would be good to know how to store it as a variable for future reference.
You can pass the result to pg_fetch_assoc() and then store the value, or did you want to get the value without the extra step?
$result = pg_query($q);
$row = pg_fetch_assoc($result);
$account_type = $row['type'];
Is that what you are looking for?
Use pg_fetch_result:
$result = pg_query($q);
$account_type = pg_fetch_result($result, 0, 0);
But on the other hand it's always good idea to check if you got any results so I'll keep the pg_num_rows check.

Categories