Adding points and then show balance - php

I have something like this on my website. and I want to calculate the whole points of Sofia and show her the total balance. which is 163. but I am not getting how to add and then show her balance on my website. sorry, if it is too easy question. I am new to php.
here is the code
<form method="POST">
user name : <input type="text" name="username"><br>
Points to Add: <input type="number" name="blance" max="100"
min="1">
<br>
<input type="submit" name="submit">
</form>
<?php
if (isset($_POST['submit'])) {
$servername = "localhost";
$user = "root";
$password = "";
$database = "enter code here";
$con = mysqli_connect("$servername", "$user" , "$password" ,
"$database");
if ($con->connect_error) {
die ("connection failed" . $con->connect_error);
} else {
$username = mysqli_real_escape_string($con, $_POST['username']);
$blance = mysqli_real_escape_string($con, $_POST['blance']);
$sql = "INSERT INTO user (username, blance) VALUES ('$username',
'$blance')";
if ($con->query($sql) === TRUE) {
echo "success";
} else {
echo "error" . $sql . "<br>" . $con->error;
}
$sql6 = "SELECT * FROM user";
$result = mysqli_query($con, $sql6);
$resultcheck = mysqli_num_rows($result);
if ($resultcheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo $row['username'] . "<br>";
}
}
echo "<br>" . "<br>" . "<br>";
}}
?>
</body>

This query will return sum of points for each username, assuming your table is named test
SELECT SUM(points) AS total_points
FROM test
GROUP BY username

Related

MySQL/PHP - Checkbox array to delete multiple rows from database

i'm having some trouble passing Form checkbox array as mysql_query in order to delete multiple rows from table.
The structure is as follows:
HTML
<form action="usunogrod.php" method="POST" enctype="multipart/form-data">
<?php
$ogrodysql = "SELECT id_ogrodu, nazwa FROM ogrody";
$result = mysqli_query($con, $ogrodysql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "• " . $row["id_ogrodu"]. " " . $row["nazwa"]. "<input type='checkbox' name='removegarden[]' value=" .$row["id_ogrodu"]." <br><br>";
}
}
else {
echo "0 results";
}
?>
<br><br>
<input type="submit" value="Usuń zaznaczony ogród."/>
</form>
PHP for processing form in usunogrod.php
<?php
$db_host = 'xxxxx';
$db_user = 'xxxxx';
$db_pwd = 'xxxxx';
$con = mysqli_connect($db_host, $db_user, $db_pwd);
$database = 'xxxxx';
if (!mysqli_connect($db_host, $db_user, $db_pwd))
die("Brak połączenia z bazą danych.");
if (!mysqli_select_db($con, $database))
die("Nie można wybrać bazy danych.");
function sql_safe($s)
{
if (get_magic_quotes_gpc())
$s = stripslashes($s);
global $con;
return mysqli_real_escape_string($con, $s);
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$ogrod_id = trim(sql_safe($_POST['removegarden[]']));
if (isset($_POST['removegarden[]'])) {
mysqli_query($con, "DELETE FROM ogrody WHERE id_ogrodu='$ogrod_id'");
$msg = 'Ogród został usunięty.';
}
elseif (isset($_GET['removegarden[]']))
$msg = 'Nie udało się usunąć ogrodu.';
};
?>
MySQL table
ogrody
# id_ogrodu nazwa
1 garden1
How may i process an array from checkboxes form so that i will be able to pass a query to delete all checked elements?
EDIT:
I have been able to make it work to a moment where it only deleted one of the checked positions, or the other time just got an error saying i can't pass and array to mysqli_query.
I think this should help you:
Change this line:
echo "• " . $row["id_ogrodu"]. " " . $row["nazwa"]. "<input type='checkbox' name='removegarden[]' value=" .$row["id_ogrodu"]." <br><br>";
For this one:
echo '• ' . $row["id_ogrodu"]. ' ' . $row["nazwa"]. '<input type="checkbox" name="removegarden['.$row["id_ogrodu"].']" value="'.$row["id_ogrodu"].'" /> <br/><br/>';
Then this one:
if (isset($_POST['removegarden[]'])) {
To
if (isset($_POST['removegarden'])) {
And finally your query:
$gardens = implode(',',$_POST['removegarden']);
mysqli_query($con, "DELETE FROM ogrody WHERE id_ogrodu IN($gardens)");
You can get your data in $_POST['removegarden']. no need [] at last.
Then convert this array to ',' seperated string which can be then used in query
if (isset($_POST['removegarden'])) {
$ids_to_delete = implode(",",$_POST['removegarden']);
mysqli_query($con, "DELETE FROM ogrody WHERE id_ogrodu IN ($ids_to_delete)");
$msg = 'Ogród został usunięty.';
}

Mysql table cell doesn't change value on click

I am trying to write a php code that changes the availability of a certain apartment. Here is my code:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
$servername = "localhost";
$username = "bla";
$password = "blabla";
$dbname = "testDB";
// Create connection
$connect = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if ($connect->connect_error) {
die("Connection failed: " . $connect->connect_error);
}else{
echo "Connected successfully to the database: " . $dbname . "<br><br>";
}
$query = "SELECT * FROM test";
$result = mysqli_query($connect, $query);
$row = mysqli_fetch_array($result);
echo "id: " . $row["id"] . " // Address: " . $row["address"] . " // Rooms: " . $row["rooms"] . " // Availability: " . $row["availability"] . ".<br>";
?>
<form method ="post" action ="<?php $_PHP_SELF ?>">
<input name="update" type="submit" value="Change Availability">
</form>
<?php
if(isset($_POST["update"])) {
$avail = mysqli_query($connect,"SELECT availability FROM test WHERE id='1'");
$availCheck = mysqli_fetch_array($avail);
settype($availCheck, "int");
if($availCheck == 1){
$upAvail = mysqli_query($connect,"UPDATE test SET availability='0' WHERE id='1'");
}else{
$upAvail = mysqli_query($connect,"UPDATE test SET availability='1' WHERE id='1'");
}
}
?>
</body>
</html>
And this is the output I get:
Connected successfully to the database: testDB
id: 1 // Address: 3787 cote des neiges // Rooms: 2 // Availability: 1.
Change Availability
So here is my issue. When the availability is 1 and I press the button it changes to 0. But after that, when I press the button again, it doesn't change back to 1.
Why is that?
Thank you for the help.
You're not toggling the availability. The mysqli_fetch_array fetches the row from the test table matching the id (id=1). As a result, $availCheck will always equal 1 after you cast the non-empty array to an integer.
You can replace all that logic with a single MySQL query to toggle the value.
UPDATE test SET availability = IF(availability = 1, 0, 1) WHERE id=1
I think what you wanted to do:
$availCheck = mysqli_fetch_array($avail)['availability'];

PHP mySql Query Problems with call

I am trying to make a query call from PHP. However, I am not sure why it is not working properly. It looks like there is something wrong with what I am trying to do with the query. Everything was working correctly before I added the where clause and the bindParam. The code is executing correctly and then stops after I make the query and the binding. Can someone see if I did that correctly?
Might have something to do with post call to gender. I could not echo out the $gender.
Thanks for any insights!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Practice Work 5</title>
</head>
<body>
<form action="babynames.php" method = "post">
Year:<br>
<input type="text" name="year">
<input type="submit" value="Submit">
</form>
<select name = "gender">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</body>
</html>
<?php>
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "baby";
$year = $_POST['year'];
$gender = $_POST['gender'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Year, Name, Ranking, Gender FROM BabyNames where Year = ? and Gender = ?";
$sql -> bindParam (1, $year, PDO::PARAM_INT);
$sql -> bindParam (2, $gender, PDO::PARAM_STR);
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<br> Year: ". $row["Year"]. " ; Name: ". $row["Name"]. " ; Ranking: " . $row["Ranking"] . " ; Gender: " . $row["Gender"]. " ". "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Your variable $sql is string, not an object.
According http://php.net/manual/en/mysqli-stmt.bind-param.php
You have to prepare the statement before bind params like:
if ($stmt = $conn->prepare($sql)) {
$stmt->bind_param("is", $year, $gender);
$stmt->execute();
$result = $stmt->get_result();
$processedRows = 0;
while ($row = $result->fetch_assoc()) {
$processedRows++;
echo "<br> Year: ". $row["Year"]. " ; Name: ". $row["Name"]. " ; Ranking: " . $row["Ranking"] . " ; Gender: " . $row["Gender"]. " ". "<br>";
}
if (empty($processedRows)) { echo "0 results"; }
}
$conn->close();
Change this
$sql = "SELECT Year, Name, Ranking, Gender FROM BabyNames where Year == ? and Gender == ?";
to
$sql = "SELECT Year, Name, Ranking, Gender FROM BabyNames WHERE Year = ? AND Gender = ?";

dropdown list and search field php

:)
I'm new here and I'm very new with php.
I am trying to make a search form with:
a dropdown list with two items: category and location;
a text field;
a search button.
It should work like this:
When "category" is selected, you enter a text and it will be searched only into categories.
When "location" is selected, your term will be searched among countries, states, zip codes.
I have a table with columns: id, name, category, country, zipcode, state.
Could somebody help me to understand why it doesn't display any results?
Here is my code:
<form action='search4.php' method='POST' name='form_filter'>
<b>Search</b><br>
<select name="selectVal">
<option value="category">category</option>
<option value="location">Country, state or zipcode</option>
</select>
<input type='text' name='search' placeholder='Enter text here...' size='50'><br>
<input type='submit' value='Send'>
</form>
<?php
// database connection
$db_host = "myhost";
$db_user = "myuser";
$db_password = "mypsw";
$db_name = "myname";
//connecting to database
$db = mysql_connect($db_host, $db_user, $db_password) or die ('Error - connection failed');
mysql_select_db($db_name, $db) or die ('Database selection error');
// retrieving search value we sent using get
$research = $_GET['research'];
// check if it has been sent, then it is ok
if ( $research == 'ok' ) {
// retrieving search value we sent using post
$search = $_POST['search'];
// check if the field has been filled
if ( $search == TRUE && $search != "" ) {
// character lenght more than 3
if ( strlen($search) >= 3 ) {
$search = mysql_escape_string(stripslashes($search));
}
if(isset($_POST['value'])) {
if($_POST['value'] == 'category') {
// query to get all categories
$query = "SELECT * FROM table_name WHERE category='$search'";
}
elseif($_POST['value'] == 'location') {
// query to get all country/state/zipcode records
$query = "SELECT * FROM table_name WHERE country='$search' OR zip_code='$search' OR state='$search'";
} else {
// query to get all records
$query = "SELECT * FROM table_name";
}
$sql = mysql_query($query);
while ($row = mysql_fetch_array($query)){
$Id = $row["Id"];
$country = $row["country"];
$category = $row["category"];
$name = $row['name'];
$zip_code = $row['zip_code'];
$state = $row['state'];
echo "Name: $name<br>";
echo "Zip_code : $zip_code<br>";
echo "State : $state<br>";
echo "Country: $country<br>";
echo "Category: $category<hr>";
}
}
}
}
?>
Thank you very much for your help.
You need to understand how to use <select> with php.
if you have this form:
<form method='post'>
<select name='example'>
<option value='e1'>example1</option>
<option value='e2'>example2</option>
</select>
</form>
You need to print it like that:
echo $_POST['example'];
In case the user selcted example1, the value will be e1.
In case the user selcted example2, the value will be e2.
You are using in your script $_POST['value']. It's just dosen't exist.
Try this, instead:
HTML FORM:
<form action='search4.php' method='POST' name='form_filter'>
<b>Search</b><br>
<select name="selectVal">
<option value="category">category</option>
<option value="location">Country, state or zipcode</option>
</select>
<input type='text' name='search' placeholder='Enter text here...' size='50'><br>
<input type='submit' value='Send'>
</form>
FORM PROCESSING:
<?php
// database connection
$db_host = "myhost";
$db_user = "myuser";
$db_password = "mypsw";
$db_name = "myname";
//connecting to database
$db = mysql_connect($db_host, $db_user, $db_password) or die ('Error - connection failed');
mysql_select_db($db_name, $db) or die ('Database selection error');
/*********************************************/
/***WHY DO YOU NEED THIS RESEARCH VARIABLE?***/
/*****WHAT IS ITS PURPOSE IN THIS SCRIPT?*****/
/*********************************************/
//GET CLEAN VERSIONS OF ALL NECESSARY VARIABLES:
$search = isset($_POST['search']) ? htmlspecialchars(trim($_POST['search'])) : null;
$catLocation = isset($_POST['selectVal']) ? htmlspecialchars(trim($_POST['selectVal'])) : null;
$query = "SELECT * FROM table_name WHERE ";
//YOU INDICATED YOU'D NEED TO RUN THE SEARCH-QUERY IF THE SEARCH-TERM AND SEARCH-SCOPE ARE DEFINED IE: NOT NULL; HOWEVER IF THE SEARCH TERM IS NOT GIVEN, YOU SELECT EVERYTHING IN THAT TABLE... (BAD PRACTICE, THOUGH)
if($catLocation){
if($search){
if($catLocation == "category"){
$query .= " category LIKE '%" . $search . "%'";
}else if($catLocation == "location"){
$query .= " country LIKE '%" . $search . "%' OR zip_code LIKE '%" . $search . "%' OR state LIKE '%" . $search . "%'";
}
}else{
$query .= "1";
}
$sql = mysql_query($query);
//HERE AGAIN WAS AN ERROR... YOU PASSED mysql_fetch_array A STRING $query INSTEAD OF A RESOURCE: $sql
while ($row = mysql_fetch_array($sql)){
$Id = $row["Id"];
$country = $row["country"];
$category = $row["category"];
$name = $row['name'];
$zip_code = $row['zip_code'];
$state = $row['state'];
echo "Name: $name<br>";
echo "Zip_code : $zip_code<br>";
echo "State : $state<br>";
echo "Country: $country<br>";
echo "Category: $category<hr>";
}
}

How to add a value from a HTML form to a value in a database

I am trying to create a form to allow a user to update data from the form to the existing amount in the database. Here is what I have so far it appears to double the value. I was thinking I needed to pull the value from the database and then add the data from the form.
<?php
$username = "username";
$password = "password";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "<font face=tahoma color=#ff000><b>Connected to MySQL</b></font><br><br>";
//select a database to work with
$selected = mysql_select_db("pdogclan_points",$dbhandle)
or die("Did this change");
// Formulate Query
$_POST["filter"];
$memid = mysql_real_escape_string($_POST["Member_ID"]);
$query = sprintf("SELECT Member_ID, Bank, Reward_1, Reward_2, Reward_3 FROM Points_Rewards WHERE Member_ID = '$memid'") or die("Could Not Formulate the Query");
//execute the SQL query and return records
$result = mysql_query($query);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
//fetch tha data from the database
while ($row = mysql_fetch_array($result))
echo "<table width=750 cellspacing=2 cellpadding=2 border=2>
<tr>
<td bgcolor=#000000 width=150><font face=tahoma color=white>ID: {$row['Member_ID']}</font></td>".
"<td width=150><font face=tahoma>Bank: {$row['Bank']}</td>".
"<td width=150><font face=tahoma>Reward 1: {$row['Reward_1']}</td>".
"<td width=150><font face=tahoma>Reward 2: {$row['Reward_2']}</td> ".
"<td width=150><font face=tahoma>Reward 3: {$row['Reward_3']}</td>
</tr>
</table><br></font>";//display the results
// Formulate Update Query
$_POST["submit"];
$memid = mysql_real_escape_string($_POST["Member_ID"]);
$query = sprintf("SELECT Member_ID, Bank, Reward_1, Reward_2, Reward_3 FROM Points_Rewards WHERE Member_ID = '$memid'") or die("Could Not Formulate the Query");
while ($row = mysql_fetch_array($result))
{
$bankdb = $row['Bank'];
$reward1db = $row['Reward_1'];
$reward2db = $row['Reward_2'];
$reward3db = $row['Reward_3'];
}
echo $bank;
echo $reward1;
echo $reward2;
echo $reward3;
$memid = mysql_real_escape_string($_POST["Member_ID"]);
$bank = $_POST['bank'];
$reward1 = $_POST['reward1'];
$reward2 = $_POST['reward2'];
$reward3 = $_POST['reward3'];
$query = "UPDATE Points_Rewards Set Bank = ('$bank' + '$bankdb'), Reward_1 = ('$reward1' + '$reward1'), Reward_2 = ('$reward2' + '$reward2'), Reward_3 = ('$reward3' + '$reward3') WHERE Member_ID = '$memid'";
$result = mysql_query($query) or die(mysql_error());
if(mysql_query($query)){
echo "updated";}
else{
echo "fail";}
//close the connection
mysql_close($dbhandle);
?>
Just create a form using basic HTML, store data you fetched from database in PHP variables, then display that data using PHP tags, like this:
<form action="..." method="post" >
<?php
$memid = mysql_real_escape_string($_POST["Member_ID"]);
$query = sprintf("SELECT Member_ID, Bank, Reward_1, Reward_2, Reward_3 FROM Points_Rewards WHERE Member_ID = '$memid'") or die("Could Not Formulate the Query");
while ($row = mysql_fetch_array($result))
{
?>
<input type="text" name="r1" value="<?php echo $row['Reward_1']; ?>" /> ;
<input type="text" name="r2" value="<?php echo $row['Reward_2']; ?>" /> ;
<input type="text" name="r3" value="<?php echo $row['Reward_3']; ?>" /> ;
...
<?php
}
?>
...
</form>
You can use operators on the tables values in your SQL - it would look something like this:
$query = "UPDATE Points_Rewards Set Bank = (Bank + '$bankdb'), Reward_1 = (Reward_1 + '$reward1'), Reward_2 = (Reward_2 + '$reward2'), Reward_3 = (Reward_3 + '$reward3') WHERE Member_ID = '$memid'";
This is the structure
// if a form is submitted
if(isset($_POST['submit'])) {
$memid = $_POST["Member_ID"];
//SELECT or INSERT or UPDATE your DATABASE. Yes use PDO and prepared statements.
$query = $dbh->prepare("SELECT Member_ID, Bank, Reward_1, Reward_2, Reward_3 FROM Points_Rewards WHERE Member_ID = '$memid'")
//don't forget to bind parameters
$sth->bindParam(':memid', $memid, PDO::PARAM_INT);
$sth->execute(...);
//the loop
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
echo '';
}
//close the if statement
}
//write the form
<form method="post"/>
<input name="Member_ID" type="text" required/>
<input name="submit" type="submit" value="submit" />
</form>

Categories