I don't know what's going on, I selected the price in the table, and when I use it it's fine. In the <form> the $seller and $_SESSION['username'] also fine, but in the buy_item.php when I try to calculate $newAmount = ($row["amount"] - $price); and tried to see the value it seems like $price became 0$.
PAGE.PHP
The sql
$sql = "SELECT seller,price FROM stuff ";
in the table (ALL informations appears fine)
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>". $row["price"] . "</td>";
echo "<td>". $row["seller"] . "</td>";
echo " <td><form action='buy_item.php' method='post'>
<input type='hidden' id='seller' name='seller' value='".$row['seller']."'/>
<input type='hidden' id='price' name='price' value='".$row['price']."'/>
<input type='hidden' id='buyer' name='buyer' value='". $_SESSION['username'] ."'/>
<input type='submit' value='Buy'/>
</form></td>";
echo "</tr>";
BUY_ITEM.PHP
<?php
session_start();
$conn = mysqli_connect("hi", "hi", "hi", "hi");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$seller = mysqli_real_escape_string($link, $_REQUEST['seller']);
$price = mysqli_real_escape_string($link, $_REQUEST['price']);
$buyer = mysqli_real_escape_string($link, $_REQUEST['buyer']);
$sql = "SELECT username,amount FROM users WHERE username = '" .
$_SESSION['username'] . "'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
if ($row["amount"] >= $price) {
$newAmount = ($row["amount"] - $price);
echo ("$newAmount");
}
else
{
echo "Records added successfully.";
}
}
} else { echo "0 results"; }
$conn->close();
?>
the $newAmount always show up = $amount cause $price always become = 0
I'm going to take a punt and say that $price has a hidden character or the like in it.
PHP practices type juggling. Internally PHP is a typed language which casts the real type as required.
$_REQUEST provides the value of $price as a string.
When you use it in a subtraction PHP casts it from a string to an integer. Something goes wrong in the cast, it doesn't look like a number, so PHP makes it zero. Your results then occur.
Printing it out with var_dump() as #mr-glass suggested will make this clear.
Related
I have a php page that interacts with a database. I am trying to display data from the database as options for a user to select. I am trying to record which option a user selects but the variable I use ($a_game_id) to record which button is clicked gets reverted back to its original value after submitting another form. I have tried declaring the variable as global within the loop and using session variables.
$a_game_id = 9;//starting value - it changes from 9 as desired, but reverts back when another form is submitted
$sql = "SELECT * FROM nbagames WHERE date = '" .$date ."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
global $a_game_id;
// output data of each row
$results = $conn->query($sql);
$resultset = array();
while($a_row = $results->fetch_assoc()){
$resultset[] = $a_row;
}
foreach ($resultset as $row){
echo "<form action='display_lines.php' method='POST'>
<br>" . $row["away"] . " " . $row['away_spread'] . "---TOTAL AVAILABLE: " . $away_sum_array[$row['game_id']].
" <input type='submit' value='Bet " . $row['away'] ."' name='" . $row['game_id']."A' />
at " . $row["home"] . " " . $row['home_spread'] . "---TOTAL AVAILABLE: " .$home_sum_array[$row['game_id']]. "
<input type='submit' value= 'Bet " . $row['home'] ."' name='" . $row['game_id']."H' /> " . $row['date'] . "
</form>
<br>";
///HERE $a_game_id has gets the desired value
if(isset($_POST[$row['game_id'].'H'])){
$a_game_id = intval($row['game_id']);
}else if(isset($_POST[$row['game_id'].'A'])){
$a_game_id = intval($row['game_id']);
}
}
} else {
echo "<br> 0 results";
}
$sql = "SELECT * FROM nbagames WHERE date = '" .$date ."'";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
if(isset($_POST[strval($row['game_id']).'H'])){
echo '<h3>'.$row['game_id'].'<br>';
echo $row['home'].' '.$row['home_spread'].'<br>';
$team = $row['home'];
$team_spread = $row['away_spread'];
echo '<form action="display_lines.php" method="post">
<input type="text" name="new_bet_amount" placeholder="Enter Bet Amount">
<input type="submit" name="new_bet_submit" value="Submit Bet">
</form></h3>';
}
else if(isset($_POST[strval($row['game_id']).'A'])){
echo '<h3>' .$row['game_id'].'<br>';
echo $row['away'].' '.$row['away_spread'].'<br>';
$team = $row['away'];
$team_spread = $row['away_spread'];
echo '<form action="display_lines.php" method="post">
<input type="text" name="new_bet_amount" placeholder="Enter Bet Amount">
<input type="submit" name="new_bet_submit" value="Submit Bet">
</form></h3>';
}
}
if(isset($_POST['new_bet_submit'])){
//HERE $a_game_id reverts back to its original value which is undesirable
$sql3 = "INSERT INTO placed_bets (user_id, game_id, bet_amount, game_date) VALUES ('".$_SESSION['id']."', '".$a_game_id."', '".$_POST['new_bet_amount']."', '".$date."')";
echo $a_game_id.'<br>';
if ($conn->query($sql3) === TRUE) {
echo "<br><h3>BET PLACED SUCCESSFULLY</h3><br>";
} else {
echo '<h3>Error placing bet<br>';
echo $conn->error;
echo '</h3>';
}
}
Thank you for taking a look
Do you mean "when I make another request all my global variables get reset?" If so, yes, that's how they work. Each request is completely independent of others. They do not share variables or other data. All you get is what's in $_SESSION, $_GET, $_POST and $_COOKIE.
If you need to persist between requests you must put that in the session, the database, or something persistent.
If you're used to code where the process persists and the variables stick, like in client-side situations, that's a mode of thinking you need to completely abandon.
I am stuck with how to insert multiple array data of checkbox. I came across some code but I don't know how to implement them in my php code. How can I insert multiple data from checkbox in my database? Can someone help me? I really appreciate it. Thank you in advance.
html code:
<?php
include ('connect.php');
$sql2 = "SELECT * FROM owner WHERE owner_username ='".$_SESSION['username']."'";
$result2 = mysqli_query($conn,$sql2);
$row = mysqli_fetch_array($result2);
$id = $row['owner_id'];
$sql = "SELECT cat_id,name,gender,health_status,neutered,breed,color,age
FROM cat WHERE owner_fk = '$id'";
$result = $conn-> query($sql);
if ($result-> num_rows > 0) {
while ($row = $result-> fetch_assoc()) {
echo "<tr>";
echo "<td>" .$row ['name']. "</td>";
echo "<td>" .$row ['gender']. "</td>";
echo "<td>" .$row ['health_status']. "</td>";
echo "<td>" .$row ['neutered']. "</td>";
echo "<td>" .$row ['breed']. "</td>";
echo "<td>" .$row ['color']. "</td>";
echo "<td>" .$row ['age']. "</td>";
echo "<td>" ."<input type='checkbox' name= 'check[]' value=''". "
</td>";
echo "</tr>";
}
echo "</table>";
}
else{
echo "0 result";
}
$conn-> close();
?>
this is my php code:
<?php
include ('connect.php');
if(isset($_POST['submit']))
{
for($i=0;$i<count($_POST["check"]);$i++)
}
$p_id =$_GET ['sitter'];
$price = $_POST ['price'];
$pickup_date =$_POST ['pickup_date'];
$dropoff_date =$_POST ['dropoff_date'];
$numdays = $_POST ['numdays'];
$total =$_POST ['test'];
$sql2 = "INSERT INTO cat_sitter(sitter_fk,cat_fk, price, date_in,
date_out,total_day, total)VALUES ('$p_id','".$_POST["check"]
[$i]."','$cat_id','$price','$pickup_date','$dropoff_date','$numdays',
'$total')" or die ("Error inserting data into table");
if ($conn->query($sql2) === TRUE) {
echo "<script language='javascript'>alert('Succesfully Book.')
window.location.replace(\"book_page.php\");
</script>";
}else{
echo "error: " . $sql2 . "<br>" . $conn->error;
}
?>
Use implode function
In your case replace $_POST["check"] with implode(',',$_POST["check"]) then it will work fine fine hope so
Instead of implode and explode. You can use convert checkbox array into JSON and store in single field.
// Convert Array to JSON String
$checkArray = $_POST["check"];
$checkJSON = json_encode($checkArray);
After you fetch its value from database convert JSON into array.
// Convert JSON string to Array
//$checkJSON is variable fetched from database
$checkArray = json_decode($checkJSON, true);
print_r($checkArray); // Dump all data of the Array
Well i use this form of
add.php
echo " <td><form action='view_ticket.php' method='get'>
<input type='hidden' id='itemid' name='itemid' value='". $row["id"] ."'/>
<input type='submit' value='Buy' class='btn-link'/>
</form></td>";
echo "</tr>";
And i got this
view_ticket.php
<?php
session_start();
$conn = mysqli_connect("localhost", "localhost", "localhost",
"localhost");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$id = $_GET['itemid'];
$sql = "SELECT id,username FROM tickets WHERE id = '" . $id . "'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
if ($row['username'] = $_SESSION['username']) {
}
else
{
header("location:/quickshops/buyer/tickets.php");
}
}
}
?>
the only problem i guess that $id = $_GET['itemid']; gets out empty idk how
I checked the source code of add.php , the ids in hidden area are real ,true, and numbers
Output $_GET at each step to see where you loose it, for instance
echo 'About to look for id "' . htmlspecialchars($id) . '"<br>';
$result = $conn->query($sql);
echo 'Just executed SQL query<br>';
var_dump($_GET); echo '<br>';
if ($result === false) {
echo 'SQL Query Error!<br>';
var_dump($_GET); echo '<br>';
} else if ($result->num_rows > 0) {
echo $result->num_rows . ' row(s) found<br>';
var_dump($_GET); echo '<br>'; /* do something */
} else {
echo 'No rows round<br>';
var_dump($_GET); echo '<br>';
}
I am new to php and need some help please.
I'd like to create a simple php while loop.
Inside the loop I want to be able to add or subtract values.
My code seems to be doing what I want, except that i do not know what to put in the $count variable.
The aim is to have one table, and inside that table either add or subtract values of 5.
Here is my code.
<?php
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>" . $row["id"] . "</td>";
echo "<td>" . $row["userName"] . "</td>";
echo "<td>" . $row["email"] . "</td>";
echo "<td>" . $row["balance"] . "</td>";
$count = $row["id"];
?>
<td>
<form name="form" method="post" action="">
<input type="submit" name="add" value="+">
<input type="submit" name="subtract" value="-">
<?php
if (isset($_POST['add'])) {
$sql2 = "UPDATE users SET balance = balance + 5 where id = $count ";
$result2 = $conn->query($sql2);
}
if (isset($_POST['subtract'])) {
$sql2 = "UPDATE users SET balance = balance - 5 where id = $count";
$result2 = $conn->query($sql2);
}
echo $row["id"];
?>
</form>
</td>
</tr>
<?php
}
} else {
echo "0 results";
}
?>
You must send the row id back to the php script, not just the action 'add' or 'subtract'. You can identify the row by the id you want to update. The code will look something like this:
if (isset($_POST['id'], $_POST['add'])) {
$stmt = $conn->prepare('UPDATE users SET balance = balance + 5 WHERE id = ?');
if (!$stmt) {
die('Prepare failed: '.$conn->error);
}
$stmt->bindParam('d', $_POST['id']);
$result = $stmt->execute();
if (!$result) {
die('Execute failed: '.$stmt->error);
}
}
if (isset($_POST['id'], $_POST['substract'])) {
// ...
}
You add this code before the while loop and remove the existing query stuff from inside the while loop.
I've been trying think of a way to do this. I want it to where users can check off items, hit submit and it goes to the code on the next page and deletes all of the checked items from the database. Problem one is that in the post its only sending over the last checked item. Here is how I have it set up right now.
echo "<form name='fm1' METHOD ='POST' ACTION ='displaydelete.php' > ";
//Draws up the table headers
echo "";
echo "";
echo "Fund Number ";
echo "Hours ";
echo "Percentage";
echo "Delete";
echo "";
//While there are query results data is pushed into table cells
while ($row = mysql_fetch_array($queryResult2))
{
$hours = $row['hours'];
$percentage = $hours / 160 * 100;
echo "<tr>";
echo "<td>";
echo $row['funnumber'];
echo "</td>";
echo "<td>";
echo $hours;
echo "</td>";
echo "<td>";
echo $percentage ."%";
echo "</td>";
echo "<td>";
echo "<input type='checkbox' name='id' value='$row[id]'/>";
echo "</td>";
echo "</tr>";
}
//End of tabel
echo "</table>";
echo" ";
echo "";
What I would like to do is push all of the items into a variable and maybe delete them that way. I'm not really sure how you would handle multiple deletes. I'm doing my delete like this for something else if this helps any.
$query = "DELETE FROM users
WHERE ninenumber = '$ninenumber'";
$result = mysql_query($query)
or die("Query Failed: " .mysql_error());
mysql_close($conn);
In your form:
<input type='checkbox' name='id[]' value='$row[id]'/>
Then, in the file you post to:
if(is_array($_POST['id'])){
foreach($_POST['id'] as $id){
...do something to $id;
}
}
Instead of this:
echo "<input type='checkbox' name='id' value='$row[id]'/>";
You need this:
echo "<input type='checkbox' name='id[]' value='$row[id]'/>";
Note the difference. I added [] after the input name. This tells the client and server that there are multiple inputs with that name. $_POST['id'] will be an array you can loop through on the next page.
foreach ($_POST['id'] as $checkbox) {
// DELETE FROM users WHERE ninenumber = $checkbox
}
isset, is_array, and mysql_real_escape_string omitted for brevity.
In the form-generating code, make the name in the html have" []" after it:
...
echo "<input type='checkbox' name='id[]' value='$row[id]'/>";
...
Then, in the form-reading code, your post'ed id will be an array.
$id_array = isset($_POST['id']) && is_array($_POST['id']) ? $_POST['id'] : array();
foreach( $id_array as $id ) {
$query = "DELETE FROM users WHERE ninenumber = '" . mysql_real_escape_string($id) . "'";
// execute the delete query
}
Putting [] after the name of a control will turn it into an array in the superglobal that you can then iterate over to get all the values from.
You need to have the same name for all of your checkboxes, then all values are passed as array POST variable.
<input type='checkbox' name='id[]' value='$row[id]'/>
Change
name=id
to
name=id[]
this will then give you an array.