I have a single page responsive HTML page. One section of the page has a product search. User can enter search criteria in a form and get back the results. The results are paged.
<form id="filterform" name="filterform" method="post" action="./loaddata.php">
...
</form>
The form is submitted by Ajax and the results are returned as an HTML fragment that gets dynamically inserted into the DOM to refresh the results.
That's all working OK, but sometimes the results from loaddata.php are very slow, usually the first time called from the page.
In loaddata.php I'm using a Sqlite3 database. It is read only. Something like the following:
$filename = "../datafile.sqlite3";
$db = new SQLite3($filename);
$q = "SELECT distinct productId, title, price, name FROM datatable LIMIT 16";
$results = $db->query($q);
while ($row = $results->fetchArray()) {
echo "<h1>Results</h1>";
}
$db->close();
Is there a way to make loaddata.php load and stay in memory to respond to the form submit? It seems like it will reload every submit.
Depending on the size of the datatable you can save it on SESSION, use functions like shmop_open/shmop_write/shmop_read or (better yet) use some cache service like redis, but in one way or another the data will be stored and processed every time you pass by that place. I would tere the page in pieces, create one webservice to deal with the form post and another to show the form.
The easiest (not necessary safest or best way to do) would be ...
PS: I assume you are working with PDO and (obviously) the code bellow is an elaboration, it will not actually work
if (isset($_SESSION['db_datatable'])) {
foreach ($_SESSION['db_datatable'] AS $item) {
echo "<h1>".$item['some_row']."</h1>";
}
} else {
$filename = "../datafile.sqlite3";
$db = new SQLite3($filename);
$q = "SELECT distinct productId, title, price, name FROM datatable LIMIT 16";
$results = $db->query($q);
while ($row = $results->fetchArray()) {
$_SESSION['db_datatable'][] = $row;
echo "<h1>Results</h1>";
}
$db->close();
}
Hope I have been of some help. Cheers!
Related
So I have a backoffice called biblioteca.php where I have some requests and I can validate them trough a button called "Validar". That button redirects to a page like this: http://localhost/pap_16gpsi21/validacao.php?nproposta=87 where I can fill the form and submit.
What I want is to validate the request related to that url.
Example:
I've a request and his number is 90, I click on "Validar", then redirects me to a page like this http://localhost/pap_16gpsi21/validacao.php?nproposta=90, I fill the form and click submit. Then it updates the request number 90 in the database ($updateEstado = "UPDATE propostas SET validacao='Validado'";)
biblioteca.php
$selectProp = "SELECT nproposta, prioridade,disponibilidade,validacao,
autorizacao,aquisicao,registo,biblioteca,docente
FROM propostas
ORDER BY nproposta DESC";
$resultado = mysqli_query($ligaBD, $selectProp);
if (mysqli_num_rows($resultado) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($resultado)) {
<td><a class="btn btn-default" href="./validacao.php?nproposta=<?= $row["nproposta"] ?>">Validar</a></td>
valida.php
// gets nproposta from propostas
$npropostaLinha = "SELECT nproposta FROM propostas";
$resultado=mysqli_query($ligaBD, $npropostaLinha);
$nproposta = "";
printf($npropostaLinha);
$row = mysqli_fetch_array($resultado,MYSQLI_NUM);
printf("==> ");
print_r($row[0]);
$nproposta = $row[0];
$insertValidacao = "INSERT INTO validacao
(nproposta,nome_validacao,nif_validacao,
email_validacao,preco_validacao)
VALUES ($nproposta,'$nome_validacao','$nif_validacao',
'$email_validacao','$preco_validacao')";
$updateEstado = "UPDATE propostas SET validacao='Validado'";
$resultado = mysqli_query($ligaBD, $insertValidacao);
$resultado = mysqli_query($ligaBD, $updateEstado);
The problem is that if I have 3 requests (90,91,92) and I decide to validate just the number 91 it updates the first which is the number 90.
Also I know this isnt the safest method but this is just a test.
Hopefully, I explained explicitly. Sorry for any grammatical mistakes. Thank you
You need a couple of changes in your code as there are a few logical mistakes that I think you want to avoid.
You need to target a variable to specify from your SELECT that you desire a specific proposta;
You need, when updating, to specify which row, otherwise you will update every single record in your DB;
For such, go to your valida.php and add the following:
At the very top, check you have the variable ready
if (!isset($_POST['nproposta']) || empty($_POST['nproposta'])) {
//Do here what you desire to stop the script from running. Redirect back if you wish;
echo "No proposal id was found";
die;
}
$nPropostaID = $_POST['nproposta'];
Once you have your ID to target the row in your DB, update your query to consider it;
UPDATE propostas SET validacao='Validado' WHERE nproposta = $nPropostaID
Go to your form view and add below line within the form
<input type='hidden' value="<?php echo $_GET['nproposta']?>" name="nproposta">
NOTE: Because you mentioned you are aware of the SQL injections and this is a test I won't go with those, but always good to remember to be careful with them :) My proposal for the queries is just to get you going and in no way good for a script!
I am new to php and had chosen to stick to PDO format. I have been able to set up a workable registration and login system, but my challenge is fetching data from my database which would be used in other page of the user profile page I created. I had tried all the many examples and methods I was able to get on the internet but there are not working, or rather I don't know how to use it, where I want to insert the variable will still be empty.
The only fetch function I was able to get will select all the row, for instance, if it is email, it will fetch all the registered emails in the database which is not suppose to be. The email should only be for the user whose profile is opened.
Here are the codes. I am sure someone will help me figure this out. Thanks
$data = $pdo->query("SELECT * FROM databaseName")->fetchAll();
//this one is in the body where i want to insert the email
foreach ($data as $row) {
echo $row['email']."<br />\n";
}
I tried everything my little knowledge of php but all to no avail. If i decide to use any other one, nothing will show.
You can try other alternative to achieve the same,
$stmt = $pdo->query('SELECT * FROM databasetable');
while ($row = $stmt->fetch())
{
echo $row['email'] . "\n";
}
If you are only interested in the email from the returned results, I would look to do the following:
$stmt = $pdo->query('SELECT `email` FROM databasetable');
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo $row['email'] . "\n";
}
Or
$stmt = $pdo->query('SELECT `email` FROM databasetable');
$data = $stmt->fetchAll(PDO::FETCH_ASSOC))
foreach($data as $row)
{
echo $row['email'] . "\n";
}
If you want to check that the data coming back is good, I would add a "print_r($data);".
You can just take the first element of the results.
$stmt = $pdo->query('SELECT `email` FROM databasetable LIMIT 1');
$data = $stmt->fetchAll(PDO::FETCH_ASSOC)[0];
or use fetch()
$stmt = $pdo->query('SELECT `email` FROM databasetable LIMIT 1');
$data = $stmt->fetch(PDO::FETCH_ASSOC);
I´ve also put a LIMIT at the end of your query, so you dont fetch unneeded data.
Unless I am missing something then surely you should be specifying a where in your SQL query, why would you get the entire database and loop through it until you find the email you want?
When you redirect the logged in user you must(or if you aren't then you should) be passing something about the user, e.g setting the userid in the session. Then you can use this to create more useful profile data with a query that says select email from table where userid = :userid - then when you fetch the result you will have the data you need.
Naturally I can't write the exact query without knowing your structure but getting a whole tables worth of data every time is unscalable
I have code for a search function here:
<?php
include("config.php");
$search = mysql_real_escape_string($_POST['search']);
if (!empty($_POST['search'])) {
$data = mysql_query("SELECT * FROM shop WHERE name LIKE '%$search%' OR shout LIKE '%$search%' ORDER BY id DESC ") or die(mysql_error());
while ($info = mysql_fetch_array($data)) {
$name = stripslashes($info['name']);
$shout = stripslashes($info['shout']);
//Result code goes here eventually
}
}
?>
and I'll eventually make it display all results in a grid.
My problem starts when a user clicks on an item to see a page devoted to just that item (like any retail store site).
I'm assuming in my search code I can use $_SESSION and just set all the columns to sessions and then echo them on my results.php page.
Is this an efficient way to do this or am I going about it wrong?
I see websites that when you click on a certain item the URL looks all crazy and what not and I'm not really sure what causes that.
You can use
header('Location: /search/'.rawurlencode($search));
exit;
and now you can get your search string by
$search = rawurldecode($_GET['your_name']);
and your first page will not differ from the others. Or you can use method="get" in your search form. Anyway, you can use session to store your search string.
I'm creating a table dynamically from a mysql database that gets fields name, email, city. The email column has emails that I'd like to have as "mailto:" links. Currently they display the email without the hyperlink. There's a 'filter' form on the page as well that when submitted will display only results that correspond with a name specified in the form textbox by the user.
I'm very novice at creating anything dynamic. What's the easiest way to display the email column as hyperlinks? I was thinking about using javascript to do a getElementByID loop for the second td of every tr and amend a "mailto:" the beginning using string manipulation. Maybe this is more practically done in PHP instead?
edit:
I realized the obvious solution to my question. I simply concatenated the a href mailto: before the echo of the php command that gets my email field from the sql db and displays it in the table.
This is, indeed, more practically done in PHP. You can use something like the following, assuming that $result contains the result of a MySQL SELECT statement which fetches the users.
while ($u = $result->fetch_assoc()) {
// Output other data
// ...
echo '' . $u['email'] . '';
// ...
}
If you're still using mysql instead of mysqli (which you shouldn't really be doing), then replace
while ($u = $result->fetch_assoc()) {
with
while ($u = mysql_fetch_assoc($result)) {
$db = new PDO(//your dsn, host and password);
$query = $db->prepare('SELECT name,email from users');
$query->execute(); while($row = $query->fetch(PDO::FETCH_ASSOC))
{
echo ''.$row['name'].'';
}
I am currently still learning PHP so some things I still struggle with.
I have been taking it slowly and reading tutorials which has helped but I can't figure this one out.
I have a database table (in mysql) with let's say, 100 urls. There is a column called 'url' and a second column 'text'. I already have the pagination code which works, so will also be using that.
What I want to do is echo out the URLs (which are all in folder called blog in the root of my site), but use the text as the link.
So for example the first three rows in my table might be:
url
001.php
002.php
003.php
text
random text
some random text
more text
when echoed out the links show the text from the column text like:
random text
some random text
more text
and will open to the relevant url when clicked
I'm guessing it will need some kind of loop to collect all the URLs and save me adding the link text in manually, and then my pagination code will split them up.
This is my first time asking a question on here, so if it wasn't clear enough or you need more info, let me know.
I have done multiple searches on the internet but can't seem to find a tutorial.
Assuming you connect to a local mysql server with username "root" and password "root", and have your url's stored in a table named url_table in a database named url_database you could do something like:
$connection = mysql_connect("127.0.0.1","root","root"); // Connect to the mysql server
mysql_select_db("url_database"); // Open the desired database
$query = "SELECT url,text FROM url_table"; // Query to select the fields in each row
$result = mysql_query($query); // Run the query and store the result in $result
while($row = mysql_fetch_assoc($result)) // While there are still rows, create an array of each
{
echo "<a href='".$row['url']."'>".$row['text']."</a>"; // Write an anchor with the url as href, and text as value/content
}
mysql_close($connection); // close the previously opened connection to the database
What you need is to:
get your result array from the database. Use something like
$query = "SELECT * FROM urls";
$result = mysql_query($query);
For every row in your results table, show the corresponding url. Note that calling mysql_fetch_array on a result resource, returns the first row of the results table when called for the first time, the second on second time etc. The function returns false when there are no more rows to return.
(See more on that in the mysql_fetch_array() documentation)
While( $row = mysql_fetch_array($result) ){
echo '<a href='.$row['url'].'>'.$row['text'].'</a>';
}
Here is a sample you can start with:
$con = mysql_connect("host","user","password");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT the_url, the_text FROM my_table");
while($row = mysql_fetch_array($result))
{
echo '"' . $row['the_text'] . ' <br />';
}
mysql_close($con);
First, you want to select only the relevant lines in your database for the page that the user is currently viewing. For example, if the user is viewing page 2, with entries 15-30 present, we only want to pull those entries from the database. This is an efficiency concern.
The code you're after is something like this:
$link = mysql_connect(/*connection parameters go here*/);
if ($link === false)
die;
mysql_select_db('my_database');
$result = mysql_query("SELECT text, url FROM my_table LIMIT 15,30");
print "<ul>\n";
while ($row = mysql_fetch_assoc($result)) {
print "<li>{$row['text']}</li>\n";
}
print "</ul>\n";
mysql_close();
The first three lines establish a connection to the database, and exit the script if an error occurs.
The next line selects the appropriate database on the server.
The next block runs the appropriate query for the second page. After the query is run, a 'result' is stored in $result. This result is comprised of a number of rows, and mysql_fetch_assoc($result) obtains those lines one at a time. It then formats these lines into the appropriate link format and outputs them. The entire set of links is wrapped in a dot-point list.
Finally, mysql_close() closes the connection to the database.
I'm assuming since you just started you're probably doing all this procedurally.
First you want to query the database and get the info you need.
<?php
$result = mysqli_query($link, "SELECT url, text FROM table_name");
while ($row = mysqli_fetch_array($result)) $hrefs[] = $row;
foreach ($hrefs as $href) {
echo "".$href['text']."";
}
?>
Please note I've done no error handling here.