I tried looking for a solution everywhere for my question and I can't seem to find it so I decided to ask it myself. Well, I'm working on a project where I'm creating multiple input fields with JavaScript, here is the code:
HTML:
<form id="buildyourform">
<legend>Registration Page</legend>
<hr>
<input type="button" value="New Registry" class="add" id="add" />
<input type="submit" value="Save" id="submitForms" />
<hr>
<script>myscript</script>
</form>
The JavaScript code inside the <script> tags above:
<script>
$(document).ready(function() {
$("#add").click(function() {
var lastField = $("#buildyourform div:last");
var intId = (lastField && lastField.length && lastField.data("idx") + 1) || 1;
var fieldWrapper = $("<div class=\"fieldwrapper\" id=\"field" + intId + "\"/>");
fieldWrapper.data("idx", intId);
var fName = $("<input type=\"text\" class=\"fieldname\" placeholder=\"Name of New Registry\" name=\"field\" />");
var removeButton = $("<input type=\"button\" class=\"remove\" value=\"x\" />");
removeButton.click(function() {
$(this).parent().remove();
});
fieldWrapper.append(fName);
fieldWrapper.append(removeButton);
$("#buildyourform").append(fieldWrapper);
});
});
</script>
The thing is that this works, it allows me to create and remove dynamically input fields, the problem is that they are all generated with the same name, so my question is: how do I add every single of them and their value in my database? This is my current php code:
<?php
require_once 'conector_superadmin.php';
$link = connect($conn);
$NameRegistryInput = $_POST['field'];
$sql = "INSERT INTO `database` (`idRegistryName`, `Name`) VALUES (NULL, '$NameRegistryInput');";
mysqli_query($link, $sql);
?>
If these were static fields I wouldn't have a problem, but the fact that they're dynamic got me stuck, so any help would be greatly appreciated.
EDIT
My new PHP code looks like this now (I also added the "[]" to the name in the input field, it now looks like this "field[]"):
require_once 'conector_superadmin.php';
$link = connect($conn);
foreach ($_POST['field'] as $NameRegistryInput) {
$sql = "INSERT INTO `database` (`idRegistryName`, `Name`) VALUES (NULL, '$NameRegistryInput');";
mysqli_query($link, $sql);
}
It still doesn't work.
PHP handles a form post containing multiple elements with the same name as an array - as long as you add [] to the name attribute
So,
var fName = $("<input type=\"text\" class=\"fieldname\" placeholder=\"Name of New Registry\" name=\"field[]\" />");
then
foreach ($_POST['field'] as $NameRegistryInput) {
$sql = "INSERT INTO `database` (`idRegistryName`, `Name`) VALUES (NULL, '$NameRegistryInput');";
mysqli_query($link, $sql);
}
Now, I see you inventing ids in javascript for each element you are adding to the page. I think you will find that you don't need that at all.
Related
This question already has an answer here:
How store multiple language textfield in mysql with php?
(1 answer)
Closed 3 years ago.
I tried to create a multi insert form where you can insert as many tiles and related languages as you want by filling in a number. The display of the Titles and language works fine, but I'm not able to get the different values and insert them into db. My aim is it that every Title with its Lang gets a unique ID in the db.
<form method="POST" action="" enctype="multipart/form-data">
<table>
<tr>
<th>Title</th>
<th>Language</th>
</tr>
</table>
<input id="count" type="number" placeholder="Number of Titles">
<input type="button" id="plus" value="+">
<input type="submit" id="save" name="save" value="Save">
<script type="text/javascript">
$('#plus').on('click', function(){
var queryString = "";
var count = $('#count').val();
var i;
for(i = 1; i <= count; i++){
$('table').append('<tr><td><input name="title" type="text" placeholder="Title" id="Title_'+i+'" autocomplete="off" class="title"></td><td><select name="lang" id="Lang_'+i+'"><option value="0">Romaji</option><option value="ja">Japanese</option><option value="en">English</option><option value="de">German</option><option value="ru">Russian</option></select></td></tr>');
}
});
$('#save').on('click', function(){
var Title = $('#Title_'+i).val();
console.log(Title);
queryString ='title='+Title+'&lang='+Lang;
jQuery.ajax({
url: "action/insert.php",
data: queryString,
type: "POST",
success:function(data){
location.reload();
},
});
});
</script>
</form>
I also tried to get the value of the inputs via Jquery and send them with Jquery Ajax to the PHP file but I only get the output "undefined" when I tried to show the values in console
The insert.php
<?php
require "../config.php";
$title= $_POST['title'];
$lang= $_POST["lang"];
$sql = "INSERT INTO MyGuests (title, lang) VALUES ('".$_POST['']."', '".$_POST['']."');";
$sql .= "INSERT INTO MyGuests (title, lang) VALUES ('".$_POST['']."', '".$_POST['']."');";
$sql .= "INSERT INTO MyGuests (title, lang) VALUES ('".$_POST['']."', '".$_POST['']."')";
...
mysqli_multi_query($conn, $sql);
?>
You need to iterate over all #Title_<something> items:
var titles = $('[id^=Title_]');
titles.each(function() {
console.log(this.val());
// do other things
});
See Wildcards in jQuery selectors
and how to iterate a result of jquery selector
Javascript
<script type="text/javascript">
$(document).ready(function(){
var input = '<input type="text" placeholder="Title" autocomplete="off" class="title">';
var select = '<select><option value="0">Romaji</option><option value="ja">Japanese</option><option value="en">English</option><option value="de">German</option><option value="ru">Russian</option></select>';
var i = 1;
$('#plus').on('click', function(){
var tr = $('tr');
var td1 = $('td');
var td2 = $('td');
td1.append($(input).attr('name', 'myguest['+i+'][title]').attr('id','Title_'+i));
td2.append($(select).attr('name', 'myguest['+i+'][lang]').attr('id','Lang_'+i));
tr.append(td1).append(td2);
$('table').append(tr);
i++;
});
});
</script>
PHP side
<?php
foreach($_POST['myguest'] as $guest) {
$sql = "INSERT INTO MyGuests (title, lang) VALUES ('".$guest['title']."', '".$_POST['lang']."');";
mysqli_query($conn, $sql);
}
don't forget to escape the values from post
I'm learning PHP and SQL and as exercise I'm working on a page that is actually something like admin panel for a website that lists movies. I'm using lampp and phpmyadmin where I have created a simple database that contains two tables, movie list and users list.
Because I'm beginner and my code is probably messy, I'm describing what I tried to achieve. There's login.php page where the only functionality is typing username and password. If info matches info from SQL table, user proceeds to adminpanel.php.
This page should load a list of movies and create a table with that data. At the end of each row I want two buttons, edit and delete. What I'm trying to achieve is to delete current row where delete button is clicked, for delete button. Edit button should show hidden form just for the row where button was clicked. This form would contain button that actually updates data in SQL table after filling form and clicking the button. (I haven't added function that shows form yet, I care about buttons much more) Form for adding movies at the end of the file works.
Here's adminpanel.php
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous">
</script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/core.js"></script>
<script type="text/javascript" src="changes.js"></script>
<script type="text/javascript" src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"></script>
<style type="text/css">
*{text-align: center;}
.skriveni_input{
display: none;
};
</style>
</head>
<?php
require_once('connection.php');
if(!isset($_POST['btnlogin'])){
exit;
}
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT usrname,password FROM usrs WHERE usrname='$username' AND password='$password' ";
$res = mysqli_query($conn,$query);
$rows = mysqli_num_rows($res);
if($rows == 1){
echo "Welcome ".$_POST['username']."<br><br>";
} else {
echo "<script>
alert('Wrong login info');
window.location.href='login.php';
</script>";
exit;
}
$query = "SELECT * FROM movies";
$result = $conn->query($query);
echo "<table align = center cellspacing = 0 border = 0;><thead><tr><th>Name</th><th>Year</th><th>Genre</th></tr></thead><tbody>";
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo '<td id="row_id" style="display:none;" value="'.$row["movie_id"].'">'.$row["movie_id"].'</td>';
echo '<td>'.$row["name"].'</td>';
echo '<td>'.$row["year"].'</td>';
echo '<td>'.$row["genre"].'</td>';
echo '<td><input type="submit" name="edit" value="edit" data-index="' . $row['movie_id'] . '" class="btnedit" id="btnedit"></input></td>';
echo '<td><input type="submit" name="delete" value="delete" class="btndlt" id="btndlt"></input></td>';
echo "</tr>";
echo "<tr>
<td><input type='text' class='hidden_input' id='hidden_name" . $row['movie_id'] . "'placeholder='hidden name'></input></td>
<td><input type='text' class='hidden_input' id='hidden_year" . $row['movie_id'] . "'placeholder='hidden year'></input></td>
<td><input type='text' class='hidden_input' id='hidden_genre" . $row['movie_id'] . "'placeholder='hidden genre'></input></td>
</tr>";
}
echo "</tbody></table>";
?>
<h3>Add movie form: </h3>
<form action="" method="POST">
<label for="movie_name">Movie name : </label>
<input type="text" name="movie_name" id="movie_name">
<br><br>
<label for="movie_year">Year: </label>
<input type="text" name="movie_year" id="movie_year">
<br><br>
<label for="movie_genre">Genre: </label>
<input type="text" name="movie_genre" id="movie_genre">
<br><br>
<input type="submit" name="submit_movie" id="submit_movie" value="Submit">
</form>
</html>
Here's my javascript file with ajax calls:
$(document).ready(function(e){
$('#submit_movie').click(function(e){
e.preventDefault();
var movie_name = $('#movie_name').val();
var movie_year = $('#movie_year').val();
var movie_genre = $('#movie_genre').val();
$.ajax({
type: 'POST',
data: {movie_name:movie_name, movie_year:movie_year, movie_genre:movie_genre},
url: "insert.php",
success: function(result){
alert('Movie ' + movie_name + ' (' + movie_year + ')' +' added successfully.');
document.location.reload();
}
})
});
$('.btnedit').click(function(e){
var id = $(this).parent().prev().prev().prev().prev().html();
alert(id);
//unfinished function
})
$('.btndlt').click(function(e){
var id = $(this).parent().prev().prev().prev().prev().prev().html();
e.preventDefault();
$.ajax({
type: 'POST',
data: {id:id},
url: 'delete_row.php',
success: function(result){
alert('Successfully deleted.');
document.location.reload();
}
})
})
});
Here's php page for adding a movie, insert.php (this one works, posting it just for more information) :
<?php
require_once('connection.php');
if($_REQUEST['movie_name']){
$name = $_REQUEST['movie_name'];
$year = $_REQUEST['movie_year'];
$genre = $_REQUEST['movie_genre'];
$sql = "INSERT INTO movies(name, year, genre) VALUES ('$name','$year','$genre')";
$query = mysqli_query($conn, $sql);
}
?>
Here's delete_row.php file for deleting entry with delete button:
<?php
require_once('connection.php');
$id = $_REQUEST['id'];
if(isset($_REQUEST['delete'])){
$sql = "DELETE FROM `movies` WHERE movie_id = $id";
$query = mysqli_query($conn, $sql);
}
?>
As you can probably see I was all over the place with php and ajax because I tried to implement multiple solutions or mix them to solve the problem.
At this stage when I click delete button I get alert message that says erasing is successful and adminpanel.php reloads with list of movies. However the movie is still there and in SQL database.
When I tried to debug delete_row.php I found out that index "id" is undefined every time even though I think I'm passing it with ajax call.
Edit
I should've said that security is not my concern right now, I do this exercise just for functionalities I described. :) Security is my next step, I am aware this code is not secure at all.
When I tried to debug delete_row.php I found out that index "id" is
undefined every time even though I think I'm passing it with ajax
call.
The reason this happens is probably because you're accessing delete_row.php directly through the browser, and because the form is not submitted (it will later through ajax) the $_REQUEST variable will always be undefined.
When debugging $_REQUEST (or $_POST) variables in the future, you should use Postman where you can actually request that php file sending your own POST arguments.
On your specific code, the query will never run because of this line:
if(isset($_REQUEST['delete']))
Which is checking for a delete variable that was never sent in the first place, hence will always resolve false
Use this code instead on delete_row.php:
<?php
require_once('connection.php');
if(isset($_REQUEST['id'])){
$id = $_REQUEST['id'];
$sql = "DELETE FROM `movies` WHERE movie_id = $id";
$query = mysqli_query($conn, $sql);
}
?>
I fetched the data from my database and echoed it. Once I go to a prisoner's profile and his status is not = detained, the button 'Add Visitor' should be automatically disabled.
Where should I put my disable() function for it to be called?
Here's my script
<script language = "javascript" type = 'text/javascript'>
function disable(){
if(document.getElementById('prisonerstatus').value == "Detained"){
document.getElementById("visitorbtn").disabled= false;}
else{
document.getElementById("visitorbtn").disabled= true;
}
};
</script>
PHP
<?php
include "connect.php";
$idd =$_GET['id'];
$result = $connect->query("SELECT * FROM prisoner
INNER JOIN offensedata ON prisoner.prisoner_id = offensedata.prisoner_id
INNER JOIN arrestdata on prisoner.prisoner_id = arrestdata.prisoner_id
INNER JOIN booking ON prisoner.prisoner_id = booking.prisoner_id
WHERE prisoner.prisoner_id = $idd") or die($connect->error);
$rows1 = $result->fetch_all(MYSQLI_ASSOC);
foreach ($rows1 as $row){
$status = $row['status'];
echo "<input type = 'hidden' value = '$status' id = 'prisonerstatus'/>";
echo "<div class='col-lg-3'>Status: $status </div>";
}
Here's my button
<input type = "button" class="call_modal" style="cursor:pointer;margin-top:1%;" value = "Add Visitor" id = 'visitorbtn'>
Please excuse my code. This is for my school project only, these codes are what have been taught to us. I will study on how to avoid SQL injections and apply it soon. Thank you in advance :)
I have this basic HTML:
<div id="main">
<form id="search_form" role="form" action="" method="post">
<div class="form-group">
<input type="text" class="form-control" name="txt_search" id="txt_search" placeholder="Enter name here" autocomplete="off" >
<p></p>
<button type="submit" id="btn_search" class="btn btn-default">Retrieve </button>
</div>
</form>
<div class="result" id="result">this element used by jquery and replaced by db</div>
</div>
I want the user to type in their search query and click the btn_search which will "hopefully" populate (without refreshing the page) the results div (eventually I want to use a graph but for the time being a table is fine).
I have this within my javascript file, specifically this part under the $(document).ready...
$('#btn_search').click(function(){
$.ajax({
url: './php/search.php',
data: "",
dataType: 'json',
success: function(rows)
{
for (var i in rows)
{
var row = rows[i];
var id = rows[0];
var vname = rows[1];
$('#result').append("<b>id: </b>"+id+"<b> name: </b>"+vname).append("<hr />");
}
}
});
});
I have checked my search.php page and it returns the values i expect from the database (about 6 columns eventually) so I am wondering why it isn't being correctly displayed on the result div.
I am a beginner trying to pick it all up, no doubt I have much to work on but I am grateful for any advice and for an answer to my problem.
EDIT: Added search.php:
<?php
if (isset($_POST["txt_search"])){
$field_search= $_POST["txt_search"];
}
else{
}
//sql
$sql = "SELECT * From tbl1 INNER JOIN tbl2 ON tbl1._tbl1.id = tbl2.tbl1_id WHERE tbl1.name like '%$field_search%'";
// Connect to the database
mysql_connect("", "", "") or die (mysql_error());
mysql_select_db("") or die (mysql_error());
// Lets build the query and execute
$result = mysql_query($sql) or die(mysql_error());
$item_num = 0;
$num_records = mysql_num_rows($result);
// Put the table data into an array
$data = array();
while ( $row = mysql_fetch_row($result) )
{
$data[] = $row;
}
echo json_encode( $data );
?>
Check this fiddle out: http://jsfiddle.net/LsB2d/2/
First, I added return: false; to your click function, so the form isn't submitted through html. Second, I added txt_search = $('#txt_search').val(); and added data: txt_search to your ajax function. This way, you're actually sending the value of the search input to the PHP file. If this doesn't work, let us know and we can go from there. (Although not seeing your PHP we can't help you with that yet)
In your PHP, you use $search = $_GET['search'];, and now $search contains your search string, which can be used to query your db or whatever you need to do.
Your question lacks the content of the result of search.php but I think your mistake is in here - you are iterating over the rows array with the var "i" but are using the rows-variable.... you mixed up iterating over array indices and iterating over array elements
for (var i in rows)
{
var row = rows[i];
var id = rows[0];
var vname = rows[1];
$('#result').append("<b>id: </b>"+id+"<b> name: </b>"+vname).append("<hr />");
}
Think it should be like this
for (var row in rows)
{
var id = row[0];
var vname = row[1];
$('#result').append("<b>id: </b>"+id+"<b> name: </b>"+vname).append("<hr />");
}
I'm making a simple list application and the items should be easy to edit (just clicking on them). It works fine, but I still have a problem at saving the changes to the database, for some reason it doesn't happen. I'm sure it's a code problem, but I haven't been able to find it.
List Page
<input type="hidden" id="hidden" id="hidden" value="">
<ul id="lista">
<?php
$IDllista = 1;
$selectitems = mysql_query ("SELECT * FROM items WHERE IDllista=".$IDllista." ORDER BY posicio ASC") or die (mysql_error());
while ($row = mysql_fetch_array($selectitems))
{
echo'<li class="item" id="';
echo $row['IDitem'];
echo '"><span class="edit" id="span-';
echo $row['IDitem'];
echo '" data="';
echo $row['Text'];
echo '">';
echo $row['Text'];
echo'</span></li>';
}
?>
</ul>
JavaScript
//Call the edit function
$(".edit").live("click", function () {
// Get the id name
var iditem = $(this).parent().attr("id");
var element = this;
var id = element.id;
//New text box with id and name according to position
var textboxs = '<input type="text" name="text' + id + '" id="text' + id + '" class="textbox" >'
//Place textbox in page to enter value
$('#'+id).html('').html(textboxs);
//Set value of hidden field
$('#hidden').val(id);
//Focus the newly created textbox
$('#text'+id).focus();
});
// Even to save the data - When user clicks out side of textbox
$('.edit').focusout(function () {
//Get the value of hidden field (Currently editing field)
var field = $('#hidden').val();
//get the value on text box (New value entred by user)
var value = $('#text'+field).val();
//Update if the value in not empty
if(value != '') {
//Post to a php file - To update at backend
//Set the data attribue with new value
$(this).html(value).attr('data', value);
$.ajax({
type: 'POST',
data: {id: iditem},
url: 'editartext.php'
});
}
// If user exits without making any changes
$(".edit").each(function () {
//set the default value
$(this).text($(this).attr('data'));
});
});
Edit Page
<?php
include_once "../connect.php";
$IDitem = $_POST['id'];
$noutext = "hola";
$actualitza = mysql_query ("UPDATE items SET Text = ".$noutext." WHERE IDitem = ".$IDitem." ");
?>
Quote problem i think. You can use query with single quote like;
"mysql_query("UPDATE items SET Text ='$noutext' WHERE IDitem ='$IDitem'");