My goal is to retrieve a dynamic SQL list of rows and edit every item in the list within the same page using POST (no multiple changes at once required). Can this be achieved within the same page? I made the script below which displays everything the way i want to, however the switch statement doesn't seem to be fit for purpouse.
I am aware this code might not be best practice (not to mention secure). Sorry for being inflexible, but i'm not allowed to use anything other then PHP/HTML
Code:
<?php
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<tr> <td class="tg">' .$row["id"]. '</td>' . "\n";
echo '<td class="tg"> <form action= "" method="post"> <input type="text" name="voornaam" value="'.$row["voornaam"].'" style="width:100px"> <input name="submit" type ="submit" value="Aanpassen"><br/><br/>' . '</td>' . "\n";
echo '<td class="tg"> <form action= "" method="post"> <input type="text" name="voornaam" value="'.$row["achternaam"].'" style="width:100px"> <input name="submit" type ="submit" value="Aanpassen"><br/><br/>' . '</td>' . "\n";
echo '<td class="tg"> <form action= "" method="post"> <input type="text" name="voornaam" value="'.$row["omschrijving"].'" style="width:500px"> <input name="submit" type ="submit" value="Aanpassen"><br/><br/>' . '</td> </tr>' . "\n";
}
} else {
echo "0 resultaten";
}
switch(!empty($_POST))
{
case !empty($_POST[$row["voornaam"]]):
// update SQL query 'firstname' here
break;
}
$conn->close();
?>
By this way you actualy see what you are editing and it's more clean.
// PDO DB conecction (secure way)
try {
$con = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $exception){ //to handle connection error
echo "Connection error: " . $exception->getMessage();
}
if isset($_POST["voornaam"]){
$stmt = $con->prepare(" QUERY");
$stmt->execute();
echo "YEAH you did it";
} else {
stmt = $con->prepare(" QUERY");
$stmt->execute();
$rows = $stmt->fetchAll();
foreach ($rows as $rs)
{
$voornaam = $rs["voornaam"]
$achternaam = $rs["achternaam"]
$omschrijving = $rs["omschrijving"]
}
}
// Just an example
echo '<form action= "" method="post"> <input type="text" name="voornaam" value="'. $voornaam .'" style="width:100px"><input name="submit" type ="submit" value="Submit"><br/><br/>';
Value is also the input so you can have only one Submit button at the end cause all other data will be overwritten by itself.
<?php
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc())
{
echo '<tr> <td class="tg">' .$row["id"]. '</td>' . "\n";
echo '<td class="tg"> <form action= "" method="post"> <input type="text" name="voornaam" value="'.$row["voornaam"].'" style="width:100px"> <input name="submit" type ="submit" value="Aanpassen"><br/><br/>' . '</td>' . "\n";
echo '<td class="tg"> <form action= "" method="post"> <input type="text" name="voornaam" value="'.$row["achternaam"].'" style="width:100px"> <input name="submit" type ="submit" value="Aanpassen"><br/><br/>' . '</td>' . "\n";
echo '<td class="tg"> <form action= "" method="post"> <input type="text" name="voornaam" value="'.$row["omschrijving"].'" style="width:500px"> <input name="submit" type ="submit" value="Aanpassen"><br/><br/>' . '</td> </tr>' . "\n";
}
}
else
{
echo "0 resultaten";
}
if( isset( $_POST[$row["voornaam"]] ) && !empty( $_POST[$row["voornaam"]] ) )
{
// update SQL query 'firstname' here
}
$conn->close();
?>
In your switch you're sending !empty($_POST) so boolean (true or false) so unique cases would be: True or False...
It's better if you change your switch to:
if(isset($_POST[$row["voornaam"]]) && !empty($_POST[$row["voornaam"]])){
// update SQL query 'firstname' here
}
Related
I use a Wordpress site, I do my search on a custom database called "operations". The search is performed on the website.
I need to get other results from the table related to this row on request, not just what I entered. And get other data related to this string. Here is the search form on the site:
<form method="post" action="https://site-name.com/wp-content/themes/theme/select_user.php">
<label for="sku">SKU:</label><br/>
<input type="text" name="sku" size="30"><br/>
<label for="barcode">Barcode:</label><br/>
<input type="text" name="barcode" size="30"><br/>
<input id="submit" type="submit" value="Search"><br/>
</form>
</fieldset>
The database has the following columns: id, date, title, size, sku, barcode, price
File Contents select_user.php:
require( __DIR__ . '/../../../wp-load.php' );
global $wpdb;
$sku = trim($_REQUEST['sku']);
$barcode = trim($_REQUEST['barcode']);
$sql_select = $wpdb->get_results(
$wpdb->prepare(
"
SELECT * FROM " . $wpdb->prefix . "operations
WHERE sku='$sku' || barcode='$barcode',
ARRAY_N
"
)
);
if ($sql_select)
{
foreach($sql_select as $row)
{
echo 'SKU: ' . $row['sku'] .'</br>';
echo 'Barcode: ' . $row['barcode'] .'</br>';
}
}
else {
echo 'No results';
}
With this code, I get the answer "no results".
I would be grateful for any help
use the post hook for wp forms not directly use .php file
add_action( 'admin_post_add_foobar', 'prefix_admin_add_foobar' );
function prefix_admin_add_foobar() {
// Handle request then generate response using echo or leaving PHP and using HTML
}
for your form use :
<form action="http://www.example.com/wp-admin/admin-post.php" method="post">
<input type="hidden" name="action" value="add_foobar">
<input type="hidden" name="data" value="foobarid">
<input type="submit" value="Submit">
</form>
I created my own shortcode, and placed everything that is necessary there. Everything works.
function custom_search_func( $atts ){
echo '<fieldset>
<form action="' . get_permalink() . '" method="POST">
<label for="sku">SKU:</label><br/>
<input type="text" name="sku" size="30"><br/>
<label for="barcode">Barcode:</label><br/>
<input type="text" name="barcode" size="30"><br/>
<label for="date">Date:</label><br/>
<input type="date" name="date" size="30"><br/>
<input type="submit" value="Search">
</form>
</fieldset>';
global $wpdb;
$sku = trim($_REQUEST['sku']);
$barcode = trim($_REQUEST['barcode']);
$date = trim($_REQUEST['date']);
$sql_select = $wpdb->get_results(
$wpdb->prepare(
"
SELECT id, date, title, size, barcode, sku, price FROM " . $wpdb->prefix . "operations
WHERE sku='$sku' || barcode='$barcode' || date='$date'
"
)
);
if ($sql_select)
{
echo '<table border="1" width="100%" cellpadding="5">';
echo '<tr><th>ID</th>';
echo '<th>Title</th>';
echo '<th>Size</th>';
echo '<th>SKU</th>';
echo '<th>Barcode</th>';
echo '<th>Price</th>';
echo '<th>Date</th></tr>';
foreach ( $sql_select as $id) {
echo '<tr>';
echo '<td>';
echo $id->id;
echo '</td>';
echo '<td>';
echo $id->title;
echo '</td>';
echo '<td>';
echo $id->size;
echo '</td>';
echo '<td>';
echo $id->sku;
echo '</td>';
echo '<td>';
echo $id->barcode;
echo '</td>';
echo '<td>';
echo $id->price;
echo '</td>';
echo '<td>';
echo $id->date;
echo '</td>';
echo '</tr>';
}
echo '</table>';
}
else {
echo 'No results';
}
}
add_shortcode( 'customsearch', 'custom_search_func' );
Use the [customsearch] shortcode to output this anywhere on the page
I am having a table with <input type="text" name="' . $r['0'] . '" value="' . $r['0'] . '"
populated from data that i fetch from database like this:
echo '<form id="actions" name="nonValidMainForm" method="post"><table border="2" width="100%">';
echo "<tr><td><b>Index</b></td><td><b>Email </b></td> <td><b>Date</b></td> <td><b>Name</b></td> <td><b>Surname</b></td> <td><b>Telephone Number</b></td> <td><b>Street Adress</b></td><br/>";
while($r = mysql_fetch_array($result)) {
$my[] = $r['0'];
echo '<tr>';
echo '<td>'.$roww++.'</td>';
echo '<td>
<input size="50%" type="text" name="' . $r['0'] . '" value="'.$r['0'].'">
<input type="submit" name="unsubscribe" value="Unsubscribe">
</td>';
echo '<td>'.$r['1'].'</td>';
echo '<td>'.$r['2'].'</td>';
echo '<td>'.$r['3'].'</td>';
echo '<td>'.$r['4'].'</td>';
echo '<td>'.$r['5'].'</td>';
echo '</tr>';
}
echo "<pre>";
print_r($my);
echo "</pre>";
if(isset($_POST['unsubscribe'])){
foreach($my as $key=>$value){
$email = $value;
}
echo "<script>console.log( 'Value is: " . $email . "' );</script>";
}
echo '<button style="position:fixed;bottom:5;left:5;">Change</button>';
echo '</table></form>';
The table looks like this:
I have tried this:
if(isset($_POST['unsubscribe'])){
$email = $POST['email'];
echo "<script>console.log( 'Value is: " . $email . "' );</script>";
}
But the value is empty
So each time i press unsubscribe button the corresponding email to be deleted. How is this possible?
Your form has many elements with the same name. How can the browser determine which element's value to send to the server when the form is posted? Generally the last one takes precedence, but I suspect that behavior may be undefined and browser-specific.
If each individual table row needs to be a separately post-able form, then each row needs its own form:
echo '<td>
<form method="POST" action="somePage.php">
<input size="50%" type="text" name="email" value="'.$r['0'].'">
<input type="submit" name="unsubscribe" value="Unsubscribe">
</form>
</td>';
That way when the browser posts the form to the server, it knows specifically which email and unsubscribe elements to use. Since there's only one of each for that form.
You have to wrap your inputs in a <form> tag.
echo '<form>';
while($r = mysql_fetch_array($result)) {
echo '<tr>';
echo '<td>'.$roww++.'</td>';
echo '<td>
<input size="50%" type="text" name="email" value="'.$r['0'].'">
<input type="submit" name="unsubscribe" value="Unsubscribe">
</td>';
echo '<td>'.$r['1'].'</td>';
echo '<td>'.$r['2'].'</td>';
echo '<td>'.$r['3'].'</td>';
echo '<td>'.$r['4'].'</td>';
echo '<td>'.$r['5'].'</td>';
echo '</tr>';
}
echo '</form>';
if(isset($_POST['unsubscribe'])){
$email = $POST['email'];
echo "<script>console.log( 'Value is: " . $email . "' );</script>";
}
Based on your code above it looks like it's a syntax error. Try the update below
if(isset($_POST['unsubscribe'])){
$email = $_POST['email'];
echo "<script>console.log( 'Value is: " . $email . "' ); </script>";
}
I have a MySQL DB table as users.
I am populating a html table using php and ajax.(working fine)
but I want to search for specific data, written some code also, but not getting what is my mistake.
my index.html
<body>
<div class="container">
<h3>Product List</h3>
<div id="users-grid">
</div>
</div>
</body>
<script>
function getresult(url) {
$.ajax({
url: url,
type: "POST",
success: function(data){ $("#users-grid").html(data);}
});
}
getresult("getresult.php");
</script>
my getresult.php(used to populate the #users-grid )
<?php
include 'database.php';
$pdo = Database::connect();
$product = "";
$queryCondition = "";
?>
<form name="frmSearch" method="post" action="index.php">
<div class="search-box">
<p>
<input type="text" placeholder="Product Name" name="product" value="<?php echo $product; ?>" />
<input type="button" name="go" class="btnSearch" value="Search" onclick="getresult('getresult.php')">
<input type="reset" class="btnSearch" value="Reset" onclick="window.location='index.php'"></p>
</div>
<table class="table table-striped table-bordered" class="tablesorter">
<thead>
<tr>
<th>Date</th>
<th>Product</th>
<th>Quantity</th>
<th>Gross Price</th>
<th>Profit</th>
</tr>
</thead>
<tbody>
<?php
$queryCondition = "";
if(!empty($_POST["product"])) {
$queryCondition .= " WHERE product LIKE '" . $_POST["product"] . "%'";
}
$orderby = " ORDER BY id desc";
$sql = "SELECT * FROM users " . $queryCondition . $orderby;
foreach ($pdo->query($sql) as $row) {
echo '<tr>';
echo '<td>'. $row['date'] . '</td>';
echo '<td>'. $row['product'] . '</td>';
echo '<td>'. $row['quantity'] . '</td>';
echo '<td>'. $row['grossprice'] . '</td>';
echo '<td>'. $row['profit'] . '</td>';
echo '</tr>';
}
Database::disconnect();
?>
</tbody>
</table>
</form>
Thank you
this code will search anything start with your search query
$queryCondition .= " WHERE product LIKE '" . $_POST["product"] . "%'";
i think you should change it to this for haveing full search
$queryCondition .= " WHERE product LIKE '%" . $_POST["product"] . "%'";
when you put onclick on your submit button it will fire only when user click on the button but when user put something on text and press enter it will submit your form so you have to change your code to this
<form name="frmSearch" method="post" onsubmit="return getresult('getresult.php')">
<div class="search-box">
<input type="text" placeholder="Product Name" name="product" value="<?php if(isset($_POST["product"])) echo $_POST["product"]; ?>" />
<input type="button" name="go" class="btnSearch" value="Search">
<input type="reset" class="btnSearch" value="Reset" onclick="window.location='index.php'">
</div>
</form>
i changed input value to show your search query. and the return part is for stop page reload
and to send POST data you have to change your ajax code to this
function getresult(url) {
$.ajax({
url: url,
type: "POST",
data: {product: $('input[name=product]').val()},
success: function(data){ $("#users-grid").html(data);}
});
return false
}
Here is my code:
while($row = mysqli_fetch_array($result))
{
$id = $row['id'];
$description = $row['description'];
$picturepath = $row['picturepath'];
$name = $row['name'];
$price = $row['price'];
$keywords = $row['keywords'];
$dynamiclist = '<table align="center" width="60%" border="0" cellspacing="5" cellpadding="8">
<tr height="20"></tr>
<tr>
<td width="70%" valign="top" align="left"> <br />' . $name . ' <br /><br />$' . $price . '<br /><br />
<form id="form1" name="form1" method="post" action="cart.php">
<input type="hidden" name="pid" id="pid" value=" ' . $name . ' - $' . $price . ' - "checkbox"/>';
echo $dynamiclist;
foreach(explode(',', $keywords) as $keyword) {
$keyword = trim($keyword);
echo "<input type='checkbox' name='checkbox' value='$keyword'>$keyword <br /><br />";
}
echo '<input type="submit" name="button" id="button" value="Add to Order"/> </form> </td></tr></table>';
}
mysqli_close($con); //close the db connection
The code pulls in an item using the items id, and then creates checkboxes and keywords for that item. A user is to click on the checkbox options they want and then submit the form which sends the information to the shopping cart. The problem is that when the form is submitted, only the name and price of the item is sent over, but not the checkbox options that were clicked. Can you help me identify why? Side note. In my database I have a column "keywords" where multiple keywords are stored. // medium, well, rare, milk, apple juice, fries. Also, on the cart.php the I have:
if(isset($_POST['pid'])){
$pid = $_POST['pid'];
which posts the data from the script using the checkboxes. I'm just stuck and can't get any further.
You should have different name for your checkbox:
while($row = mysqli_fetch_array($result))
{
$id = $row['id'];
$description = $row['description'];
$picturepath = $row['picturepath'];
$name = $row['name'];
$price = $row['price'];
$keywords = $row['keywords'];
$dynamiclist = '<table align="center" width="60%" border="0" cellspacing="5" cellpadding="8">
<tr height="20"></tr>
<tr>
<td width="70%" valign="top" align="left"> <br />' . $name . ' <br /><br />$' . $price . '<br /><br />
<form id="form1" name="form1" method="post" action="cart.php">
<input type="hidden" name="pid" id="pid" value=" ' . $name . ' - $' . $price . ' - "checkbox"/>';
echo $dynamiclist;
$i=0;
foreach(explode(',', $keywords) as $keyword) {
$keyword = trim($keyword);
$chkname = "checkbox{$i}";
$i = $i+1;
echo "<input type='checkbox' name='$chkname' value='$keyword'>$keyword <br /><br />";
}
echo '<input type="submit" name="button" id="button" value="Add to Order"/> </form> </td></tr></table>';
}
mysqli_close($con); //close the db connection
You need to get checkbox data in the cart.php like this:
if($_REQUEST['checkbox0']) echo $_REQUEST['checkbox0'];
if($_REQUEST['checkbox1']) echo $_REQUEST['checkbox1'];
//so on foreach checkbox
Your checkboxes need to have different names, otherwise the values are overwritten:
<input type="checkbox" name="keyword1" value="keyword1">Keyword1
<input type="checkbox" name="keyword2" value="keyword2">Keyword2
<input type="checkbox" name="keyword3" value="keyword3">Keyword3
You then access them in PHP like so:
if ( isset($_GET['keyword1']) ) {
}
if ( isset($_GET['keyword2']) ) {
}
if ( isset($_GET['keyword3']) ) {
}
A more logical way to manage the data is to pass the checkbox values as an array:
<input type="checkbox" name="keyword[]" value="keyword1">Keyword1
<input type="checkbox" name="keyword[]" value="keyword2">Keyword2
<input type="checkbox" name="keyword[]" value="keyword3">Keyword3
It then becomes much easier to work with the data in PHP;
if ( isset($_GET['keyword']) && is_array($_GET['keyword']) ) {
foreach ( $_GET['keyword'] as $v ) {
}
}
I am trying to get the values of a dynamically created set of checkboxes in PHP but apparently I couldn't get it. The source codes are below.
The "managestaff.php" page would allow searching for staff via their names and throws out a list of names with checkboxes for the admin to check them and click on a "delete" button at the bottom to delete the staff whom are being checked.
The deletion would be done on "deletestaff.php" as the "delete" button on "managestaff.php" simply forwards these values to "deletestaff.php" to do deletion work of the staff.
"managestaff.php" page codes:
<b><h3>Manage Staff</h3></b><br/>
<form action="managestaff.php" method="POST">
<input name="form" type="hidden" id="form" value="true">
<table width=300>
<tr>
<td width=112>Staff Name: </td>
<td width=188><input type="text" class="textfield" name="sname" /><br/></td>
</tr>
</table><br/>
<input type="submit" value="submit" />
</form>
<?php
if (isset($_POST['form']) && (isset($_POST['sname'])) && $_POST['form'] == 'true') {
$space = ' ';
$staffname = mysql_real_escape_string($_POST['sname']);
$query = 'SELECT * from staff where staffname like \'%' . $staffname . '%\'';
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result) != 0) {
echo '<br><br>';
echo '<table>';
echo '<tr><th>Staff ID' . $space . '</th><th>Staff Name' . $space . '</th></tr>';
echo '<form action="deletestaff.php" method="POST">';
echo '<input name="delstaffform" type="hidden">';
while ($row = mysql_fetch_array($result)) {
echo '<tr>';
echo '<td>' . $row['staffid'] . '</td><td>' . $row['staffname'] . '</td>';
// :Begin - dynamic checkbox generation for deleting staff
echo '<td>';
echo '<input type="checkbox" name="delstaff" value="' . $row['staffid'] . '" />';
echo '</td>';
// :End
echo '</tr>';
}
echo '<tr align="right"><td colspan="3"><input type="submit" value="delete"/></td></tr>';
echo '</form>';
echo '</table>';
}
}
?>
"deletestaff.php" page codes:
<?php
print_r('POST: ' . $_POST);
echo '<br>';
if (isset($_POST['delstaffform']) && isset($HTTP_POST_VARS)) {
echo 'Submission of delstaffform FOUND !';
echo 'Staff to delete' . $HTTP_POST_VARS['delstaff'];
}
else{
echo 'Submission of delstaffform NOT FOUND !';
}
?>
The "deletestaff.php" doesn't do delete for now as it's a test page.
The current output I get is "Submission of delstaffform NOT FOUND !".
Thanks for the solutions.
Try this:
<input type="checkbox" name="delstaff[]" value="' . $row['staffid'] . '"/>';
print_r your $_POST and you'll see it sticks your submissions nicely into an array for you.
<?php
if (isset($_POST['delstaff']) && is_array($_POST['delstaff'])) {
echo 'Submission of delstaffform FOUND !';
$array = $_POST["delstaff"];
foreach($array as $value){
echo "<br>Value: ".$value."<br>";
}
} else {
echo 'Submission of delstaffform NOT FOUND !';
}
?>
Found the answer on my own but nevertheless you are helpful :D . Thanks a lot.