PHP MySQL maths update value in database [closed] - php

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
So ive got a rating system in place on a website im making. Currently each itema has a plus and minus button on either side as well as a visible rating level in this case its 3.1 for one of the items.
Im trying to programme both the plus and minus buttons in such a way that when the user presses them then the rating either increases or decreases by one.
Currently ive only implemented the minus button, however, when I click it the rating value doesnt decrease. It stays at 3.1. The page works fine and when i click on the "minus" button i get the error Call to a member function execute() on a non-object on line 67 which is the $stmt->execute()
Here is the code i have so far:
<?php
$results = $mysqli->query("SELECT * FROM programmes ORDER BY ProgrammeName ASC");
if ($results) {
$i=0;
echo '<table><tr>';
echo '<br/>';
echo '<br/>';
while($obj = $results->fetch_object())
{
echo '<td>';
echo '<div class="tvProgs">';
echo '<form method="post" id = "programmes" action="">';
echo "<input type=\"hidden\" name=\"progID\" value=\"".htmlentities($obj->ProgrammeID)."\" />";
echo '<div class="progImage"><img src="images/'.$obj->Image.'"></div>';
echo '<div class="progTitle"><h3>'.$obj->ProgrammeName.'</h3>';
echo '<div class="progRating"><h5>'.$obj->Rating.'</h5></div>';
echo '<div id = "btnMin"><input type="button" id ="minus" value ="-"/></div>';
echo '<div id = "btnPl"><input type="button" id ="plus" value ="+"/></div> ';
echo '<br/>';
echo '</form>';
echo '</div>';
echo '</td>';
$i++;
if ($i == 5) {
echo '</tr><tr>';
}
}
echo '</tr></table>';
}
if(isset($_POST['minus'])){
$newRating = 1;
$ID = $_POST['progID'];
$upsql = "UPDATE programmes SET Rating = Rating - $newRating WHERE progID='$ID'";
$stmt = $mysqli->prepare($upsql);
$stmt->execute();
}
?>
Ive kept the ID field hidden as i dont want that to be displayed on the web page. I just want to update the rating of a particular ID.
any informatino will be appreciated

Change your query from:
$upsql = "UPDATE programmes SET Rating = Rating - $newRating WHERE progID='$ID'";
To this:
$upsql = "UPDATE programmes SET Rating = Rating - $newRating WHERE ProgrammeID='$ID'";
Hope it should work..

For using _POST['some_name'] field on your form should have attribute name with value some_name
<input type="button" name="some_name" value="Some value"/>
Currently you have id="minus" which is not passed to a server. At least you should have:
<input type="button" id ="minus" name="minus" value="-" />
^ we got name here
And second thought - as your plus/minus buttons have no type="submit" I suppose your form doesn't submit, unless you have some hidden javascript.
Try setting you plus/minus buttons like:
<input type="submit" name="minus" value ="-"/>
<input type="submit" name="plus" value ="+"/>

Alternatively, you could use HTML5 number type input for your rating. Depending on the broswer you will have a little spinner that will do this task. Note that not all the broswers render this the same.
echo '<div class="progRating">
<h5><input type="number" id="rating" name="rating" value="'.$obj->Rating.'"/></h5></div>';
Then you have to update only the rating with its new value.
More info here: http://www.html5tutorial.info/html5-number.php

Related

Retrieving Mysql data and print in specific order

I got a problem that driving me crazy for last 4 or 5 days.I'm building a facebook style posting system,where users can post on their timeline and friends of that user can comment on every specific post.I'm actually having problem to print that correctly in php.Your help would be greatly appreciated.Thanks a lot in advance for your time.
The 'status' table that I created for all the post contain following values
id osid author type data postdate
1 1 helal a Hi... 2014-08-20
2 1 Abdul b Hey.. 2014-08-20
3 1 helal b Good.. "
4 4 helal a Hello.. "
5 4 Irin b Hi... "
so,basically,all new posts are having type 'a' and all replies are having type 'b'.And also,all separate conversation(post and replies) is having same 'osid',so that user can see separate conversation on separate div with a comment box attached to each post(followed by conversation)
I coded the following code,but it's not giving me expected result.
$sql="SELECT * FROM status WHERE type='a'";
$query=mysqli_query($connect_dude,$sql);
$numrow=mysqli_num_rows($query);
if($numrow>0){
while($row=mysqli_fetch_assoc($query)){
$id=$row["id"];
$osid=$row["osid"];
$name=$row["author"];
$data=$row["data"];
$date=$row["postdate"];
$query_replies = mysqli_query($connect_dude, "SELECT * FROM status WHERE type='b' AND osid='$id' ");
$replynumrows = mysqli_num_rows($query_replies);
if($replynumrows > 0){
while ($row2 = mysqli_fetch_assoc($query_replies) ) {
$statusreplyid = $row2["id"];
$statusreplyosid = $row2["osid"];
$replyauthor = $row2["author"];
$replydata = $row2["data"];
$replydata = nl2br($replydata);
$replypostdate = $row2["postdate"];
$replydata = str_replace("&","&",$replydata);
$replydata = stripslashes($replydata);
$status_replies .= '<div id="reply_'.$statusreplyid.'" class="reply_boxes"><div><b>Reply by '.$replyauthor.' '.$replypostdate.':</b><br />'.$replydata.'</div></div>';
}
}
$statuslist .= '<div id="status_'.$id.'" class="status_boxes"><div><b>Posted by '.$name.' '.$date.':</b> '.$statusDeleteButton.' <br />'.$data.'</div>'.$status_replies.'</div>';
if($logged == $username){
$statuslist .= '<form id="posting1" action="user.php?u='.$logged.'" method="post" enctype="multipart/form-data"><textarea id="replytext" name="replytext" class="replytext" placeholder="write a comment here '.$osid.'"></textarea><input id="hel1" name="hel1" type="hidden" value="'.$osid.'"><input type="submit" id="replyBtn" name="replyBtn" value="reply"></form>';
}
}
$postbox="<form id='posting' action='user.php?u=$logged' method='post' enctype='multipart/form-data'><input id='hid' name='hid' type='hidden' value='<?php echo $iid;?>' ><textarea id='taxi' name='taxi' rows='15' cols='40' placeholder='Say something to your Buddies'></textarea></br><input id='hel' name='hel' type='submit' value='post'></form>";
}
}
and I have used echoed '$statuslist' on html part.
It keeps compounding all replies within all the post.
Desired form of result,let say
For post no 1
helal:Hi...
Abdul:hello...
helal:Good....
"then the comment box(reply text area)"
For post no 2
helal:Hello...
Irin:Hi...
"then the comment box(reply text area)"
so on and so forth within separate divs for separate conversation
I'd say you need to reset $status_replies in the outer loop. Add:
$status_replies = '';
anywhere between the two while lines.

Adding 2 or more items to the cart

So here is my problem. I am able to add one item to the cart. But I want to be able to add more items. I am using form and GET method to add the item
require "connect.php";
$query = "SELECT `DVDID`, `NameOfTheDVD`, `Quantity`, `Price` FROM `DVD` ";
$stmt = $dbhandle->prepare($query);
$stmt->execute();
$num = $stmt->rowCount();
if($num>0){
while ($row = $stmt->fetch(PDO::FETCH_OBJ)){
if(!isset($_SESSION['cart'])){
echo "<table border='3' cellpadding='10' position='relative` bottom= '450px' color = 'blue';>";//start table
echo '<div class="DVD ID">';
echo '<tr><td>DVD Id : '.$row->DVDID. '<br></td>' ;
echo '<td>Name Of the DVD : '.$row->NameOfTheDVD.'<br></td>';
echo '<td>Quantity : '.$row->Quantity.'</td>';
echo '<td>Price: '.$row->Price.'</td></tr> ';
$mydvd = $row->DVDID;
$name = $row->NameOfTheDVD;
$Quantity = $row -> Quantity;
$Price = $row -> Price;
First of all I retrieving the products from the database and then adding them tot h cart via Form and GET methods
echo '<input type="hidden" name="id" value="'.$mydvd.'">';
echo '<input type="hidden" name="item" value="'.$name.'">';
echo '<input type="hidden" name="Quantity" value="'.$Quantity.'">';
echo '<input type="hidden" name="Price" value="'.$Price.'">';
echo '<input type="hidden" name="Cart" value="'.$cartItemCount.'">';
//echo '<input type="submit" value="Add To Basket">';
echo ' Add To Basket<br>';
and this is how I am printing the results out
$myid = $_GET['id'];
$DVDname = $_GET['name'];
$Qty = $_GET['Quantity'];
$price = $_GET['Price'];
echo '<div class="DVD ID">';
echo '<h1> Cart </h1>';
echo '<table border="1" cellspacing="1" position="relative" left="250">';
echo "<tr><th> DVD ID<td> " . $myid . "</td></th></tr>";
echo "<tr><th> DVD Name<td> " . $DVDname . "</td></th></tr>";
echo "<tr><th> Quantity<td> " . $Qty . "</td></th></tr>";
echo "<tr><th> Price<td> " . $price . "</td></th></tr>";
echo '</div>';
Thank you for your help
I'm not gonna write the whole codes for you but instead gonna give you some advice, lecture, etc.
First, you need to know what and how to use SESSION in PHP, using session_start(), session_destroy() and $_SESSION variable.
Now, your cart should be stored on a single session variable, and it should be and will be an array of products.
The structure that I would suggest for simplicity sake is:
$_SESSION['cart'] = array(
12 => array('quantity'=>99),
15 => array('quantity'=>10)
);
On the code above, 12 and 15 are product ids serve as keys in the $_SESSION['cart']. That way, it's easier for us to find the product in the array if we need to update some info, like for example, adding or subtracting quantity.
Also, the example above is simple, to make it work, if your going to show the cart, you need to put it on a loop then query the other info from the database as it loops. You will use the ids (keys) for your search query. But, you can also just store other info in the array where the quantity is when you add an item to your cart so you don't need to query each items from the database.
To add an item to a cart, obviously you need to do a $_GET or $_POST. I'm sure you know how to do this already.
Now, if you want multiple-same items, then I suggest each items have their own form with text field for the quantity. I don't know how your website looks like or when and where "customers" can add item to a cart so algorithm, structure, etc might differ.
So if multiple different items, then you'd need the help of javascript to validate the valid values first before posting it on your php script to process. You can make to do that in the php level but I suggest you do it on the javascript level. Here, I'm saying you should have only 1 form for the product list. I recommend not doing this though.
An example for adding or updating a product in the cart. I use GET for this example.
if(isset($_GET['product_id'],$_GET['product_quantity']))
{
$pid = $_GET['product_id'];
$pq = $_GET['product_quantity'];
$_SESSION['cart'][$pid]['qty'] = $pq;
// if you have more, you can just add something like
// $_SESSION['cart'][$pid]['name'] = "Apple";
}
For deleting an item from the cart:
if(isset($_GET['product_id']))
{
$pid = $_GET['product_id'];
unset($_SESSION['cart'][$pid]);
}

How to store the result of a radio button with a database value, back into the database?

Been stuck on this bit of code for a while now. What I'm doing in 'do_assignments.php' (below) is creating a loop that outputs each question in my database and every possible answer associated with that question.
<form method="post" action="user_storeresults.php"> $query = "SELECT * FROM questions, question_choices WHERE q_topic = 'PhoneGap' AND visible = 1 AND q_type = 'Multiple' AND questions.q_id = question_choices.question_id";
$result=mysql_query($query);
while($row = mysql_fetch_array($result)){
if($row['q_id'] != #$qid){
echo "<h4><strong>" . $row['q_string'] . "</strong></h4>";
#$qid = $row['q_id'];
}
echo "<input name='".$row['choice_id']."' value='".$row['correct_choice']."' type='radio' />";
echo $row['choice_string'] . "<br/>";
}
?>
<p><input type="submit" name="submit" value="Submit"><p>
</form>
<?php
The value of each radio button contains data from a field in 'correct_choice' in my database, where there is wrong answers (0) and a correct answer (1) associated with each question.
All of this works well, but because i'm trying to submit a post from a radio button that doesn't have a specific name or value (only what it retrieves from the database), i can't quite figure out how i would be able to retrieve these values in the next page 'user_storeresults.php'...
Any help would be much appreciated. If i'm being a bit too vague then say, and ill try and clear it up as much as possible.

How to retrieve imploded array from a cell in an MySQL database through PHP

Thanks for taking the time to look at this question.
Currently, I have a piece of code that creates four checkboxes labeled as "Luxury, Brand, Retailer," and "B2B." I have looked into a number of PHP methods to create checkboxes, and I felt the implode() function was the most simple and suitable for my job. I have looked into a number of tutorials to create the implosions, however, they did not fit my criteria, as I would like the database values be reflected in the front-end. Currently in my database, the implode() works, therefore (for example), if I check "Luxury", "Brand", "Retailer", and press the "Submit" button, the three items "Luxury, Brand, Retailer" will be in that specified cell. It looks like my code works in the back-end, but these are my issues:
I am not exactly sure (despite multiple Googles) how to retrieve those values stored in the single-cell array, and have it selected as "selected" (this would "check" the box in the front-end)
Could someone kindly take a look at my code below and let me know what seems to be missing/wrong/erroneous so I could attempt the revisions? Anything would be appreciated, thank you!
<?
if (isset($_POST['formSubmit2'])){
$category = mysql_real_escape_string(implode(',',$_POST['category']));
$accountID = $_POST['accountID'];
mysql_query("UPDATE Spreadsheet SET category='$category' WHERE accountID='$accountID'");
}
$query = mysql_query("SELECT * FROM Spreadsheet LIMIT $firstRow,$rpp");
while($row = mysql_fetch_array($query)){
// Begin Checkboxes
$values = array('Luxury','Brand','Retailer','B2B');
?>
<form name ="category" method ="POST" action ="" >
<?
echo "<input type = 'hidden' name = 'accountID' value = '" . $row['accountID'] . "' >";
for($i = 0; $i < count($values); $i++){
?>
<input type="checkbox" name="category[]" value="<?php echo $values[$i]; ?>" id="rbl_<? echo $i; ?>" <? if($row['category'] == $i) echo "checked=\"checked\""; ?>/>
<? echo $values[$i] ?><br>
<? } ?>
<input type ="Submit" name ="formSubmit2" value ="Submit" />
</form>
<? } ?>
The best approach i can recommend given what you have is to, explode the values out of the db giving you a new array of all the select fields. Then use in_array to compare the list you have with this new list in the loop. then flag the checkboxs as needed.

Loop results executing twice

I creating a simple site with PHP where the users can submit blogs and other users (who are logged in) can post comments on them. I have made a link called "comments" below each blog that when clicked will show / hide all the comments relevant to the specific blog (also if the user is logged in, it will show a form field in which they can submit new comments). So basically each blog will have multiple comments. I have done two different codes for this but they both have the same problem that each comment appears twice (everything else works fine). Could anyone point out why?
mysql_select_db ("ooze");
$result = mysql_query ("select * from blog") or die(mysql_error());
$i = 1;
while($row = mysql_fetch_array($result))
{
echo "<h1>$row[title]</h1>";
echo "<p class ='second'>$row[blog_content]</p> ";
echo "<p class='meta'>Posted by .... • $row[date] • Comments<div id='something$i' style='display: none;'>";
$i++;
$a = $row["ID"];
$result2 = mysql_query ("select * from blog, blogcomment where $a=blogID") or die(mysql_error());
while($sub = mysql_fetch_array($result2))
{
echo "<p class='third' >$sub[commentdate] • $sub[username]</p><p>said:</p> <p>$sub[comment]</p>";
}
if ( isset ($_SESSION["gatekeeper"]))
{
echo '<form method="post" name="result_'.$row["ID"].'" action="postcomment.php"><input name="ID" type = "hidden" value = "'.$row["ID"].'" /><input name="comment" id="comment" type="text" style="margin-left:20px;"/><input type="submit" value="Add comment" /></form>';
}
else
{
echo '<p class="third">Signup to post a comment</p>';
}
echo "</div>";
}
mysql_close($conn);
//second version of inner loop://
if ( isset ($_SESSION["gatekeeper"]))
{
while($sub = mysql_fetch_array($result2))
{
echo "<p class='third' >$sub[commentdate] • $sub[username] said:</p> <p>$sub[comment]</p>";
}
echo '<form method="post" name="result_'.$row["ID"].'" action="postcomment.php"><input name="ID" type = "hidden" value = "'.$row["ID"].'" /><input name="comment" id="comment" type="text" style="margin-left:20px;"/><input type="submit" value="Add comment" /></form>';
}
else
{
while($sub = mysql_fetch_array($result2))
{
echo "<p class='third' >$sub[commentdate] • $sub[username] said:</p> <p>$sub[comment]</p>";
}
echo '<p class="third">Signup to post a comment</p>';
}
echo "</div>";
}
mysql_close($conn);
Your problem lies in this query from the first example.
$result2 = mysql_query ("select * from blog, blogcomment where $a=blogID")
You have already queried the blog table so there is no need to query it again. Simply changing this to
$result2 = mysql_query ("select * from blogcomment where $a=blogID")
should solve the problem.
However there are many things you need to think about.
Why are you re-inventing the wheel? There are plenty of good blog applications out there. You'd be better off using one of them.
It's not recommended to use the mysql_ family of functions any more. Go away and learn mysqli_ or better still PDO.
You should learn about separation of concerns. At the very least you should make sure your data access/business logic is separate from your display logic. MVC is very common in PHP.
You should also learn about JOINs. Even in this simple inline script you have a query within a loop which is not very efficient. You can combine your queries into one (as you've tried with the inner query). The difference is the one query should be outside your main loop.

Categories