I have a little problem, I've got this database with these fields.
Table Data{
ID
Name,
Text,
Location,
imagepath
}
And now I want the put these values into my fields, the data is just strings.
<h3><!-- Text value here --> - <!-- Name value here --></h3>
<p> <!-- Location data here --> </p>
And I also got this JS script that generates new fields, when the user clicks on a button.
$('.Next').click(function(e) {
e.preventDefault();
Slide.appendSlide('<!-- HTML DATA HERE NAME AND TEXT & LOCATION VALUES -->')});
I want the ID to be random, and I don't want the user to get the same data twice.
How should i approach this? I've tried a getdata.php but failed.
Thank you so much! Happy holidays!
Honestly i would look at saving the page id to $_session['visited']. Then each time they view a page append that to the session variable comma separated
$_session['visited'] .= ",".$page_id;
Then your sql will be.
EDITED
Ok so let make this code safe
$ph = explode(",",$_session['visited']);
foreach($ph as $check){
if (!isnumeric($check)){
echo "Not numeric, possible injection";
exit;
}
}
$parmcount=count($ph);
$inclause=implode(',',array_fill(0,$parmcount,'?'))
$sql='SELECT * FROM table WHERE ID NOT IN (%s)';
$preparesql=sprintf($sql,$inclause);
$st=$db->prepare($preparesql);
$st->execute($parms);
Or alternative just save all viewed ids as an array in the first place.
Related
I am making a page with soccer teams and leauges. Now i`m printing all Leagues that i want from the database.
League 1
League 2
League 3
etc.
As you can see each League has its own League_ID. In Database i also have a table of all teams, and each team has matched League (with League_ID). I also have a view, where i can print table of League that i want. This function in php looks like this.
public function leauge_table(){
$tables = $this->scoreTableRepository
->getScoreTable(1);
//TODO how to change this "1" static to generated
//TODO when pressing link
return $this->render('leauge_table', ['table' => $tables]);
And as you can see, when i go to this page i will always see the score table from leauge that has id=1.
And the question is how can i make that when i press for example at "League 2" i will open page but with table matching to League_ID = 2. Shall it be <button></button> or <a></a> in HTML. And how to pass there League_ID so my php back will see which table should render.
Thank you really for help.
PS
Or maybe do i have to make a seperate view for each leauge score table? And then just simply make buttons direct to these views with simple JS code. But would like to avoid it if it`s possible.
It can be a link or a button. A link with the league ID as a parameter in the URL is the simplest approach though, if you're new to the concept. e.g.
League 1
The ID would then be available in the php script via $_GET["id], once the link is clicked.
In your SoccerTeam page add a button in a form with the following :
<form action="youpage.php" method="post">
<input name="leagueId" type="hidden" value="<?php echo $leagueId;?>" >
</form>
And in order to process that information, since we passed an id, we can retrieve it with $_POST['leagueId'] and because it's a POST request it wont be visible in the url:
$leagueId = $_POST['leagueId'];
I have a form which asks for employment history, where you have applied to college etc. So for example for colleges they applied to I have one text box at first and there is a button below that calls a javascript function to add another text input right below it. When I first made this form I was doing that with a few different pieces of data then once they were submitted I would get them from $_POST and put them in arrays then add each element of the array to the corresponding table in my db. All of a sudden though, I can no longer submit my form and I get a message telling me that I have tried to get an unspecified index. However when i inspect the text inputs in my browser they are correctly named. I read that I should name them college[] so that they all go into an array, but that also did not work.... now what?
js:
var numcol = 1;
function addnewschool(){
numcol++;
var container = document.getElementById("collegecontainer");
container.appendChild(document.createTextNode(numcol));
var input = document.createElement("input");
input.type = "text";
input.name = 'applied'+numcol;
container.appendChild(input);
container.appendChild(document.createElement("br"));}
html:
<p class="text-dark mb-4">List the Colleges you have applied to:<br>
<div id="collegecontainer" name="collegecontainer">
<input type="text" name='applied1'><br>
</div>
<input type="button" id="addcollege" name="addcollege" value="Add College"
onClick="addnewschool()"><br>
</p>
php:
$applied = array();
foreach($_POST['applied'] as $value){
array_push($applied, $value);
}
Update: Ok so I changed it to another way and that didn't work so i decided to just copy an earlier version of it which was working and paste it into the correct layout. And that worked... SO now that it was fixed i continued adding to it. I added "required" to a few tags, changed some styling a bit, and changed my javascript file a bit. But now I'm having the same issues as before. All of my POST arrays only have the first value in them. What could I have added that changed this? Has anyone ever had any issues like this?
Your first additional input should have index "applied1", not "applied2"
look at:
var numcol = 1; // put this to 0
function addnewschool(){
numcol++; // or move this to the end of the function
You don't need to add a different name for each input. Just use applied[] in all input names.
To get the array in PHP, just use $_POST['applied'].
If you want to use each of them later, you could use a foreach, like
foreach ($_POST['applied'] as $value) {
// Do what you want. Retrieve the value using $value
}
Or any other method you prefer.
Name your text input field(s) applied[] and when you process the form the post value of $_POST['applied'] will be an array already filled for you with however many entries were completed.
To get the data into your table:
foreach ($_POST['applied'] as $id => $applied) {
$sql = "INSERT INTO Colleges(id, college) VALUES('$id','$applied')";
if($conn2->query($sql) === TRUE){
echo "New Record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn2->error;
}
} // end of foreach
I am pretty new to coding php and javascript but have manged to scrape my way through so far. However, I have hit a wall. I'm not 100% sure that what I'm trying to do can be done, or that I'm even attempting it in an effective way.
I have a dynamically filled table, made of rows from a SQL statement using php. On each row is a radio button, each one given a unique value based on the row number (a unique value in one of the database columns). I am attempting to program a button that enables the user to pass a selected radio button value to a separate php enabled page that will allow the user to edit the row information using the unique row value. Also, i used the confirm option, because I would also like to add an if else statement that allows the user to cancel, if the wrong row was selected (I haven't attempted that yet because I haven't been able to get the value to pass).
Page button
<input type="button" id="edit_order_button" value="Edit Order"></input>
JQuery page
$(document).ready(function(){
$("#edit_order_button").click(function(){
var selected = $("input[name ='order_edit_select']:checked").val();
var r = confirm("Confirm Order Number to edit: " + selected);
$.post("php/editOrder.php", {
selected1: selected
}, function(data,status) {
//alert("Data: " + data + "\nStatus: " + status);
window.open("php/editOrder.php","Edit Order","menubar=1,resizable=1,width=750,height=600, left=250, top=50");
});
});
});
PHP end destination
<?php
//Login to database (usually this is stored in a separate php file and included in each file where required)
require('config.php');
$selected2= isset($_POST['selected1']) ? $_POST['selected1'] : ''; // Fetching Values from URL
echo "Selected Row number is ".$selected2.".";
mysqli_close($connection); // Connection Closed.
?>
I have tried a few things but have so far been unsuccessful in getting the new window to load with the value of the radio button passed. Currently, the window loads, but the new window only displays the echo text, no variable. When I run with the alert popup, the data shows me the value of the selected row but it does not seem to be posting to the new page prior to the window.open command. Any tips would be appreciated, or if i'm approaching the problem from a wrong angle, any insights would also be great. I have also tried debugging, thinking I was missing a parentheses or semicolon but I wasn't able to find anything. Thanks
Looks to me like you can get rid of the post statement altogether and just pass the selection to the newly opened window.
$(document).ready(function(){
$("#edit_order_button").click(function(){
var selected = $("input[name ='order_edit_select']:checked").val();
// only open window if order okayed
if ( confirm("Confirm Order Number to edit: " + selected) ) {
window.open("php/editOrder.php?selected1=" + selected,"Edit Order","menubar=1,resizable=1,width=750,height=600, left=250, top=50");
}
});
});
php/editOrder.php:
$selected2 = $_GET['selected1'];
echo "Selected Row number is $selected2.";
I'm using the template from this mySQL x AJAX tutorial (http://www.9lessons.info/2010/08/dynamic-dependent-select-box-using.html) to create dependent dropdowns.
How the code should work:
Coach selects what activity group ($activity) he wants to browse from box one.
Box two the populates with a list of players($username) who are part of that activity.
It does the above, but the entries show up blank as opposed to printing the name - see screenshot attached. Below is the piece
<?php
if($_POST['activity'])
{
$activity=$_POST['activity'];
$sql=mysql_query("SELECT id AND username FROM player WHERE activity='$activity'");
while($row=mysql_fetch_array($sql))
{
$id=$row['id'];
$username=$row['username'];
$activity=$row['activity'];
echo '<option value="'.$username.'">'.$username.'</option>';
}
}
?>
I've messed around with the number of entries in the db, and the blank values change respectively (when changed to 5 people being in group, 5 blank spaces show, etc.)
It's really odd because of the fact it appears to be working, just not showing the names.
Any ideas?
Cheers.
Try fixing your query. You are ANDing the values id and username
SELECT id, username FROM player WHERE activity='$activity'
You forgot to isset your $_POST['activity'].
I'm trying to retrieve a list of users from a simple MySQL database table, e.g., called TableA, which looks something like: Username(varchar), Level(tinyint), DateCreated(datetime).
On an html page I have a search input box, say - and underneath it I have a div, say to display the results. I have it so that when I start typing a word (to look for a username), jQuery makes makes an ajax request to a php file which queries the TableA for the usernames.
The jQuery part looks like:
$("#search_bar").keyup(function()
{
var user = $(this).val();
$.post('get_user.php', user_name : user, function(data)
{
$("#result_box").html();
});
}
The php script, get_user.php, again is a simple script which looks something like
<?php
$user = $_POST['user_name'];
//connect db,
$query = mysqli_query (select Username from TableA where Username like '$user%');
//IMPORTANT PART HERE, I create a <DIV> or can be <P> and display it back
while ($row = mysqli_fetch_array($query))
{
echo "<div id="user_info" username='".$row['Username']."'>".$row['Username']."</div>
//I have the username as an attribute so I can make another .post request and get detailed user info.
}
?>
Now, previously using jQuery, every result that is being returned as a is being dumped in the result_box div ($("#result_box").html();). The problem I have with this is that if I have 3 users, say Mick, Mike and Mila and I start searching by typing 'M', the query returns all three (that's fine), however, when I click on a name, say the last one returned would be Mila, this will trigger another jQuery function which say for now just prints the name of the selected in a popup box - it however picks up the attribute of the first name, Mick, from the the first div that appeared there and not the one I clicked on. It's strange. If the search returns only a single entry then that's fine - however with multiple entries, regardless of which one I click, jQuery picks up only the first one.
I suspect its because the divs all have the same ID, and since they are being 'dynamically' created - jQuery just picks up the attribute (e.g., $("#user_info").attr('username') ) of the very first one or only one created?
Any help would be appreciated.
Thanks
You should use jQuery data()
You should create the div like :
<div class="userLink" data-username="$row['username']"></div>
And acces it from jQuery like
$('.userLink').on('click',function(e) {
var username = $(this).data('username');
}
And the attribute ID must be UNIQUE.
First off, you need to fix the issue of multiple DOM objects with the same id. Perhaps you can just use a class name. But, that probably won't fix your click issue. The click issue should be fixed by using the this reference that comes with the click event. This will tell you exactly which items was clicked on so even if there are multiple items, you can know which one was clicked on and can reference the attributes on that particular object with code like this:
$(this).attr("username");
FYI, you perhaps should use the HTML5 convention of data attributes. So, instead of an attribute of username="xxx", you would use data-username="xxx". Then, you can use:
$(this).data("username");
You can combine all these changes with delegated event handling to have a click handler like this:
Your PHP (switch to a class name and data-username attribute):
//IMPORTANT PART HERE, I create a <DIV> or can be <P> and display it back
while ($row = mysqli_fetch_array($query))
{
echo "<div class="userInfo" data-username='".$row['Username']."'>".$row['Username']."</div>
//I have the username as an attribute so I can make another .post request and get detailed user info.
}
Your delegated event handling click handler in the page:
$("#result_box").on("click", ".userInfo", function(e) {
var username = $(this).data("username");
});