I have a form in which I enter the name, surname and function (result one select), I display them with a foreach in a table.
I want to add a button to every foreach record that will load the first form with the data from the row but I can not.
Thanks for the help!
<?php
require_once 'functii/functii.php';
$r = functia();
$options = "";
while ($row = mysqli_fetch_array($r)) {
$options = $options . "<option>$row[0]</option>";
}
?>
<form method="POST">
<table id="add"><tr><td>Nume:</td><td><input type="text" name="nume"/></td></tr>
<tr><td>Prenume:</td><td><input type="text" name="prenume"/></td></tr>
<tr><td>Functia:</td><td><select name="functia"><?php echo $options; ?></select></td></tr>
<tr><td>Activ:</td><td><input type="radio" name="activ"/></td></tr>
<tr><td></td><td><input type="submit" name="adaugare" value="Adauga"/><input type="submit" name="modificare" value="Modifica"/></td></tr></table>
</form>
<?php
if (isset($_POST['adaugare'])) {
require_once 'functii/functii.php';
$n = $_POST['nume'];
$p = $_POST['prenume'];
$f = $_POST['functia'];
$r = adaug_utilizator($n, $p, $f);
}
require_once 'functii/functii.php';
$utilizatori = grid_utilizatori();
if (count($utilizatori) == 0) {
print 'Nu sunt utilizatori adaugati';
} else {
?>
<table id="view">
<thead><tr><th colspan="4">Utilizatori adaugati</th></tr>
<tr><th>Nume</th><th>Prenume</th><th>Functia</th></tr>
</thead>
<tbody>
<?php
foreach ($utilizatori as $utilizator) {
print "<tr>";
print "<td>" . $utilizator['nume'] . "</td>";
print "<td>" . $utilizator['prenume'] . "</td>";
print "<td>" . $utilizator['denumire'] . "</td>";
print "<td><input type='submit' name='modifica' value='Modifica'></td>";
print "</tr>";
}
if (isset($_POST['modifica'])) {
$_POST['nume'] = $utilizator['nume'];
$_POST['prenume'] = $utilizator['prenume'];
$_POST['functia'] = $utilizator['denumire'];
}
?>
</tbody>
</table>
<?php
}
?>
You can execute loop as follows:
<?php
foreach($utilizatori as $index => $utilizator){
?>
<input type='submit' name='modifica<?php echo ($index+1);?>' value='Modifica' class="clickBtn"></td>
<?php
}
?>
with above loop name attribute will be as modifica1, modifica2 etc.
Now, you want to fill information based on button clicked to the form shown at your top of code, I think so.
For this, you can use jQuery:
$('.clickBtn').click(function(e){
var buttonOfRowClicked = $(this).attr('name');
var rowNumber = buttonOfRowClicked.substr(8); // It will get 1,2,3 etc table row.
$('input[name=nume]').val($(tr:nth-child(rowNumber) td:nth-child(1).val());
$('input[name=prenume]').val($(tr:nth-child(rowNumber) td:nth-child(2).val()); //similarly fill other variables.
});
I have not check the code by executing. It is overview for you to run your code. I think idea is sufficient for you for direction how should your code works.
Related
I have a database witch contain users information and (with user name from database) and I have to show all information from database for user name selected.
<select name="user[]" id="user" multiple="multiple" tabindex="1" onchange="showUser(this.value)">
<?php while($row = mysqli_fetch_array($result)){
?>
<?php
foreach($result as $row){
?>
<option value ="<?php echo $row['username']; ?>"> <?php echo $row['username'];?></option>
<?php }
?>
<?php }?>
</select>
I can only display data for one user even if I select two or more
edit :
this is my script function and display function:
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","123.php?q="+str,true);
xmlhttp.send();
}
}
</script>
123.php :
<!DOCTYPE html>
<html>
<head>
<?php
session_start();
$q = $_REQUEST["q"];
require 'conectare.php';
mysqli_select_db($conectare,"users");
$sql = "Select * from users where username = '{$q}'";
$result = mysqli_query($conectare, $sql);
echo "<table>
<tr>
<th>Id</th>
<th>Username</th>
<th>Password</th>
<th>email</th>
<th>Telefon</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['username'] . "</td>";
echo "<td>" . $row['password'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "<td>" . $row['telefon'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($conectare);
?>
</body>
</html>
enter image description here
It looks like this, I want to display 2 or more users and it only shows me one
Here's I am trying to show how you can achieve it. To display tabular data without.
I am not answering the exact solution, because i want you learn the basics. this code
is for example only.
$connection = mysql_connect('localhost', 'root', '');
//The Blank string is the password
mysql_select_db('hrmwaitrose');
$query = "SELECT * FROM employee"; //You don't need a ; like you do in SQL
$result = mysql_query($query);
echo "<table>"; // start a table tag in the HTML
while($row = mysql_fetch_array($result)){
//Creates a loop to loop through results
echo "<tr><td>" . $row['name'] . "</td><td>" . $row['age'] . "</td></tr>";
//$row['index'] the index here is a field name
}
echo "</table>";
//Close the table in HTML
mysql_close();
//Make sure to close out the database connection
You can open your browser tools, go to network and send the request, select the XHR pill and observe your request in the preview/response tab of the request. Also a good practice is to use parameterized queries. This web page is actually asking for someone to perform an SQL Injection.
The preview of your actual data will be really helpful in loading the page data to see what is the error that you are getting.
I'm totally stuck with my code.
<?php
$id = $_GET['kid'];
if (isset($_POST['mainit'])) {
if(!empty($_POST['new_kateg'])){
$jaunakategorija = $_POST['new_kateg'];
$kmst = $conn->prepare('UPDATE kategorijas SET kat_vards=:katvards WHERE kat_id=:katid');
$kmst->bindParam(':katvards', $jaunakategorija);
$kmst->bindParam(':katid', $id);
$kmst->execute();
if($kmst->execute()){
header('Location: new_kateg.php');
} else {
$message = '<p class="red">Kļūda </p>';
}
} else {
$message = '<p class="red">Lauks nedrīkst būt tukšs! </p>';
}
}
?>
<form action="kateg_edit.php" method="POST">
<p>Ievadiet jaunās kategorijas nosaukumu</p>
<?php echo $id; ?>
<input type="text" name="new_kateg" placeholder="Ievadiet nosaukumu">
<input type="submit" name="mainit" value="Mainīt!">
</form>
This is my code for updating record from database.
My URL is: localhost/....../kateg_edit.php?kid=2
when i echo $id it says it's 2. Code do its job but record is not changed.
If i hard code $id ='2';
code works and record that's ID is 2 is changed.
Im stuck why it dont change record when i get the same number from URL!
this is previous page where is button labot(edit)
<?php
$query = $conn->prepare("SELECT * FROM kategorijas");
$query->execute();
$result = $query;
echo
"<table class='table-fill'>
<tr>
<th>ID</th>
<th>Kategorijas nosaukums</th>
<th style='text-align:center;'>Darbība</th>"
;
foreach($result as $row)
{
echo "<tr>";
echo "<td>" . $row['kat_id'] . "</td>";
echo "<td>" . $row['kat_vards'] . "</td>";
echo '<td style="text-align:center;">Labot
Dzēst</td>';
}
echo "</tr>";
echo "</table>";
?>
Thanks for help...
instead of
$id = $_GET['kid'];
try this
$id = $_POST['kid'];
instead of
method="POST"
try this
method="GET"
ANYWAY THANKS FOR A HELP EVERYONE!
SOLVED BY MYSELF!
just inserted one more input field with value from GET and then use in query id which is taken from form.
">
I've got a page where I render a table of values from Mysql using PHP and HTML.
I want to delete rows checked with a checkbox upon clicking a delete button. Unfortunately, nothing happens when clicking the button and I'm at a total loss as to where to look.
Code is below (database connection has been omitted, but it works).
<body>
<?php
$delete = $_POST['checkbox'];
$query = "SELECT * FROM Cards";
$result = mysql_query($query);
echo "<table>";
echo "<tr><td>Name</td><td>Quantity</td><td>Color</td><td>Type</td></tr>";
while ($row = mysql_fetch_array($result)){
echo "<tr><td><input type='checkbox' name='checkbox[]" . $row['id'] . "]'></td>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['Quantity'] . "</td>";
echo "<td>" . $row['Color'] . "</td>";
echo "<td>" . $row['CardType'] . "</td></tr>";
}
mysql_free_result($result);
echo "</table>";
?>
</body>
<tr>
<td colspan="5" align="center"><input name="delete" type="SUBMIT" id="delete" value="delete" action="POST"></td>
</tr>
<?php
if (isset($_POST['delete'])) {
$checkbox = $_POST['checkbox'];
$count = count($checkbox);
for($i = 0; $i < $count; $i++) {
$id = (int) $checkbox[$i]; // Parse your value to integer
if ($id > 0) { // and check if it's bigger then 0
mysql_query("DELETE FROM Cards WHERE id = $id");
}
}
}
?>
<?php include "../footer.htm";?>
Try this:
<body>
<?php
$connect=mysqli_connect("Host","Username","Password","Database"); /* REPLACE NECESSARY DATA */
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
if (isset($_POST['delete'])){
$checkbox = $_POST['checkbox'];
$count = count($checkbox);
for($i=0;$i<$count;$i++){
if(!empty($checkbox[$i])){ /* CHECK IF CHECKBOX IS CLICKED OR NOT */
$id = mysqli_real_escape_string($connect,$checkbox[$i]); /* ESCAPE STRINGS */
mysqli_query($connect,"DELETE FROM Cards WHERE id = '$id'"); /* EXECUTE QUERY AND USE ' ' (apostrophe) IN YOUR VARIABLE */
} /* END OF IF NOT EMPTY CHECKBOX */
} /* END OF FOR LOOP */
} /* END OF ISSET DELETE */
$query = "SELECT * FROM Cards"; /* SELECT FROM Cards TABLE */
$result = mysqli_query($connect,$query); /* EXECUTE QUERY */
echo "<form action='' method='POST'>"; /* SUBMIT PAGE ON ITSELF */
echo "<table>";
echo "<tr><td>Name</td><td>Quantity</td><td>Color</td><td>Type</td></tr>";
while ($row = mysqli_fetch_array($result)){ /* FETCH ARRAY */
$id=mysqli_real_escape_string($connect,$row['id']);
echo "<tr><td><input type='checkbox' name='checkbox[]' value='$id'></td>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['Quantity'] . "</td>";
echo "<td>" . $row['Color'] . "</td>";
echo "<td>" . $row['CardType'] . "</td></tr>";
}
mysqli_free_result($result);
echo "</table>";
?>
<tr>
<td colspan="5" align="center"><input name="delete" type="SUBMIT" id="delete" value="delete" action="POST"></td>
</tr>
</form>
<?php include "../footer.htm";?>
</body>
I've converted your code to MySQLi from the deprecated MySQL.
And used empty() function to determine a checked checkbox.
You forgot to put a <form> function for your html.
And also forgot to use value tag for your checkbox.
I have put explanations quoted in /* */ inside the code I have provided.
Try this:
<body>
<?php
$delete = $_POST['checkbox'];
$query = "SELECT * FROM Cards";
$result = mysql_query($query);
echo "<form method=post action=''>";
echo "<table>";
echo "<tr><td>Name</td>
<td>Quantity</td>
<td>Color</td>
<td>Type</td></tr>";
while ($row = mysql_fetch_array($result)){
$content .= <<< END
<tr>
<td><input type="checkbox" name="checkbox" value="{$row['id']}"></td>
<td>{$row['Name']}</td>
<td>{$row['Quantity']}</td>
<td>{$row['Color']}</td>
<td>{$row['CardType']}</td>
</tr>
END;
}
echo $content;
mysql_free_result($result);
?>
<tr>
<td colspan="5" align="center"><input name="delete" type="SUBMIT" id="delete" value="delete"></td>
</tr>
</table></form>
</body>
<?php
if (isset($_POST['delete'])) {
$checkbox = $_POST['checkbox'];
foreach($checkbox as $id) {
$id = (int) $id;
mysql_query("DELETE FROM Cards WHERE id = $id");
}
}
?>
<?php include "../footer.htm";?>
I am creating an insert process in php but I have a problem in my code. when I refresh my page, it will also submit and insert the data.
here is my code :
<form action="/drupal/node/1" method="post">
Name: <input type="text" name="name" />
Price: <input type="text" name="price" />
Minutes: <input type="text" name="minutes" />
<input type="submit" />
</form>
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// some code
mysql_select_db("zain", $con);
if (isset($_POST['name']) && isset($_POST['price']) && isset($_POST['minutes']))
{
$val_name = $_POST['name'];
$val_price = $_POST['price'];
$val_min = $_POST['minutes'];
$max_id_sql = mysql_query("SELECT MAX(id) FROM card_category");
$data = mysql_fetch_array($max_id_sql);
if ($data[0]==0)
{
$val_id = 1;
}
else
{
$val_id = $data[0] + 1;
}
mysql_query("INSERT INTO card_category (id, name, price, minutes) VALUES ($val_id,'$val_name',$val_price,$val_min )");
$_POST['name'] == NULL;
$_POST['price'] == NULL;
$_POST['minutes'] == NULL;
}
$result = mysql_query("SELECT * FROM card_category");
echo "<table border='1'>
<tr>
<th>id</th>
<th>name</th>
<th>price</th>
<th>mins</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['price'] . "</td>";
echo "<td>" . $row['minutes'] . "</td>";
echo "</tr>";
}
echo "</table>";
if (isset($_POST['lastname']))
{
print $_POST['lastname'];
}
mysql_close($con);
?>
my question is, how can I handle when I refresh the page and it will not submit the data?
thanks in advance
When you get the POST submission:
Process the data
Return a Redirect response
Get a GET request from the browser on the URL you redirect to
Respond to that with the HTML
If the browser is refreshed, it will resubmit the GET request which your PHP won't use to modify the database.
This is the POST-REDIRECT-GET pattern. There are some more details in this blog entry (which also has example PHP code in the comments).
How to fix refresh the page do not post the value using php:
if ($_SERVER['HTTP_CACHE_CONTROL']=="")
{
// process the data
}
If you look at $_SERVER['REQUEST_METHOD'] variable, it will say 'POST' when the user submitted data and 'GET' when he did not. So:
if($_SERVER['REQUEST_METHOD']=='POST')
{
// process the data
}
By the way, your code is eminently vulnerable to SQLI attacks ...
I have a webpage that contains some data from a text file, when checked displays the checked data on a different page.
Every time a check box is checked I would like to increment the visits field to it, how do I increment the variable "$visit" every time it is visited and save it to the text file?
new.php
<html>
<body bgcolor="#99FF00">
<table border="1">
<FORM ACTION="new.php" METHOD="POST">
Enter maximum price <input type="text" name="maximumprice"/>
<p><input type="submit" value="Go" name="Go"/>
</form>
<?
$mPrice = $_POST['maximumprice'];
$file1 = "properties.txt";
$filedata = fopen ($file1, "r");
$array1 = file ($file1);
print "<form action=\"visit.php\" method=\"POST\">";
for ($counter1 = 0; $counter1 < count($array1); $counter1++)
{
$arrLine = $array1[$counter1];
$pCode = getvalue ($arrLine, 0);
$price = getvalue ($arrLine, 1);
$picture = getvalue ($arrLine, 2);
$visit = getvalue ($arrLine, 3);
if ($price < $mPrice)
{
print "<tr>";
print "<td>";
print $pCode. "<br>";
print $price. "<br>";
//print $picture. "<br>";
print $visit. "<br>";
print "<input type=\"checkbox\" name=\"box[]\" value=\"$arrLine\" />";
print "</td>";
print "<td>";
printf("<img src='$picture' width='200' height='150'>");
print "</td>";
print "</tr>";
}
}
print '<input type="submit" name="Visit" value="Visit"/>';
// Move the form outside the for loop
print "</form>";
fclose ($filedata);
function getvalue ($text, $arrNo)
{
$intoarray = explode (",", $text);
return $intoarray[$arrNo];
}
?>
</table>
</body>
</html>
this is the second page, display.php
<html>
<body bgcolor="#99FF00">
<?
foreach ($_POST['box'] as $values)
{
echo "$values <hr/>";
}
?>
</body>
</html>
There are several tutorials on how to do this on the web.
A great tutorial is the one here:
http://www.developingwebs.net/phpclass/hitcounter.php
Of course incrementing everytime a checkbox is checked will require some AJAX script.
Unless you are waiting for the post data to come through and then updating the counter.