I'm building a website where users can view eachother's profile. When a person clicks on another user's name they are directed to their profile page. The URL would look as follows:
http://www.mywebsite.com/profile.php?id=21
In ASP.NET this was trivial to do since I could call controls from C# and edit their text after I've retrieved user information from the database, but i can't seem to find a way how to do the same thing using PHP and jquery. This is how I would like the procedure to go:
User A clicks name of User B
User A is redirected to profile page of User B
Server retrieves information about User B and sends it to jquery
Page is loaded and the HTML fields are filled with the variable contents which were just sent from the server
I guess what i'm finding most hard is how to pass information from php to jquery within the same page.
In PHP you can mix server side code with HTML. You don't really need to involve jQuery to fill the HTML fields (unless you're using AJAX).
You would execute your mysql query and then use that result set to populate the page like so:
This isn't the best code (from w3Schools) but it illustrates the point:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM Persons");
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
Notice the echo statements. This will output the value from the database into your HTML page.
As I said this is not an example of good code but you can easily change this to add the parameter from the query string (remember to escape the string) to the select statement and output into a profile page.
Related
I have a tests.php web page that successfully creates and populates a html table using data from a mysql database on an online server. Next I want to make the web page interactive by adding html select to limit the number of rows the sql query returns. I've added the html select code and amened my sql query to use a variable for LIMIT. The issue I have is how to make the query run when the select dropdown is changed. I'm assuming some kind of page refresh needs to be called but unsure how to go about this. For example would I need to enclose the html as a from and have a submit button to make this work? This IS NOT what I want, ideally the user presses html select and then the page refreshes or re runs the sql database query.
Please be kind this is the first php code I've written.
My select code
<select name="limit" id="limit">
<option value="10">10</option>
<option value="25">25</option>
<option value="50">50</option>
<option value="100">100</option>
</select>
The php code
</body>
</html>
<?php
$limit = 10;
if(isset($_POST["limit"])) $limit = $_POST["limit"];
$con=mysqli_connect("localhost","user","password","database");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM TableName WHERE Region='Home' ORDER BY TeamName ASC LIMIT $limit");
echo "<table class='sample' style='width:50%'>
<tr>
<th>Team Name</th>
<th># Players</th>
<th>Venue</th>
<th>Date</th>
<th>Score</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['TeamName'] . "</td>";
echo "<td>" . $row['NumPlayers'] . "</td>";
echo "<td>" . $row['Venue'] . "</td>";
echo "<td>" . $row['Date'] . "</td>";
echo "<td>" . $row['Score'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
UPDATE
I think I may have a simpler solution using javascipt although it's not working correctly.
Using javascript function:
window.location.reload(true);
and change my html select
<select onchange="refresh.call()">
However when the page re loads it's using the typed $limit value
$limit =10;
instead of the select value.
The page refresh is working but is there a way to inject the html select value somehow?
Sanitizing Input
First off, you need to sanitize your limit variable as it's insecure to allow input directly into the SQL.
see:
What's the best method for sanitizing user input with PHP? AND
https://www.shift8web.ca/2015/06/securing-your-mysql-queries-from-sql-injection-in-php/
Single Page App Approach
Secondly, you need to decide if you will re-write the html notes using javascript ( in which case you will make an ajax/jquery request). Then you will rewrite the html using some framework or javascript ( innerHTML = '') or editing the DOM tree.
See:
Ajax tutorial for post and get
AND
https://stackoverflow.com/a/19527642/1688441
Reloading the page
If you decide you don't want to use javascript to rewrite the Dom tree, then the only solution is to refresh the entire page using either a GET or POST with the limit parameter.
So you will use an onChange listener, and call the page again with a limit parameter.
See: Reload page after user clicks on combobox (with some rules)
//DB CONNECTION
$sql = "SELECT `city`,`country` from infotab";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
echo $row["city"].$row["country"]"<a href='order.php'>order</a>"; }
Table output:
This code will select data. Additionally, there is reference to order.php on every line. When the user clicks on reference( <a href> clause), it opens order.php and there I need to know which row the user selected to work with these data.
Change the code to:
while ($row = $result->fetch_assoc()) {
echo $row["city"] . $row["country"] . "<a href='order.php?city=" . $row["city"] . "&country=" . $row["country"] . "'>order</a>";
}
In order.php you can then access these values by using the $_GET["city"] and $_GET["country"] variables which contain the values from your <a href> link on the previous page. For example, running echo $_GET["city"]; will output the city name.
Edit: As #Rizier123 pointed out, using a unique ID might be more prone to errors in case your database contains more than one entry for the same city or country. You should consider introducing an ID in your table structure and then using that in the link to order.php.
I have two PHP pages. On page1 a temporary table is created and filled with data from a mysql database. I am trying to store this table into a $_SESSION variable so that I can put the table onto page2.
Right now this has been my approach:
This is the code on page1:
//Select data from database
$result = mysqli_query($mysqli,"SELECT * FROM table");
//Set array
$array = array();
while($row = mysql_fetch_assoc($result)){
// add each row returned into an array
$array[] = $row;
}
//store array into session variable
$_SESSION['fase1result'] = $array;
This is the code on page2:
$table = $_SESSION['fase1result'];
echo "<table border='1'>
<tr>
<th>ProductID</th>
<th>ProductName</th>
<th>Fase1</th>
</tr>";
foreach ($table as $row)
{
echo "<tr>";
echo "<td>" . $row['ProductID'] . "</td>";
echo "<td>" . $row['ProductName'] . "</td>";
echo "<td>" . $row['Fase1'] . "</td>";
echo "</tr>";
}
echo "</table>";
Unfortunately, up until now these scripts return me an empty table on page2. Help would be greatly appreciated!
UPDATE:
Best thing for me would be to preserve the temporary table as is, so that I'm able to further manipulate it with MySQL queries on page 2. Do you know how to do that instead of ripping it apart by pulling the data into a php array? Sorry for mixing up this question a little bit.
You need to call session_start() before using any session-related facilities.
session_start();
$_SESSION['fase1result'] = $array;
then
session_start();
$table = $_SESSION['fase1result'];
Note that in most cases you need to call session_start() before any output, since it typically needs to send Cookie: headers to the client browser unless you have configured a different means of session persistence. Failing to do so can result in "header already sent" errors.
As tgies already pointed out, you need to have your session intialized.
Furthermore you use mysql_fetch_assoc() eventhough you're using mysqli (at least for the query), use while($row = $result->fetch_assoc()) or themysqli_fetch_assoc function (note the i).
Edit: There are several other options, but in most cases storing the data in a single, persistent table and identify it via an id in $_SESSION is a good way.
I have a table with arrays pulling information from a database, I have linked the fix to be a hyperlink "click me for fix" I have entered the link to send the variable to a php that will use $GET to echoe the information.
code below , i am new to php and been racking brains . the only out put i get is Welcome . (done welcome to test if information was being passed)
<div id=list>
<?php
// Create connection
$con=mysqli_connect('172.16.254.111',"user","password","Faults"); //(connection location , username to sql, password to sql, name of db)
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//where statement in the sql syntax will select where in db to get infor, use AND to add another condition
$result = mysqli_query($con,"SELECT * FROM Fixes WHERE Product='Serv1U' AND Fault_type='Broadcast Manager'"); //this creates a variable that selects the database
//below is the echo statment to create the results in a table format, list collumn titles
echo "<table id=tables border='1'>
<tr>
<th>Products</th>
<th>Fault_type</th>
<th>Fault_Description</th>
<th>Fix</th>
</tr>";
//below is script to list reults in a table format, $row [row name on table]
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['Product'] . "</td>";
echo "<td>" . $row['Fault_type'] . "</td>";
echo "<td>" . $row['Fault_Description'] . "</td>";
echo "<td>Click for Fix</td>"; //this is how you link into an echo, alsothe id=" hopefully means i can send ID information.
}
echo "</tr>";
echo "</table>";
// below closes the coonection to mysql
mysqli_close($con);
index.php:
Welcome <?php echo $_GET["Fix"]; ?>.
I'm lost. Any help is appreciated.
Thanks
?>
Is it just a typo here? $GET must be $_GET.
And it should be $row['Fix'] not $rows['Fix']! Note the 's'!
I searched fot the solution but nothing works.
<?php
$result = mysql_query("SELECT username, EmailAddress FROM users", $connection);
echo "<form method='post'><table class='mecz' cellpadding='0' cellspacing='0' border='0'>
<tr>
<th>user names:</th>
<th>address e-mail</th>
<th></th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr align='center'>";
echo "<td>" . $row['username'] . "</td>";
echo "<td>" . $row['EmailAddress'] . "</td>";
echo "<td><input class='delete' type='submit' name='delete' value='usuĊ' /></td>";
echo "</tr>";
}
echo "</table></form>";
//here a part when i'm trying to pass delete action from the form
?>
<?php
if (($_POST['username'] != "") && (isset($_POST['delete'])))
{
$username = $_POST['username'];
$query = "DELETE FROM users WHERE username = '".$username."' AND '".$_POST['delete']."'";
$result = mysql_query($query,$connection);
echo mysql_error();
}
?>
I think the solution is not very complex but i can't find it, please help.
Thanks,
Kris
you aren't sending username in the code you posted, so $_POST['username'] isn't set and thus the delete isn't executed.
even if you would enter the if-block, your delete-query doesn't make much sense - what should AND '".$_POST['delete']."' do? that part seems pretty sensless.
you try to make one form containing several submit-buttons (one for every user). on server-side you can't determine wich submit-button is pressed as the whole form gets sent as one big bunch of data. you'll need one form per user or simply use links (a-elements) to sent the delete- and username-values (but note that in the latter case you'd do GET instead of POST-requests)
you don't specify a action for your form - this might or might not be a problem in your case, please see the various comments to your question about this for more information.
your delete-query is perfectly open for sql-injections. please consider using prepared statements or at least mysql_real_escape_sting to avoid this.
and this are only the real problematic points that prevent your code from working at all or leave awkward security-holes. in addition, there are some things that are just unneccessary or some kind of messy (like calling mysql_error every time instead of doing that only if a query fails - but maybe you just added that for debugging).
altogether it seems like you should start reading a good book or some detailed tutoriala again to refresh and extend your fundamental understanding of php/mysql/html.