In my table I have various requests each with their own reference number.
a user can see the number of requests on the page, but I want the user to be able to click on each request separately and be taken to a new page to see the specific details for that request.
I am trying to echo the reference in a hyperlink when the request is clicked and on the next page when I run my query to retrieve the name etc of that request it will only show the information which matches that reference number, i.e. 'SELECT * WHERE reference = $row['reference'].
However I am not sure on how to to do this, also I am concerned is this secure, if my query is checking against the reference in my url, i.e. mypage.php?reference=1234, whats to stop a user just manually typing in the url with a different reference number?
'mypage.php?reference=2468
the user should only be able to view the page if they actually clicked on the request, they should never be able to enter it directly into the url as this poses a security risk.
could I potentially mask my reference into a string? and echo out mypage.php?reference=$someString
page1.php
<div class="results_area">
<h44>Existing Supplier Request's</h44>
<?php
$conn = new mysqli($host, $username, $password, $db_name);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error); }
$sql = "select * from new_supplier_request where status!= 'complete' AND action_taken='actioned'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo '<div class="table_header"><p>Request By</p><p>Date Requested</p><p>Status</p><p>Supplier Name</p><p>Description</p><p>Action</p></div>'; ?>
</div>
<div class="results_area"><?php
while($row = $result->fetch_assoc()) {
echo '<div class="request"><a href="ns_application.php?ns_request='.$row['reference'].'/">';
mypage.php
$reference = $row['reference'];
<?php
$conn = new mysqli($host, $username, $password, $db_name);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error); }
$sql = "select * from new_supplier_request where status!= 'complete' WHERE reference = $reference Limit 1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo '<h44>New Supplier Request: ' .$reference. ' </h44><br>';
echo 'The name of this supplier is, '.$reference['name'].';
} } ?>
</div>
You can use JavaScript to solve this problem.
I don't think that this will be 100% secure but actually it's more secure way than you are using now.
echo "<div .... onclick='showuniquereference('".$row['reference']."')'>"."</div>";
And Function like this
function showuniquereference(code)
{
var reference = code;
var form = document.createElement("form");
form.method = "POST";
form.action = "mypage.php";
var input = document.createElement("input");
input.name = "reference";
input.value = reference;
input.type = "hidden";
form.appendChild(input);
document.body.appendChild(form);
form.submit();
}
You can use this posted data to show unique reference to users.
Related
I'm trying to get a value from the database and compare it with whatever id href was set. But nothing happens.
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "";
$dbname = "products";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id FROM items";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$id = $row["id"];
echo <<<EOT
<br>
<form action='index.php?$id' method="POST">
<input type='submit' name="submit" value="more">
</form>
EOT;
}
} else {
echo "0 results";
}
if (isset($_POST['submit'])) {
while($row = $result->fetch_assoc()) {
if ($_SERVER["QUERY_STRING"] == $row) {
echo 'you clicked something from the database' . $id;
}
}
}
$conn->close();
?>
Trying to eventually get a value from the database then individually show a description if the more href is clicked.
your answer has a high time complexity you can easily make you
SQL query
SELECT id FROM items WHERE id = ?
and if the rows number is 0 this is mean there is no record with this id
you can check row's number from num_rows
You will never see "you clicked something from the database" message because you already fetched the result from your query in the first loop, check this question why-cant-i-loop-twice-on-mysqli-fetch-array-results
An option is to save the result in an array to use it later in your second loop
//your first loop
$savedRows = [];
while($row = $result->fetch_assoc()) {
$savedRows[] = $row;
//the rest of your code
}
// ......
// your second loop
if (isset($_POST['submit'])) {
foreach($savedRows as $row) {
if ($_SERVER["QUERY_STRING"] == $row['id']) {
echo 'you clicked something from the database ' . $id;
}
}
}
Also note that if this is your actual code, you need to make the closing identifier of your herodoc EOT; the first character on it's line, otherwise the rest of the file will be part of this string
how can I redirect the user to another php page based on the button he is pressing?
For example .. I want that once loaded the page, in it are generated buttons containing the "id" of the table taken from a database ... At the click of the button you are redirected to a page in which there are textbox with the fields belonging to the table id ..
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT idCantiere,nomeCantiere,codiceCommessa,indirizzoCantiere FROM Cantiere";
$result = $conn->query($sql);
echo'<h1> <font face="verdana" color="green">Quale Cantiere desideri Modificare?</font> </h1>';
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo'<br><br><br>';
echo'' . $row["nomeCantiere"] . '';
// echo '';
//''<input type="button" value="' . $row["nomeCantiere"] . '" />'
}
echo'<br><br><br>';
echo 'Nuovo Cantiere +';
} else {
echo "0 results";
}
$idCantierePerSelect = $_POST["idCantiere"];
global = $idCantierePerSelect;
function navigaButton()
{
// FUNCTION That redirect to the page
};
$conn->close();
?>
So I have to pick up the "idCantiere" and I have to make sure that by clicking on the button on the page that opens me there are textBox with the data of the table of the "idCantiere"
I think you are confusing the static html between dynamic server page.
1.PHP is responsible for fecthing data from database or server file system ,and send html tags to front end
2.the browser receives strings from php , and parse the strings to html elements ,finally starts to run javascript
If you want to redirect page.
In php header('Location: /your/path')
In javascript , window.location.href='/your/path'
Very quickly written and not tested - you could perhaps do like this. The function has to be javascript to interact with the client's actions ( ie: button press ) but the processing of the task is done by php. So, in the loop pass the ID of the record to the function as an inline argument and reload the same page with a new querystring. PHP will process the querystring, find the ID and then do a different database lookup to find the page that you want to redirect to.
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) die("Connection failed");
/*
This section should be ignored when page loads normally
but will be processed when the `navigaButton` is called
and the url changes.
*/
if( $_SERVER['REQUEST_METHOD']=='GET' && isset( $_GET['action'],$_GET['id'] ) ){
$sql='select NEWLOCATION from TABLE where ID=?';
$stmt=$conn->prepare( $sql );
if( $stmt ){
$stmt->bind_param('i',$id);
$id=filter_input( INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT );
$stmt->execute();
$stmt->store_result();
$stmt->bind_result( $url );
$stmt->close();
/* read the recordset and .... */
exit( header( 'Location: '.$url) );
}
}
?>
<!doctype html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>.... </title>
<script>
function navigaButton(id){
location.search='action=redirect&id='+id
};
</script>
</head>
<body>
<?php
$sql = "SELECT idCantiere,nomeCantiere,codiceCommessa,indirizzoCantiere FROM Cantiere";
$result = $conn->query($sql);
echo'<h1> <font face="verdana" color="green">Quale Cantiere desideri Modificare?</font> </h1>';
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo'
<br><br><br>
' . $row["nomeCantiere"] . '
';
}
echo'<br><br><br>
Nuovo Cantiere +';
} else {
echo "0 results";
}
$idCantierePerSelect = $_POST["idCantiere"];
/* below is incorrect */
/*global = $idCantierePerSelect;*/
$conn->close();
?>
</body>
</html>
In the PHP file can anyone help me directly making a for loop where I don't know the number of rows that are going to be selected.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydb";//database details
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM mytable";
$result = $conn->query($sql);
$myarray = array();
$index = 0;
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc())
{
$myarray[$index] = $row["firstname"];
$index++;
$myarray[$index] = $row["lastname"];
$index++;
$myarray[$index] = $row["email"];
$index++;
}
}
else
{
echo "0 results";
}
$conn->close();
?>
The Javascript code contains javascript of a search bar suggestion code and here i didn't mention the typeahead javascript file
var substringMatcher = function(strs) {
return function findMatches(q, cb) {
var matches, substringRegex;
// an array that will be populated with substring matches
matches = [];
// regex used to determine if a string contains the substring `q`
substrRegex = new RegExp(q, 'i');
// iterate through the pool of strings and for any string that
// contains the substring `q`, add it to the `matches` array
$.each(strs, function(i, str) {
if (substrRegex.test(str)) {
matches.push(str);
}
});
cb(matches);
};
};
$('#the-basics .typeahead').typeahead({
hint: true, //here i used typeahead js code though i didnt mentioned here
highlight: true,
minLength: 1
}, {
name: 'states',
source: substringMatcher(states)
});
You can simplify the PHP a little bit here when you read in the values as you dont need to increase the index:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydb";//database details
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);//making a connection
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM mytable";
$result = $conn->query($sql);
$myarray = array();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$myarray[] =$row["firstname"];
$myarray[] =$row["lastname"];//storing in the array
$myarray[] =$row["email"];
}
} else {
echo "0 results";
}
$conn->close();
?>
You could echo in the results to the Javascript where you require them, echo($myarray[0]) for example.
Your Javascript may look something like this:
var matches = <?php echo($myarray[0]); ?>
There are 4 ways you can do to insert dynamic content to your javascript code.
Make the javascript inline to your PHP page. That is, putting your js code inside <script> tags
Make the dynamic js variables global and populate them in your php page. Your separate JS files will be able to read these global js variables.
If you want to have a separate file for JS, you have to generate it everytime (because you cant have PHP code in javascript. The browser cannot interpret it, and the server cannot interpret it)
If you want to force the server to interpret PHP code in JS files, add a handler so that .js is handler by the php interpreter (whether php module or php-cgi) see Clean links to PHP-generated JavaScript and CSS
Using php i quay links from a database. when the link is clicked it should take me to a page. the problem here is the pages content depends on what link is clicked. i am trying to make a page were you can score stuff. the scores are in one database and the links are in another. is there
A:
a way to just add one number up from the last number in the database. for example the databases number is 1 and i click a button it will then be 2.
B:
is there a way to add a session with the link which is clicked and then somehow quay the name of the table that the scores are in.
i think A would be easier but i can not find an answer for this anywhere. my code is a mess and having the numbers just add up would be easier. i am here to answer any questions because im not very good at explaining things.
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "score";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name, description FROM all_scores ORDER BY id DESC LIMIT 5";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<p></p>";
echo "<a href=add/all_games/".$row['id']."/viewlink.php>". $row["name"]. "</a>";
echo "<p>". $row["description"]. "</p>";
}
} else {
echo "0 results";
}
$conn->close();
?>
please help
You could do something like this (depending on what the id equals, different content will be echoed):
Page with the links
<a href="location.php?id=1>Example</a>
<a href="location.php?id=2>Example</a>
<a href="location.php?id=3>Example</a>
Location.php
if(!isset($_GET['id']) === false) {
$id = $_GET['id'];
if ($id == 1){
echo 'Content displayed from clicking the first link';
}
if ($id == 2){
echo 'Content displayed from clicking the second link';
}
if ($id == 3){
echo 'Content displayed from clicking the third link';
}
}
Not sure what I did wrong. I'm aware that having two fetch_assoc removes the first result but I don't have such a thing.
$sql = "$getdb
WHERE $tablenames.$pricename LIKE 'm9%'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo $tableformat;
while($row = $result->fetch_assoc()) {
$name = str_replace('m9', 'M9 Bayonet', $row['Name']);
include 'filename.php';
echo $dbtable;
}
My connect file:
$servername = "";
$username = "";
$dbname = "";
$password = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
require_once ('seo.php');
$dollar = '2.';
$euro = '1.9';
$tableformat = "<div class=\"CSSTableGenerator style=\"width:600px;height:150px;\"><table><tr><th>Name</th><th>Price</th><th><a class=\"tooltips\">Community<span>New !</span></a> </th><th>Cash Price</th><th>Trend </th><th>Picture </th></tr></div>";
$getdb = "SELECT utf.id, utf.PriceMin, utf.PriceMax, utf.Name, utf.Trend , community1s.price as com_price, utf.Name, utf.Trend
FROM utf
INNER JOIN (select id, avg(price) price from community1 group by id) as community1s
ON utf.id=community1s.id";
$tablenames = 'utf';
$pricename = 'Name';
$idrange = range(300,380);
What happens is, it fetches the first two column's fine and the rest of the row is not there and pushes the other results down one row, which messes up the data.
Here's an image to demonstrate:
http://imgur.com/CQdnycW
The seo.php file is just a SEO function.
Any ideas on what may be causing this issue?
EDIT:
My Output:
echo $tableformat;
while($row = $result->fetch_assoc()) {
$name = str_replace('m9', 'M9 Bayonet', $row['Name']);
include 'filename.php';
echo $dbtable;
EDIT: Solved it by moving my variables around. Marked as solved.
I found the issue. Some Variables that did the output were in a bad place. Rearranged them and now they are fine.
Your HTML is broken, and strange things happen in broken tables. $tableformat contains HTML that opens a <div> and a <table>, but then closes the <div> with the table still open.
Fix the broken HTML and you'll probably find that all is well