Appending contents to an array [closed] - php

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I want to add data from my DB to an array when a user clicks a link e.g
echo 'ADD'.
i get the id of the element and query the database to get the details of the item clicked and display it using a for loop like this(on cart-page.php):
$cart = $_GET['cartid'];
$cartData = array();
$SQL = "SELECT * FROM tbl_product where id ='$cart'";
$result = mysql_query($SQL);
while($row = mysql_fetch_assoc($result)){
array_push($cartData, $row);
}
$length = count($cartData);
for($i = 0; $i < $length; $i++) {
echo '</tr>';
echo ' <td class="product">'.$cartData[$i]['name'].'</td>';
echo'<td class="quantity"><input type="text" value='.$cartData[$i]['quantity'].' class="inputform"/></td>';
echo '</tr>';
}
My problem is array_push() isn't appending the data. Each time i navigate away from cart-page.php and click a link the previous content in cartData[] is overwritten leaving only one row in cartData[] at a time. How i can i get the data appended to cartData[] whenever i click a link like the one shown above? Thanks

Does it need to be APpended? Why not just add it to the array and order the array at a later time?
PHP array sorting
while($row = mysql_fetch_assoc($result)){
$cartData[] = $row;
}
In addition, you should ALWAYS escape your data.
$cart = $_GET['cartid'];
The above code is vunerable to SQL injection. At the least, escape it!
$cart = mysql_real_escape_string($_GET['cartid']);
EDIT
In order to remember all previous cart additions, you will need to create a session, and add each click to it:
session_start();
$cartid = mysql_real_escape_string($_GET['cartid']);
function addToCart($cartid)
{
$SQL = "SELECT * FROM tbl_product where id ='{$cartid}'";
$result = mysql_query($SQL);
while($row = mysql_fetch_assoc($result)){
$_SESSION['cartItems'][] = $row;
}
}
function getCartItems()
{
print_r($_SESSION['cartItems']);
}
This will hopefully work as you expect. Sessions will retain state across browser refreshes.
To use this code, when you want to add items to the original $cartData, you need to call the function addToCart($cartid). This will add the item data to the cartItems session array
To see whats in the cart as an array, just use print_r($_SESSION['cartItems']);

Short answer: Your issue is not that you aren't adding the item to the array, it's that you don't understand how arrays work. Arrays do not persist across pages, they are instantiated to a single runtime of a single script unless declared otherwise.
MAJOR security flaw #1 - Sending cartid in URL:
Edit: I misunderstood this. Your cartid variable refers to a product_id. This is very poor variable naming, any programmer would assume this referred to an ID of a shopping cart. Whilst this security flaw is not relevant in this instance, I'm leaving it here for anyone who misunderstands your code and decides to copy it.
Firstly, this URL is a problem:
echo 'ADD'
This means that if I can guess another user's cart ID, I can add items to their shopping cart by visiting cart-page.php?action=add&cartid=100 where 100 is another user's cart ID. You should process the $cart variable internally using a validated session, not send them across the internet via GET or POST requests which can be user manipulated.
MAJOR security flaw #2 - Vulnerability to SQL Injection attacks:
The statement
$SQL = "SELECT * FROM tbl_product where id ='$cart'";
is incredibly dangerous. Let's say I submit this in my URL (properly encoded of course):
cartid = 2'; DROP TABLE tbl_product; SELECT * FROM tbl_product WHERE cartid='
This will then perform the following query on your database:
SELECT * FROM tbl_product where id ='2'; DROP TABLE tbl_product; SELECT * FROM tbl_product WHERE cartid='';
If you want to avoid this, you have a few options. The best of those options is to switch to using prepared statements, the easiest of those options is to use mysql_real_escape_string on everything you put into your database, like this:
$SQL = "SELECT * FROM tbl_product where id ='" . mysql_real_escape_string($cart) . "';";
Once you've fixed the above, we can fix the rest of the code:
First, we want to put your results into the array. As $results is already an associative array, you can either use it directly or store it like this:
$cartData = $results;
Keeping products in the cart
Edit: I misunderstood what you were doing, you're using a variable called $cart to store a product ID, you need to sort out your variable names.
In order to have an array which will persist across multiple page loads, you will need to make it a session variable, first you have to start a PHP session:
session_start();
Use a session variable like this:
$_SESSION['shopping_cart'] = array();
Then, when you 'add' a product, do this:
$_SESSION['shopping_cart'][$cartData['id']] = array(
'name'=>$cartData['name'],
'quantity'=>1
);
When you change the quantity, this:
$_SESSION['shopping_cart'][$productId]['quantity'] = $newQuantity;
Now, when you display the cart, instead of displaying directly from products, insert to the array using the above first, then return the contents of $_SESSION['shopping_cart'].
foreach was made for array transversal, use it!
Finally, don't use an ugly for loop to iterate an array, just do:
<?php foreach($_SESSION['shopping_cart'] as $product): ?>
<tr>
<td><?php echo $product['name'] ?></td>
<td><input type='text' value='<?php echo $product['quantity'] ?>'></input></td>
</tr>
<?php endforeach; ?>
Hope this helps, I haven't done all the work for you, but I have given you a lot of pointers in the right direction and identified some serious issues which matter.
Recommendations for this Project:
A shopping site is a major undertaking, you should spend some time reading about concepts like PHP security, sessions, relational databases etc. It may seem like an unnecessary hassle, but writing clean and secure code now means that when you have to debug it and make changes, you will be able to do so much more easily.
I'd also suggest you look into some (free, open source) MVC frameworks like Zend and CakePHP. These wont do all the work for you, but they will make it easier for you to keep your code well maintained and readable.

Related

Is there a way to combine independent functions of a page into single and query once to distribute fetched data individually

First of all, it's an idea, need to share because its solution is not present to me. But if applicable, it can help many PHP developer as well.
I'm developing a WordPress Ad Manager Plugin. Very simple thought, get an image URL into db with an id, and fetch the URL and show them with <img> tag. In my show ad function I did something like this:
<?php
function show_ad($id){
global $wpdb;
$table = $wpdb->prefix . "my_ad";
$query = $wpdb->get_results(
"SELECT *
FROM $table
WHERE id = $id;
");
$output = echo '<img src="'. $query[0]->img_url .'"/>';
return $output;
}
?>
The ad can be shown by any of these ways: PHP Function in Template (<?php show_ad($); ?>), Shortcode, Sidebar Widget. In all the cases the image showing process will be the same function.
Suppose, I have a site, where I added 20 ads into the plugin db. Now I want to show 10 of them into 10 different places, 10 different <div>s. in the same page. So what the function is doing, using the same function in 10 different places means 10 Individual db Queries. And 10 db Queries means 10 times hit to db.
So, I'm seeking a way to combine all the function into one and execute a single db query to fetch data. I'm dreaming something like the following. Assuming there are 10 different ad places in my page:
<?php
// A TOTAL FICTIONOUS CODE BLOCK
if( function_in_this_page_exists( 'show_ad' ) ) {
$function_array = make_them_array_with_vallues();
//so function_array looks like: array( '2','4','1','5','8','10','15', ... )
//execute the combined query function
//and query the db once
$query_result_array = combined_query_function();
//so the $query_result_array looks like: array('2'=>'http://url2.com','4'=>'http://url4.com','1'=>'http://url1.com', ...)
//now, distribute the data to the individual function where they are
//by executing another function that distribute fetched data where their id belongs
distribute_array_data_to_functions($query_result_array);
}
?>
Though it's a fictionous code block, but [if possible], with this way a simple db query can do all the individual queries instead. I don't think such a function-fetching-with-parameter thing is present now in PHP. Any idea?
Firstly, you might use the MySQL keyword IN to fetch more than one id.
Secondly, just write your processing function for the returned data-set as you imagined.
In other words, build the content, insert image URL for each for the ids.
After that, you might think about caching the query and caching the generated content.
$array_with_ids = array('1','2','3');
$sql = 'SELECT *
FROM `table`
WHERE `id` IN (' . implode(',', array_map('intval', $array)) . ')';

Retrieve constantly from database

I am doing this animation tool where I fetch a value from my database and then a picture will animate to a certain position. My question is if it is possible to retrieve data constantly or like every 5 seconds?
Somehow like this:
while(autoretreive){
$data = mysql_query("select * from ......");
}
UPDATED from here
Thanks for your answers! Made it a little bit clearer what to do! Maybe I can explain better what I'm doing in my code.
I am doing this animation program as said, where balls with information is moving around to different locations. I have one value that will be updated frequently in the database, lets call it 'city'.
First at previous page I post the balls of information I want based on the 'city' and I do like this (simplified):
$pid = $_POST['id'];
$pcity[0] = $_POST['city'];
$pcity[1] = $_POST['city'];
$pcity[2] = $_POST['city'];
//...
$while(autoretrieve) { // HOW TO?
$data = mysql_query(select * from table where city == $pcity[0] OR $pcity == [1] //...);
while($rows = mysql_fetch_array($data)){
$city = $rows['city'];
$id = $rows['id'];
if($city == example1){
"animate to certain pos"; //attached to image
}
else if($city == example2){
"animate to certain pos"; //attached to image
}
}
}
So for every update in the database the image will animate to a new position. So a time interval of 5 seconds would be great. I'm not an expert in coding so sorry for deprecated code. Not so familiar with AJAX either so what is going to be imported to the code? It is also important that the page is not reloading. Just the fetch from database.
you can do it with ajax and javascript
make one javascript function which contains ajax code to retrive data from database
and at your page load using setTimeout call your ajax function at every 5 second
You can use sleep function to control how often you want to fetch data.
while(autoretreive){
$data = mysql_query("select * from ......");
//output your data here, check more in link about server sent events bellow
sleep(5);
}
Since you haven't specified how you plan to access data I'm writing this answer assuming Server-Sent Events as they are only ones that make sense according to your question.
Now all this was according to your question which wasn't very clear on how do you plan to use data. Again you'll most likely want to fetch data using ajax, but Server Sent Events can also be a good way you could achieve this.
And don't use mysql_* it's deprecated, switch to PDO or mysqli_*

PHP Cart with Object Oriented PHP

I am developing a simple system of sample products with Object Oriented PHP, very simple thing. So far, no problem, but I have to create a button that adds a product code recorded in the database to a form in the sidebar. I do not know to develop a shopping cart with OO PHP, and codes that I find always give error because of the call of the database, or when the data list. I've been thinking of doing for JS, any help?
sorry my bad english
I got it, first I did when I click a link step by GET and the ID Code I need after seto it in a cookie, each cookie with an ID. Then I check if cookie has registered with the IDs. Not the best and most correct, but it works (more or less). Now another problem, I need to click two times to get the result as it passes by id and need to be caught refresh = /
I think it was a bit confusing but it is the maximum that dyslexia allows me to do hehehe
Here I set up the structure with the data I have in my product page:
add
<?php
$cod_get = $_GET['cod'];
setcookie("SITENAME_cod_".$id_get."", $cod_get, time()+3600, "/","", 0);
?>
And here I have a loop checking if cookie with ids, I think it will give problems, but for now I think it works ...
Thank you all.
$produto = new produtos();
$i = 0;
$produto->selecionaTudo($produto);
$produto->selecionaCampos($produto);
while($res = $produto->retornaDados()):
$res->id;
$i++;
$get_cookie = $_COOKIE['SITENAME_cod_'.$res->id.''];
if (isset($get_cookie)) {
echo $get_cookie.', ';
}else{
echo "";
}
endwhile;

PHP isnull First pass/Second pass flag

I have a PHP results page which starts off "first-pass" with ALL rows returned. It's a search listing of all pizza places in the county.
SELECT * from pizzeria;
Then the user can drill down into more detail... the page also has a CSS dropdown menu where the user can pick a specific neighborhood (which carries a URL):
href="samepage.php?neighborhood=HELLSKITCHEN"
which then changes the query after I pick up the $_GET[]
SELECT * from pizzaria WHERE nbh=(the $_GET[] variable sent in the URL);
but I'd like the page to call itself and I have header("Cache-Control:no-cache"); at the top.
I'm trying to create a first-pass or first visit flag variable with the isnull() function:
if (is_null($firstpass)) {
$query = SELECT all the records from the pizzaria table
} else {
$query = SELECT only the records WHERE I $_GET[] the value from the reloaded URL
}
It seems though that the $firstpass variable doesn't stick on reloads. Should I SESSION that variable? (though still have the problem of constantly resetting it)
Or maybe implement some other approach?
I know I can redirect to a separate second page and javascript back to this page to avoid "headers already sent", but I want to avoid the round-trip back to the client.
Is there a known best practice on reloads with new info? Kinda new to PHP here. thanks
Maybe I didn't understand well your problem but why wouldn't you do :
if (!isset($_GET['example'])) {
$query = 'SELECT * FROM pizzerias';
} else {
$query = 'SELECT * FROM pizzerias WHERE pizzeria = \'.mysql_real_escape_string($_GET['example']).\' LIMIT 1';
}
at the first pass because, it seem that the $_GET variable is set only when the user choose a pizzeria?
Here is a more targeted answer.
NOTICE: mysql_* functions are being depreciated, so use PDO instead. In my example I'm being semi-lazy and not using PDO.
//Connect to database and define table up here
...
if(!isset($_GET['neighborhood')){
$q = "SELECT * FROM pizzeria;";
}else{
$q = sprintf("SELECT * FROM pizzeria WHERE nbh=%s",mysql_real_escape_string($_GET['neighborhood']));
}
$query = mysql_query($q);
foreach($row = mysql_fetch_array($query,MYSQL_ASSOC){
//display the updated view of restaurants.
}
I would also suggest that you use jQuery for that Web 2.0 effect. It's really nice when you select from a drop-down menu and things magically move without a page reload.

select from dropdown list containing sql data

Pls help.
I am working on a php project and this requires adding and altering data from the SQL database. There are two tables involved with this: emp which contains employee details and pay containing payroll records for each employee.
I would like to have a dropdown list containing all employee names (empname) from the database. Below the list is a form where the user shall input the payroll details. These details will then be saved into the SQL pay table corresponding to the employee name selected.
I've tried searching over the web but it doesn't seem to similar to my problem. How should I do this? Thanks!
Wihtout knowing any more details about your datbase, table structure and other stuff, this is closes that I could get.
<?php
/* Connect to SQL and retreive data */
$sqlConf = array('u'=>'username','p'=>'password','h'=>'localhost','d'=>'myDatabase');
$sqlCon = mysql_connect($sqlConf['h'], $sqlConf['u'], $sqlConf['p']);
if ($sqlCon) {
$emp = array();
mysql_select_db($sqlConf['d'], $con);
$result = mysql_query("SELECT * FROM emp");
while($row = mysql_fetch_array($result)) { $emp[] = $row; }
mysql_close($sqlCon);
}
/* Generate select box contents */
$html = '<select name="emp">';
$html .= '<option>Employee list</option>';
if (!empty($emp)) {
foreach ($emp as $k => $v) {
$html .= '<option value="'.$v['empid'].'">'.$v['empname'].'</option>';
}
}
$html .= '</select>';
/* Output */
echo $html;
?>
Sounds like you need to learn some basic php/SQL. The basic outlines of the problem are:
Query the dropdown list from SQL, and display in an option-select.
When they the form submit, send a corresponding query to update the database.
Is there some particular aspect of this problem that you can't get past?
This can be solved in any number of ways and the overall structure, design and layout of your application would dictate which route to go.
You could have classes that represent your database objects, classes that represent your forms, you could print your forms by mixing php and html like a crazy person and so on and so on.
Then it all depends on if you will be using ajax or not.
So give us a bit more information about how your application is designed and that will probably help.
If you have not started at all I would suggest you to look into some of the many frameworks. Zend Framework or Symphony for example. They have a good way of handling db abstractions and forms creation etc.

Categories