I've a online book store where I sell books. Here I store data's of the cart on session. When two or more books are selected there may not be all the books available. I can do check only fore one book that is available or not. But I can't make it through when two or more books selected for ordering. What I did for one book is:
$result = mysql_query("SELECT id FROM book_table WHERE id IN ($cart)");
while ($row = mysql_fetch_array($result)) {
$q=mysql_num_rows(mysql_query("SELECT available FROM book_table WHERE id='$row[0]'"));
if($q!=0){
//order goes fore processing.
}
else{
//books not available.
$q2=mysql_fetch_array(mysql_query("SELECT name FROM book_table WHERE id='$row[0]'"));
echo "The book: $q2[0] Not Available";
//If there is more than 1 books in the cart and one or two books of them are not in the stock, its showing the order cant be processed(But I want to show which books aren't available).
}
}
Here $cart is the books cart saved on session like 1,2,3,4.
Now I need to show which books aren't available to buy by redirecting with another page.
Can anyone help me out on this?
make a array and put id and availaibilty as key and values pair and check for availaiblity for each id.
$all_available = true;
$orders = array();
$result = mysql_query("SELECT id, available, name FROM book_table WHERE id IN ($cart)");
while ($row = mysql_fetch_assoc($result)) {
if ($row['available')) {
$orders[] = $row['id'];
} else {
$all_available = false;
echo "The book: " . $row['name'] . " is not available.\n"
}
}
if ($all_available) {
// Process $orders
} else {
// Send redirect
}
You can do like below,
$query=mysql_query("SELECT id,available FROM book_table WHERE id IN ($cart) ");
$books_available_num = mysql_num_rows($query);
$books_order_num = count(explode(",",$cart));//i think there should be better way to do this...
if($books_available_num==0){
//no book is available
}elseif($books_available_num==$books_order_num ){
//all books are available
while($fetch=mysql_fetch_array($query)){
//order done successfully.
}
}else{
//some are available some are not.
while($fetch=mysql_fetch_array($query)){
if($fetch['status']=="available"){
//place in order
}else{
//this is not available
}
}
}
//rest of code. I think now you can do yourself.
I show you method and you can improve yourself. Code may contain errors, and you can improve it.
you can use ajax like without redirecting to other page
$.ajax({
url :'yourpage.php',
type :'post',
sucess : function(data){ alert(data)}
})
and your php code need a bit modification
$result = mysql_query("SELECT id FROM book_table WHERE id IN ($cart)");
$error = array();
while ($row = mysql_fetch_array($result)) {
$q=mysql_num_rows(mysql_query("SELECT available FROM book_table WHERE id='$row[0]'"));
if($q!=0){
//order goes fore processing.
}
else{
//books not available.
$q2=mysql_fetch_array(mysql_query("SELECT name FROM book_table WHERE id='$row[0]'"));
$error[] = "The book: $q2[0] Not Available";
//If there is more than 1 books in the cart and one or two books of them are not in the stock, its showing the order cant be processed(But I want to show which books aren't available).
}
if (!empty(error))
{
// print array as you want
}
else
{
echo "order successfully placed"
}
}
see more about jquery ajax
if you want to do that redirecting to other page the out $error in session.
I dont think any other thing can help you
NOTE : avoid using mysql_* as they are deprecated
Related
I have a question please,
I am making an online store.
It offers a product with an available quantity attribute
Let's imagine a certain product has 1 quantity available only.
2 users are logged in and added this element to cart.
They both at the same time checked out (I am trying to do this by splitting 2 browsers in the screen and pressing at the checkout button simultaneously.)
How can I manage that the product checkout is successful for only one user in this case?
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(isset($_POST['qty_array'])&&isset($_POST['ids_array'])){
$order_address=$_POST['addressCart'];
$ids_array=$_POST['ids_array']; //this is array of product ids in the cart
$qty_array=$_POST['qty_array']; // this is array of quantities in the cart
$date=date("Y-m-d H:i:s");
$j=0;
$x=0;
foreach($ids_array as $id){
$query = "SELECT available_quantity from products where product_id='$id' AND product_active=1";
$result = mysqli_query($db,$query);
$row = mysqli_fetch_array($result);
$qty1=$qty_array[$j];
if($row['available_quantity']==0 || $qty1>$row['available_quantity']){
$x++;
}
$j++;
}
if($x!=0){
$msg="unable_checkout";
echo $msg;
}
else{
$bool=mysqli_query($db,"INSERT INTO order_table(customer_id,order_date,order_address)
VALUES ('$customerID','$date','$order_address')") or die("".mysqli_error($db));
$order_id=mysqli_insert_id($db);
if($bool){
$k=0;
foreach($ids_array as $id){
$query2 = "SELECT * from products where product_id='$id' AND product_active=1";
$result2 = mysqli_query($db,$query2);
$row2 = mysqli_fetch_array($result2);
$qty_available=$row2['available_quantity'];
$qty=$qty_array[$k];
$unitprice=$row2['product_price'];
$discount=$row2['product_discount'];
if($qty<=$qty_available && isset($_SESSION['cartProds']) && $qty_available!=0 ){
mysqli_query($db,"INSERT INTO order_details(order_id,product_id,unitprice,discount,quantity)
VALUES ('$order_id','$id','$unitprice','$discount','$qty')") or die("".mysqli_error($db));
$newqty=$qty_available-$qty;
mysqli_query($db,"UPDATE products SET available_quantity='$newqty' WHERE product_id='$id'");
}
$k++;
}
}
$msg="checkedout_successfully";
//unset inserted order :
unset($_SESSION['cartProds']);
$_SESSION['nOfProds']=0;
echo $msg;
}
}
I need to stop the submission and to not insert anything when one of the quantities is equal to Zero.
What I am getting is that if 2 users want to checkout 3 same products at the same time (one product is added to order table of user 1 , and the other 2 are added to order table of user2 ..which is wrong , I want in this case to make checkout successful for only one user, and to give a warning alert msg for the second user)
Ajax code:
$(document).ready(function() {
$("#enableAddress").change(function(){
if($("#enableAddress").prop("checked") == true){
$("#addressCart").prop('disabled',false);
}
else{
$("#addressCart").prop('disabled',true);
}
});
$("#checkoutBtn").click(function(){
var ids_array = [];
$('input[name^=checkoutHidden]').each(function(){
ids_array.push($(this).val());
});
var qty_array = [];
$('input[name^=quantity]').each(function(){
qty_array.push($(this).val());
});
var telCart = $("#telCart").val();
var addressCart = $("#addressCart").val();
$.ajax({
type: "POST",
url: "../phpOnly/checkOut.php",
data: { ids_array:ids_array, qty_array:qty_array,addressCart:addressCart},
success: function(msg) {
// alert(msg);
if(msg=="checkedout_successfully"){
// $("#orderMsg").fadeIn(3000);
// $("#cartBody").fadeOut(2000);
// $("#nOfProdsSpan").text('0');
alert(msg);
}
else if(msg=="unable_checkout"){
// window.location.href="#";
// $("#inavailableMsg").fadeIn(1000);
alert(msg);
}
}
});
});
});
Don't forget that I am taking into consideration that the available quantity is only 1 ( which only one user can order it only)
An approach to handle concurency would be to change the logic, and start the process by attempting to update the products table, with a where clause that ensures that the requested quantity is available, like so:
UPDATE products
SET available_quantity = available_quantity - 1
WHERE
product_id = :id
AND product_active = 1
AND available_quantity > 0
You can then check the number of rows affected by the query:
if one row was affected, then it means the that check out did succeed; you can then do the rest of the process (create the order and the order details records)
if no row was affected, then the check out failed; do not create the order
With this technique, you let the database handle the concurrency for you, and you are guaranteed to never sell more product than available.
Working on a website where you can add news, that data gets sent to a database and then converted to json, which is used in an app.
I'm having trouble with filtering the news using the url. I want to be able to filter news by 2 database columns, Type and Region. When I add the news I need to specify which type[can only choose 1] of news it is and in what region[can choose multiple] it goes under. Now when i'm in the app, let's say I want to only see "Emergency" news from "X" region. For that I would check "Emergency" type checkbox and "X" region checkbox.
With my current code I can filter the news by type perfectly, but im having trouble adding an extra filter to only show X region news.
<?php
function turnIntoUTF8($arrayName) {
if (is_array($arrayName)) {
foreach ($arrayName as $k => $v) {
$arrayName[$k] = turnIntoUTF8($v);
}
} else if (is_string ($arrayName)) {
return utf8_encode($arrayName);
}
return $arrayName;
}
$tag = $_GET["tag"];//Tag = type
//Tried adding a new GET here.
$sql = "SELECT * FROM news WHERE
FIND_IN_SET(`tag`, '$tag')//Tried to do another FIND_IN_SET here with &&.
ORDER BY id DESC";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
echo json_encode(turnIntoUTF8($emparray));
mysqli_close($connection);
?>
Currently I can use this url: http://localhost/vvuudised/getNewsJson.php?tag=uudis,teade to show only news that have their type set as "uudis" or "teade. The outcome is the following:
Now if I wanted to I would filter the news to only show lets say "rohuneeme" region news with the url. How can I do that. Thanks and sorry for the bad explanation.
I am trying to create a post-comment system, with simple php-mysqli, as simple as it is, it does not seem to give me the result in the fashion I want i.e:
---POST MESSAGE----
-----comments-----
Here is the code I used:
<?php
session_start();
include_once('php_includes/db_conx.php');
$user=$_SESSION['user'];
$o =mysqli_query($db_conx, "SELECT post.id,post.post,post.date,post_comments.poster,post_comments.comment,post_comments.date FROM post LEFT JOIN post_comments ON post.id=post_comments.post_id AND post.username='$user' ORDER BY post.date");
while($r=mysqli_fetch_array($o,MYSQLI_ASSOC)){
$status= $r['post'];
$date=$r['date'];
$com=$r['comment'];
$pid=$r['id'];
$poster=$r['poster'];
if(count($pid) > 1){
}
echo $status.'|'.$pid.'|'.$date.'<br>'.$poster.':'.$com.'<hr>';
}
?>
It seems to duplicate the post for each comment for same post.
Not sure am making sense, but i will appreciate an answer.
First, add post id to your query's ORDER BY. That will ensure that your post and all its comments appear together, and only once. (I'd recommend adding post_comments.date as well so your comments will appear in order, but that won't be necessary to get the grouping working.)
... ORDER BY post.date, post.id, post_comments.date
Then keep track of the post id as you go. Echo the post information only when the post id changes.
$id = null; // initialize to null
while ($r = mysqli_fetch_array($o, MYSQLI_ASSOC)) {
$pid = $r['id'];
$status = $r['post'];
$date = $r['date'];
$com = $r['comment'];
$poster = $r['poster'];
if ($pid !== $id) {
echo $status.'|'.$pid.'|'.$date.'<br>'; // new post, so echo post info here
$id = $pid; // $id becomes new post id
}
if ($com) {
echo $poster.':'.$com.'<br>'; // echo comment if present
}
}
One other thing that will probably cause some trouble is that you have selected both post.date and post_comments.date in your query, so I'm not sure which one will be in $r['date']. It would be a good idea to alias at least one of those columns to disambiguate them.
I am having some trouble with displaying some SQL query results.
Goal: I want to display the Helper 'name' in the table that is being generated if there is a helper signed up in the 'signup' table for that event 'eid' (event id).. If (1)there is no helper then display 'waiting for help', (2) there is a helper then display 'name -- awaiting approval..' and (3) else just display the name of helper..
Tried running the SQL query in phpMyAdmin with hard coded values and I get the results that I want so I know it is not my query. Have a suspicion that it is just the print out of the info into the table that is wrong somewhere. The table will display the data up until the ZIP from the address and then the next column which is the 'Helper' column does not display anything at all. So it makes me think I have a simple typo somewhere based on my if() statement logic BUT also find it interesting also that when I do the line:
echo "testing method -> ".getHelperIdOrName(2, 80)."<br>";
I cant get the table to print out at all. Not sure if this is related to my exact issue but it seems it could be. After I put this function in stuff stopped working so it seems like it could be culprit. The return of the function should either return an ID (int), a name "string", or just a generic value X (string)..
Any and all help is appreciated!
function getHelperIdOrName($x, $eid){
//Get the helper name first
$helperName = "";
$helperId = 0;
$sql = "SELECT id, first FROM users WHERE id IN (SELECT helper FROM signup WHERE gner = '".$userId."' AND eid = '".$eid."')";
$result = mysqli_query($db,$sql);
$row = $result->fetch_assoc();
if ($x == 2){
$helperName = $row["first"];
return $helperName;
}
else if ($x == 1){
$helperId = $row["id"];
return $helperId;
}
else {
return "X";
}
}
echo "testing method -> ".getHelperIdOrName(2, 80)."<br>";
//look for calendar and/or business approved events (approved=1) to display on page
$sql = "SELECT s.gner, s.helper, s.eid, s.approved, e.name, e.date, e.summary, e.street, e.city, e.state, e.zip
FROM signup s
INNER JOIN events e ON e.id = s.eid
INNER JOIN users u ON u.id = s.gner
WHERE s.gner = '".$userId."'";
$result = mysqli_query($db,$sql);
echo "<h3 class=\"text-center\">Events I'm Going To</h3>";
echo "<table class=\"table table-hover\"><tr><th>Event Name</th><th>Date</th><th>Summary</th><th>Location</th><th>Helper</th><th>Remove</th></tr>";
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["name"]."</td><td>".$row["date"]."</td><td>".$row["summary"]."</td><td>".$row["street"].", "
.$row["city"].", ".$row["state"]." ".$row["zip"]."</td>";
$tmp_eid = $row["eid"];
if (getHelperIdOrName(2, $temp_eid) == "X"){
echo "<td>Waiting for help..</td>";
}
else if ($row["approved"] == 0){
echo "<td>".getHelperIdOrName(2, $temp_eid)." -- Awaiting Approval (see below)</td>";
}
else {
echo "<td>".getHelperIdOrName(2, $temp_eid)."</td>";
}
echo "<td><form method=\"post\" action=\"remove.php\">
<button type=\"submit\" name=\"remove\" value=\"".$row["eid"]."\">Not Going</button></form></td></table>";
}
}
else echo "</table><br><p class=\"text-center\">You are not signed up for any events. Click here to sign up for events near you!</p>";
Thanks for that Jeff. The issue was that inside of the function it indeed did not know what $userId was even though I had the include statement at the top of my php file. I had to add this line into my function at the top..
global $db; //is part of my db my connection info in my config.php file
and then I also passed the $userId to the function as a parameter
these lines are what I used to help me see the errors:
ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(-1);
i also had some ending < /table > tags inside some if logic so that fixed the funky displays I was getting (2nd row of table being outside of the table)
Sorry for my English,
I need to display a banner ad from a database every third row in php. Banner ads and rows with the classified are selecting from database. To this moment I create something like this:
Rows with the classifieds from database:
while(#$row_select_kat = mysql_fetch_assoc($results_select_kat))
{
... //classifieds from database
if(($row_select_kat['id_ogloszenia']%3)==0)
{
$lim = 1;
echo"<div id=\"rek_poz_a\">";
modAddsDisplayHelper::wyswietlReklamyPozA();
echo"</div>";
}
}
Selecting banner ads from databes:
public static function wyswietlReklamyPozA()
{
$baza_danych = &JFactory::getDbo();
$query_sel_all_banners = "SELECT * FROM juxhv_banners";
$baza_danych->setQuery($query_sel_all_banners);
$baza_danych->query();
$banner_ads = $baza_danych->loadObjectList();
echo$query_sel_all_banners;
echo"Liczba x= ".$l_ogloszen;
foreach($banner_ads as $banner_ad)
{
if($banner_ad->state==1)
{
echo"$banner_ad->name<br/><img src=\"images/$banner_ad->username/bannerwerbung/$banner_ad->zdjecie\" width=\"434px\" height=\"94px\" />";
}
else
{
echo"No banner";
}
}
}
When I doing this in that way at every three rows displaying all three banner ads. How can I display only one banner ad every three rows?
URL: http://www.nachbarhilft.de
Greetings
You need to use external counter variable which will be incremented on each iteration and depending on its condition you can check modulo condition: Please see the following updated code.
[code]
$recordCount = 0;
while(#$row_select_kat = mysql_fetch_assoc($results_select_kat))
{
if(($recordCount%3)==0)
{
echo"<div id=\"rek_poz_a\">";
modAddsDisplayHelper::wyswietlReklamyPozA();
echo"</div>";
}
$recordCount++;
}
if($banner_ad->state == 1) {
echo"$banner_ad->name<br/><img src=\"images/$banner_ad->username/bannerwerbung/$banner_ad->zdjecie\" width=\"434px\" height=\"94px\" />";
break;
}
In this way you only print one banner, but always will be the first with state == 1 in the database.
Maybe is better improve the query:
$query_sel_all_banners = "SELECT * FROM juxhv_banners WHERE state = 1 LIMIT 1";
That will give you the same result, I think.
I hope it helps