i am new to PHP so please bear with me.
in my php project using mysqli queries i get results from mysql database and display them "as an html table with pagination" (e.g. 10 results per page).
my main piece of code to achieve that is the code below and works fine:
<table>
<tr>
<td> word-combinations </td>
</tr>
<?php
while ( $row=mysqli_fetch_assoc($result) ) { ?>
<td><?php echo $row['words'],$_POST['fname'];?></td>
</tr>
<?php } ?> <!-- end of while loop -->
<?php ?> <!-- the end of php tag -->
</table>
so the url of first page of the table is :
http://example.com/mytable.php?page=1
the url of second page of the table is :
http://example.com/mytable.php?page=2
and so on.
i also have created an start.php page which contains a "simple HTML form" with a "single input field" with POST action:
<?php
session_start();
echo "<form method='POST' action='http://example.com/mytable.php?page=1'>";
echo "<label for='fname'>First name:</label>";
echo "<input type='text' name='fname'> <br>";
echo "<input type='submit' value='Submit'>";
echo "</form>";
?>
My goal is to be able to get (access) the string user entered in the input field of start.php page on all pages of table and append that string to the end of all results of the table pages when is displays to the user.
so to achieve this I've used php session concept.
when user fills out the input filed and hit submit button, user is redirected to http://example.com/mytable.php?page=1 url and the $_POST['fname'] value is present and is successfully added at the end of the results of the first page of the table.
when user fills out the input filed and hit submit button, user is redirected to http://example.com/mytable.php?page=1 url and the $_POST['fname'] value is present and is successfully added at the end of the results of the first page of the table.
but when user clicks on the same page1 pagination link (actually tag) under the table, the $_POST['fname'] is not present anymore !
also when user clicks on next pages links (page2, page3, etc) $_POST['fname'] is not present anymore !
My piece of code to create "pagination links" under table are:
<?php
for ($i=1;$i<=$total_pages;$i++){
echo "<a href='mytable.php?page=".$i."'> $i </a>";
}
?>
I don't know where I am wrong.
whether I need to place some code in somewhere to make session_start(); be executed on all pages of the table?
or for a reason which i don't know, the $_POST['fname'] can not be retrieved on all pages of the table.
any help would be appreciated.
The problem is that you are not setting the $_SESSION data after starting the session_start.
Your can try this..........But the Processor will be on the same page:.
1)create File to fetch the data....."index.html".....
<form action="index2" method="post">
2)Process the form When the user hit submit....."index2".....
<?php
session_start();
if(!empty($_POST['name1'])){
$_SESSION['name1']=$_POST['name1'];
}else{
echo "There is no Data in the Variable";
}
3)Now the SESSION variable will be absent in all the script you just have to start the session in each page, but i recommend using a one script processor page
Thanks to all guy who guided me.
so according to your guidance i change the form action from POST to default GET.
then according to CBroe guidance i added $_GET['fname'] into pagination link code.
in this way seems there is no need to deploy php sessions at all.
<?php
$userinput = $_GET['fname'] ;
for ($i=1;$i<=$total_pages;$i++){
echo "<a href='mytable.php?page=".$i."&fname=$userinput'> $i</a>";
}
?>
now everything works fine as expected but i don't know whether my codes and settings are perfect!
thanks to all
Related
I´ve been having a weird problem trying to create a php page that uses html forms to update mysql data.
The idea is to create a page that retrieves all the rows from a "news" table that I have, and inserts all the data into html forms as "default" values, so I can see what is already written before changing whatever I want in this form. Each form is generated exclusively for each row of data retrieved.
For that I use the POST method and two php files, one called "updateNews.php" which retrieves data and renders forms, and another one called "newsUpdater.php" which injects the updated data.
I have two problems here. One, the form doesn´t post the new data written in the form, but instead it posts the original data posted as "default". I guess this is a problem in my form code. I guess I´m not coding "default" values right.
The second problem is pretty strange. I retrieve rows from "news" table in reverse order, but when I "submit" the form associated with a particular row, it posts the data from the first row, not the row I´m interested in.
This is my code in the first php file, which retrieves data and renders forms:
<html>
<head>
<?php
include "connectToNews.php";
mysqli_set_charset($conToNews,"utf8");
$query = mysqli_query ($conToNews, "SELECT * FROM news ORDER BY id DESC");
?>
</head>
<body>
<?php
while ($newsArray = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
echo "<form action='newsUpdater.php' method='post' enctype='multipart/form-data'>";
echo "<p>".$newsArray['id']."</p><br>";
echo "<input name='Id' type='hidden' value='".$newsArray['id']."'>";
echo "<input class='input' name='Fecha' type='text' value='".$newsArray['fecha']."'><br>";
echo "<textarea class='textarea' name='Headline' type='text'>".$newsArray['headline']."</textarea><br>";
echo "<textarea class='textarea' name='Story' type='text'>".$newsArray['story']."</textarea><br>";
echo "<input type='submit' value='Actualizar'><br><br><br>";
echo "</form>";
}
?>
</body>
</html>
So, as you can see, I render a new <Form> for each existing row. I use 2 <input> tags and 2 <textarea> tags. One of the <input> tags is hidden and has he "Id" info associated with the particular row data. In anycase, I use "echo" with this Id data to verify that is retrieving ok (and it is). I use "value" attribute to set the retrieved text as default text in this <input> tags.
In the <textarea> tags, I use the space between the opening tag and the closing tag to locate the "default" text.
At this point, everything renders ok, I get as many forms as there are rows in "news" table and and when i press submit button, it takes me to the second php file.
The second php file is the "data updater". The code is the faollowing:
<html>
<head>
<?php
$Id=$_POST['Id'];
$Fecha=$_POST['Fecha'];
$Headline=$_POST['Headline'];
$Story=$_POST['Story'];
echo "<p>".$Id."</p><br>";
echo "<p>".$Fecha."</p><br>";
echo "<p>".$Headline."</p><br>";
echo "<p>".$Story."</p><br>";
include "connectToNews.php";
mysqli_set_charset($conToNews,"utf8");
$query=mysqli_query ($conToNews, "UPDATE news SET fecha='$Fecha' headline='$Headline' story='$Story' WHERE id='$Id'");
?>
</head>
<body>
<?php
echo "<p>News updated</p><br>";
echo "<p><a href='updateNews.php'>Go back to form</a></p>";
?>
</body>
</html>
As you can see, I´m saving the posted data "$_POST['whatever']" into 4 variables, just to have an easier time writting the future mySql query.
Then, I echo this variables to check what info is really been passed. And this is where it gets weird, because te rendered texts are the ones retrieved from to the first row in my "news" table, no matter which row am I editing in the form or what I´m writting in the form.
The other problem is that, regard of getting the "ok" message related to the updating process, the data never saves to "news" table. Although, I could be wrong, because I´m really injecting the original text from row 1 into row 1, no matter of which row I was really trying to edit.
Could you read my code and tell me if you guys see any problem.
Thanks!!!
In an UPDATE query the columns being updated must be seperated by commas, this explains why your data is not being updated.
The reason you didnt know for sure that the query was failing, and why, is that you are not testing that the query actually worked or not.
It is always a VERY good idea to test the results of all MYSQLI_ calls so I would add. This will then show you an error message that would help in bebugging
$query=mysqli_query ($conToNews,
"UPDATE news SET fecha='$Fecha',
headline='$Headline',
story='$Story'
WHERE id='$Id'");
if ( $query === FALSE ) {
echo mysqli_error($conToNews);
exit;
}
You have some SQL Injection issues in this code, you should read How can I prevent SQL injection in PHP?
I'm new to web programming and I have a problem with the website I'm trying to do : I want to send some data to another .php page when the user clicks a link (there are several links, each link is the title of an newspaper article and when the user clicks one of them, it sends the id of the article because the next page has to load the content of the article). But I must not use Javascript.
Here is my previous code :
<h2> Articles </h2>
<?php
$articlesSql = "SELECT id, title FROM Article A, ApproveArticle VA WHERE A.id = VA.article AND VA.state='published';";
$articlesQuery = pg_query($connect, $articlesSql);
while($articlesResult = pg_fetch_array($articlesQuery)) {
echo "<form id=\"linkArticle\" action=\"article.php\">";
echo "<input type=\"hidden\" name=\"article\" value=\"$articlesResult[id]\"> </form>";
echo "<a href='#' onclick='document.getElementById(\"linkArticle\").submit()'> $articlesResult[title] </a> <br/>";
}
?>
Is there a way to avoid using Javascript? If so, how do I do?
Thank you for your help in this matter and have a nice day.
There is no way to submit a form without using a submit button with HTML only.
You can however make your button look like a link. This will require some CSS. Have a look at this thread for inspiration.
A better alternative that also solves your problem would be to ditch the form completely.
Simply include the article id you want to transfer to your PHP script into the URL as a parameter:
echo " $articlesResult[title] <br/>";
After the user clicked the link, you will be able to read the article id using $_GET['article'].
I am currently stuck on how to use $_GET from a hyperlink and send it to another php page for processing.
I have 2 php pages. The first page, we'll call it page1.php, gets user input (customerID) from a HTML page through a textbox and according to that id, goes into the database and finds relative information such as the Customer Name and the Address etc using logical joins.
$id = $_GET['custID']; //This is to obtain the input from the HTML page.
I have that working perfectly.
My next task is to create another php page, we'll call it page2.php, in where i am required to output only the customerID and the customerName, and from there i am required to hyperlink every record in the Customer ID row which references to page1.php and when the user clicks any of those links, it should only show information according to that customerID in a table.
So far i can make each record in the Customer ID row link to page1.php but i am unable to output any results.
<?php
while ($row = mysql_fetch_array($rs)) { ?>
<tr>
<td><?php echo $row["customerName"]?></td>
<td><?php echo "<a href='page1.php?'>{$row["custID"]}</a>"?></td>
</tr>
<?php }
Any help would be much appreciated.
Change the link to following
<?php echo ''.$row["custID"].'';?>
The $i variable is each field and is populated in the 'inp' boxes which are just input boxes and sboxes which are just select boxes. There is only one form when the page loads and it has all the criteria for a trainer to be added. The trainer name would be trainer_name1 on the first form. If they chose to hit the new button they could fill out the information for another trainer, the input box for the second form for 'name' would just be trainer_name2 and all the other fields are named respectively to what they are in the form. As new forms are built in just adds the next consecutive number onto the end of whatever the field might be named.
Here is my code:
<fieldset><legend>Trainer Request</legend></fieldset>
<tr><td><input type='button' onClick="if (show_item(1,10, 0)) { this.style.display = 'none'; }" value='New'></td></tr>
<?php
$contact_array = array('ACCEPTED TRAINING','DECLINED TRAINING','LEFT MESSAGE FOR TRAINING ACCEPTANCE',
'NEED TO CONTACT TO SEE IF INTERESTED',
'NEED PAPERWORK/TRAINING',
'NEED SIGNED CONTRACT AND PAPERWORK',
'NEED TO COMPLETE TRAINING');
for ($i = 10; $i > 0; $i=$i-1)
{
echo "<table id='hidden$i' style='display:none;'><tr>";
echo "<td>Date</td><td>Status</td></tr>";
echo "<tr><td>"; inp("date$i"); echo "</td><td>";
sbox("contact$i", $contact_array, 0, 'wide2');
echo "</td></tr>
<tr><td>Facility</td><td>";
inp("facility$i",50); echo "</td></tr>";
echo "<tr><td>Trainer Name</td><td>";
inp("trainer_name$i",35);
echo "<tr><td>Distance From</td><td>";
sbox("distance_from$i", array('1','2','5','10','15','20','25','30','40','50','60','70','80','90','100'));
echo "</td></tr>
<tr><td>Phone</td><td>";
inp("phone$i",13,'phone');
echo "</td><tr><tr><td>Email</td><td>";
inp("email$i",50);
echo "</tr><tr><td>Address 1</td><td>";
inp("addr1$i",50);
echo "</tr><tr><td>Address 2</td><td>";
inp("addr2$i",10);
echo " City ";
inp("city$i",20);
echo "</td></tr><tr><td>State</td><td>";
inp("state$i",2);
echo " Zip ";
inp("zip$i",'zip');
echo "</td></tr><tr><td>Notes</td><td>";
tbox("notes$i", 40, 3);
echo "</td></tr></table>";
}
?>
<script type='text/javascript'>
show_item(1,10,1);
</script>
As you can see down here I'm building a link which would name the link whatever the trainer name is, in this case trainer_name1 is Tim Jackson, so i've just built a hyperlink with his name.
<?php
// print_r ($_GET);
echo sendback_link($_GET['trainer_name1'], 'ACS/TrainerLookup', 'trainer_id=trainer_code&trainer_name=trainer_name');
?>
I'm confused on how to add a dynamic link like this into the for loop so as the form builds 1 - 10 each trainer_name2, trainer_name3, trainer_name4 etc etc. will have their names hyperlinked.
I'm thinking I create a new variable for the number 1-10 and append it onto the $_GET[trainer_name$].. something like that?
I hope that makes sense and any help would be greatly appreciated.
If I understood your question correctly, you are trying to add more content or replace content on a webpage that has already been generated with PHP.
I think what you are trying to do can be achieved using AJAX.
AJAX is a technique for creating dynamic webpages. AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.
In your case, the process can be described in 3 steps:
the browser making a new request to your server (using javascript)
the server processes the request and sends some information back to the browser
the browser deals with that information (again using javascript) and then updates part of the webpage
There is an example here that shows how you can dynamically change the webpage contents.
Although, if you are allowed to, I would suggest that you use a javascript framework like jQuery which simplifies the whole process (google it for download and instructions on how to use).
You can read about using AJAX with jQuery here and reading the examples that follow to better understand how you can use it.
If you are going to try and use AJAX with jQuery or simply AJAX I suggest that you try it on a test page to get a simple working example, then adding a few things and checking to see if everything works as expected. When the test page is working as expected, import the code to your page.
This is how I would do it, there may be better or easier ways to do it.
I have a database which holds the residents of each house in a certain street. I have a 'house view' php web page which can display an individual house and residents when given the house number using 'post'. I also have a 'street view' web page which gives a list of houses. What I want to know is if you can have links on the street view which will link to the house view and post the house number at the same time without setting up a form for each?
Regards
If you want to pass the data using POST instead of GET, you can do it using a combination of PHP and JavaScript, like this:
function formSubmit(house_number)
{
document.forms[0].house_number.value = house_number;
document.forms[0].submit();
}
Then in PHP you loop through the house-numbers, and create links to the JavaScript function, like this:
<form action="house.php" method="POST">
<input type="hidden" name="house_number" value="-1">
<?php
foreach ($houses as $id => name)
{
echo "$name\n";
}
?>
</form>
That way you just have one form whose hidden variable(s) get modified according to which link you click on. Then JavaScript submits the form.
I assume that each house is stored in its own table and has an 'id' field, e.g house id. So when you loop through the houses and display them, you could do something like this:
<a href="house.php?id=<?php echo $house_id;?>">
<?php echo $house_name;?>
</a>
Then in house.php, you would get the house id using $_GET['id'], validate it using is_numeric() and then display its info.
You cannot make POST HTTP Requests by some_script
Just open your house.php, find in it where you have $house = $_POST['houseVar'] and change it to:
isset($_POST['houseVar']) ? $house = $_POST['houseVar'] : $house = $_GET['houseVar']
And in the streeview.php make links like that:
Or something else. I just don't know your files and what inside it.
This is an old thread but just in case anyone does come across i think the most direct solution is to use CSS to make a traditional form look like an anchor-link.
#ben is correct you can use php and javascript to send a post with a link, but lets ask what the js does -- essentially it creates a form with style='display:none' sets an input/text line with value='something' and then submits it.
however you can skip all this by making a form. setting style='display:none' on the input/text lines (not the form itself as above) and then using CSS to make the button look like a normal link.
here is an example is i use:
in PHP Class,
public function styleButton($style,$text){
$html_str = "<form id='view_form' action='".$_SERVER['REQUEST_URI']."' method='post' >";
$html_str .= "<input style='display:none;' name='list_style' type='text' value='".$style."' >";
$html_str .= "<input id='view_button' type='submit' value='".$text."' >";
$html_str .= "</form>";
return $html_str;
}
Then in the CSS id="view_form" set "display:inline;"
and in the CSS id="view_button" set to something like: "background:none;border:none;color:#fff;cursor:pointer"
I would just use a value in the querystring to pass the required information to the next page.
We should make everything easier for everyone because you can simply combine JS to PHP
Combining PHP and JS is pretty easy.
$house_number = HOUSE_NUMBER;
echo "<script type='text/javascript'>document.forms[0].house_number.value = $house_number; document.forms[0].submit();</script>";
Or a somewhat safer way
$house_number = HOUSE_NUMBER;
echo "<script type='text/javascript'>document.forms[0].house_number.value = " . $house_number . "; document.forms[0].submit();</script>";
This post was helpful for my project hence I thought of sharing my experience as well.
The essential thing to note is that the POST request is possible only with a form.
I had a similar requirement as I was trying to render a page with ejs. I needed to render a navigation with a list of items that would essentially be hyperlinks and when user selects any one of them, the server responds with appropriate information.
so I basically created each of the navigation items as a form using a loop as follows:
<ul>
begin loop...
<li>
<form action="/" method="post">
<input type="hidden" name="country" value="India"/>
<button type="submit" name="button">India</button>
</form>
</li>
end loop.
</ul>
what it did is to create a form with hidden input with a value assigned same as the text on the button.
So the end user will see only text from the button and when clicked, will send a post request to the server.
Note that the value parameter of the input box and the Button text are exactly same and were values passed using ejs that I have not shown in this example above to keep the code simple.
here is a screen shot of the navigation...
enter image description here