save database rows in a cookie and then retrieve them - php

i want to use PHP setcookie() and i am having a problem with it. as a matter of fact i want to fetch some rows from data base then first save them in cookies and then retrieve them. consider i have a table in my database with multiple rows and for example 4 column. how can i do this. this is my current code. any idea thank you
<html>
<body>
<?php
error_reporting(0);
include("config.php");
$quer= "SELECT*FROM ".$db_table." ";
$query=mysqli_query($connect,$quer)
or die(mysqli_error());
?>
<?php while($row = mysqli_fetch_array($query)):
setcookie("$cookiename", $row, 2 * 24 * 60 * 60 * 1000);
//i do not know how can i retrieve columns now
?>
<?php endwhile;?>
</body>
</html>

In your case mysqli_fetch_array() function returns an multidimensional array, which means that you should refer to the $row variable, for example:
$row[0][0] // 1st row, 1st column
$row[2][4] // 3rd row, 5th column
You can also fetch data as an assotiative array, look at http://php.net/manual/en/mysqli-result.fetch-array.php

Here's an example:
$cookie_name="cook";
setcookie($cookie_name, $row['key'],2 * 24 * 60 * 60 * 1000), "/");
Check this out for more:setcookie

If you really want/need to save the entire row in the cookie you can pack the array $row in a single string eg as JSON:
//modified example from #Satty
$cookie_name="cook";
setcookie($cookie_name, json_encode($row),2 * 24 * 60 * 60 * 1000), "/");
//to read the cookie:
if(isset($_COOKIE[$cookie_name]))
$row_from_cookie = json_decode($_COOKIE[$cookie_name]);
If there is a certain caracter that you can be sure of that it isn't present in your data so it can be used as a separator (eg. ";") you could also use implode and explode to pack your entire array in a single string.
But if some of the columns are of any type that can contain any character I wouldn't do it like that since there can always be a character that you didn't expect in your data (eg. if you only store names you may assume that nobody has a semicolon in his name but it's still possible that somebody enters a semicolon in the input field).

Related

Select query returns nothing for a random number

I am trying to fetch values from the database where a certain random number has a match. Here is my line of code
echo $rand_number = $_POST['rand'];
$select = mysqli_query($connection,"select * from temp_info where rand_number = '$rand_number'");
I am successfully receiving the random number which is also saved in the database. When I want to fetch from the database using the mysqli_fetch_array command, it returns nothing. However, when I write the random number itself instead of the variable $random_number. The query returns the desired result.
I have double checked that the $rand_number has the same random number that is saved in the database. What seems to be the problem?
Try this it might help :
$select = mysqli_query($connection,"select * from temp_info where rand_number ='".$rand_number."'");
could be the rand_number is stored in db like a number then try using rand_number = $rand_number without quotes
$select = mysqli_query($connection,"select *
from temp_info
where rand_number = $rand_number");

Converting exploded array into string

In the project that I am creating, I have a mysql column that is an array of different pieces of data from the database. These pieces of data have info that I want to display. In order to separate these items in the array I used,
$get_query = mysql_query('Select array FROM data');
while($dataRow = mysql_fetch_assoc($getfrnd_query)) {
$array = $dataRow['array'];
if($array != "") {
$data_from_array_column = explode("," $array);
$getdata = mysql_query("SELECT * FROM info WHERE item = $data_from_array_column");
//Then I used a mysql_fetch_assoc to get data based on the item.
}
}
When I run this code, I get an error "Array to string conversion on the line with $getdata".
Is there any way to get this to work?
Thank you.
The problem is that explode returns an array containing the strings in between the character(s) you used as a delimiter (, in your case), not a string.
PHP is getting mad because it doesn't know how to convert your array to a string automatically. So, you will need to convert it yourself. The options are:
You want to select the row where item is equal to the nth element in the array, $data_from_array_column. If this is the case, you need to insert the following line of code after your explode:
$data_from_array_column = $data_from_array_column[0];
If you want to select where it matches any of the elements in the $data_from_array_column array, it will get more complicated. You would need to add this line after the explode:
$data_from_array_column = implode("' OR item='",$data_from_array_column);
and change your query on the next line to:
$getdata = mysql_query("SELECT * FROM info WHERE item='$data_from_array_column'");
This will create a MySQL query that looks some thing like this:
SELECT * FROM info WHERE item='foo' OR item='bar' OR item='bla'

PHP / Mysql increment by one from previous row

I am looking to take the ID that auto increments already from the latest row in a table and increment it by one and append it on to a returned result from that same table. So if the row id is 5 and the tabledata result is product5, I need it changed to product6 in the php result. So when the data is resubmitted it is in-line with the new row ID.
EDIT:
I need it displayed and incremented before the sql insert because it's also emailed on data submit for ordering. The database insert is just to retain the order record.
Current code display results:
$conn=mysql_connect(" "," "," ");
mysql_select_db("database",$conn);
$sql="SELECT * FROM table WHERE ID=(SELECT max(ID) FROM table)";
$rs=mysql_query($sql,$conn) or die(mysql_error());
$result=mysql_fetch_array($rs);
echo '<table>
<tr>
<td>Data: '.$result["tabledata"].'</td>
</tr>
</table>';
?>
What if you modify the query to select value after incrementing it. i.e.
SELECT ID+1 AS ID, /*all other fields of the table */ FROM table WHERE ID=(SELECT max(ID) FROM table)
So if I understand, you have two fields, not one:
id tabledata
1 PO-01
5 product5
is a Purchase order field so it stays in line with the previous just one number different (Example PO-01 to PO-02)
First thing that comes to mind is not to write that number in two places anyway. You could have
id tabledata
1 PO-%02d
5 product%d
and then wherever you had the row data, you could use
sprintf($row['tabledata'], $row['id'])
to get the "human readable" version of tabledata. Then to get the "next" ID you could just do
sprintf($row['tabledata'], $row['id'] + 1)
Otherwise, you need to extract the number from the text field. This requires that you know in advance its format (e.g. is it %d or %02d or...?).
If you know it is just the number, with variable length, as in your first example (product5 to product6), you do
$table['tabledata'] = preg_replace('#\\d+$#', $table['id'] + 1);
The above will replace the last sequence of numeric digits (here, 5; it could be 1701 for example) with 6. Or you can capture the number with preg_match and much the same expression, only in parentheses, increment it, and store it back.
If it is a fixed-length sequence of numbers as in your second example (PO-01 to PO-02), you just use substr:
$size = 2; // Two-digit number
$num = substr($table['tabledata'], -$size);
$prd = substr($table['tabledata'], 0, -$size);
$table['tabledata'] = $prd . sprintf("%0{$size}d", $num + 1);
An even more complicated solution would be to merge the two versions into a "decoding" function that would count leading zeroes and digit lengths and use this to determine the format being used. This however would have problems in some cases (e.g. maybe the next number out from AB-99 is not AB-100 but AC-00 or AC-01), so all in all I think this is best left to someone with the knowledge of the specific domain.

how to +1 to the MAX record from a field

.i have the following code:
$task_id = mysql_query("SELECT MAX(task_id) from it_task");
echo $task_id;
.what I want to do is to get the highest value from a field named task_id on the table it_task. Instead of getting a result which is an integer I get "Resource id #5". how do i get around this?
mysql_query generates a resource which you then have to read using another mysql_ function. In this case you'll need a 2nd line to read from the query's result:
$result = mysql_query("SELECT MAX(task_id) from it_task");
$task_id = mysql_result($result, 0, 0); // get the first row, first column
echo $task_id;
Any problem here??? In my postgres sql, I can have:
select max(task_id)+1 as max from it_task;
Yes, mysql_query always returns a resource (unless it returns false), which you have to work on using one of the mysql_ functions like mysql_fetch_assoc.

How to grab items from a DB by date

This is my script:
$spending_period = time() - (30 * 24 * 60 * 60);
$spending_period = date('Y-m-d', $spending_period);
$monthly_income_query="SELECT amount FROM budget_items WHERE (date_code >= '$spending_period') && (type=='Income') ORDER BY date_code DESC";
$monthly_income_result=mysql_query($monthly_income_query);
while($monthly_income_scan=mysql_fetch_array($monthly_income_result)){
if($montly_income_counter >=1){
$monthly_income=$monthly_income + $monthly_income_scan['amount'];
}
}
I receive an error that mysql_fetch_array() is not a valid result resource.
The goal is to grab only items in the budget_items table that have a date_code (using the DATE type) occurring within the last 30 days.
Anyone have suggestions?
If something doesn't work with your
query - you may want to try it out in
mysql console with some sample date.
If data is returned, then try printing out a query. I have a hunch that $spending_period variable might not be interpolated correctly into your query string (try using '{$spending_period}' instead of '$spending_period'.
You need to format the date as a strong and use CAST inside the select statement to accept the value as a date value.

Categories