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

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.';
}

Related

Adding points and then show balance

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

Comparing a value inside database with input value

My if statement doesn't recognize the textbox name ("ans"). What should I change? and where should I put it? I also want to know if my if statement is correct; I want to compare the value inside the database with the input value ("ans"). Thanks in advance.
<?php
$con = mysql_connect("localhost", "root", "avtt123");
mysql_select_db("arvintarrega",$con);
$sql = "SELECT * from identification";
$myData = mysql_query($sql,$con);
echo '<form method = "POST">';
while($iden = mysql_fetch_array($myData))
{
echo '<center>' . $iden['question_number'] . '. ' . $iden['statement'] . ' <input type = "text" name = "ans"></input></center></br>';
if($iden['correct_answer'] == $_REQUEST['ans'])
{
echo "Correct";
}
else
{
echo "Wrong";
}
}
echo '</form>';
?>
<form method = "POST">
<input type = "submit" name = "submit" value = "Submit" class="btn btn-warning">
</form>
Give the following a try which worked for me, and I'm using a mysqli_ connection and query, so change the xxx with your own credentials.
<?php
$DB_HOST = 'xxx';
$DB_USER = 'xxx';
$DB_PASS = 'xxx';
$DB_NAME = 'xxx';
$Link = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($Link->connect_errno > 0) {
die('Connection failed [' . $Link->connect_error . ']');
}
$sql = "SELECT * from identification LIMIT 1";
$myData = mysqli_query($Link, $sql);
echo '<form method = "POST">';
while($iden = mysqli_fetch_array($myData))
{
echo '<center>' . $iden['question_number'] . '. ' . $iden['statement'] . ' <input type = "text" name = "ans"></center><br/>';
if(isset($_POST['submit']))
{
if(isset($_POST['ans']) && $iden['correct_answer'] == $_POST['ans']){
echo "Correct<br><br>";
}
else
{
echo "Wrong<br><br>";
}
} // if(isset($_POST['submit'])) end brace
} // while loop end brace
echo '<input type = "submit" name = "submit" value = "Submit" class="btn btn-warning">';
echo '</form>';
?>

Make a hyperlink from SQL and PHP

I have several "providers" with website urls listed in a table. I am wondering how I would link their websites that are listed in the table to make them live urls.
<?php if($Website){
echo "<div class='providerData1'>Website: </div> <div class='providerData1 providerData2'>" . $Website . "</div><br />"; }
?>
Any ideas? Thank you. :)
Base yourself on the following: (details can be found in comments)
<?php
$DB_HOST = "xxx";
$DB_NAME = "xxx";
$DB_PASS = "xxx";
$DB_USER = "xxx";
$db = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($db->connect_errno > 0) {
die('Connection failed [' . $db->connect_error . ']');
}
if($db->connect_errno > 0){
die('Unable to connect [' . $db->connect_errno . ']');
}
// Use
// $sql = mysqli_query($db, "select * from tablename ");
// Or select particular columns
$sql = mysqli_query($db, "select link,name from tablename LIMIT 1");
// You can remove LIMIT 1 if you want to show them all
echo "Pages (found):";
echo "<hr>";
while ($row = mysqli_fetch_array($sql)){
$name= $row['name'];
$Website = $row['link'];
echo $name;
echo "<br>";
echo "<div class='providerData1'>Website: </div> <div class='providerData1 providerData2'><a href='$Website'>" . $name . "</a></div><br />";
}
echo "<br>";
?>
In place of the entire while loop, you can replace it with:
Sidenote (having a URL for the link column)
echo '<table><tr><th>Name</th><th>Page</th><th>Link</th></tr>';
while ($row = $result->fetch_assoc()){
echo '<tr><td>'.$row["name"].'</td>';
echo '<td>'.$row["link"].'</td>';
echo '<td>Link</td></tr>';
}
echo '</table>';
and display your links neatly in an HTML table.

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 display database value in form list

I've created drop down list with value name from the database. When I select the value from the drop down list, other data will appear in other textfield based on the database. The submit process was doing fine except when I check on the list. The drop down list value didn't appear in the list but other data did.
This is my adding form:
<tr><td width="116">Medicine name</td><td width="221">
<center>:
<select name="name" id="name" >
<option>--- Choose Medicine ---</option>
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("arie");
$sql = mysql_query("SELECT * FROM tabelmedicine ORDER BY name ASC ");
if(mysql_num_rows($sql) != 0){
while($row = mysql_fetch_assoc($sql)){
$option_value = $row['priceperunit'] . ',' . $row['stock'];
echo '<option value="'.$option_value.'">'.$row['name'].'</option>';
}
}
?>
</select ></center>
This is a script to display other database value in other textfield when the drop down list is selected:
<script>
var select = document.getElementById('name');
var priceperunit = document.getElementById('priceperunit');
var stock = document.getElementById('stock');
select.onchange = function()
{
var priceperunit_stock = select.value.split(',');
priceperunit.value = priceperunit_stock[0];
stock.value = priceperunit_stock[1];
}
</script>
This is my inserted data into database process:
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db = "arie";
$connect = mysql_connect($host, $user, $pass) or die ('Failed to connect! ');
mysql_select_db($db);
$name=$_POST['name'];
if ($name === "")
{
echo "Please fill all the data";
}
else
{
$query="INSERT INTO `tabelout`(`name`)
VALUES ('$name');";
$result = mysql_query($query) OR die (mysql_error());
echo "You have successfully added new medicine to the database.";
}
?>
This is my list page, where the name didn't show up:
<?php
$con=mysqli_connect("localhost","root","","arie");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM tabelout");
echo "<table border='1'>
<th>name</th>";
while($row = mysqli_fetch_array($result))
{
echo "<td><center>" . $row['name'] . "</center></td>";
}
echo "</table>";
mysqli_close($con);
?>
Make sure your database table has records, If it has records, then change the table structure, Add tr tags where required.
echo "<table border='1'>
<tr><th>name</th></tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr><td><center>" . $row['name'] . "</center></td></tr>";
}
echo "</table>";

Categories