On one page I have a form which POSTs the data entered in the 1 field across to another page.
On this page which you are directed to after entered data in the form field is a connection to a sql database. It happily rePOSTs the form field data on the page. Then I have got the PHP for retrieving the information from the database. This works nicely when the WHERE part is fixed manually ('criteria') however I would like the WHERE criteria for this search to be the form data from the previous page.
is there a way to echo the data to it? The form data is successfully getting to the displaying page however need help with the WHERE part.
That line of code currently is...
$result = mysqli_query($con,"SELECT * FROM table WHERE field = 'formdata'");
Any help would be appreciated greatly.
Right now, query compares field to the actual string 'formdata'. You'll want to grab the formdata, if you're POSTing, like this:
$result = mysqli_query($con, "SELECT * FROM table
WHERE field = '" . $_POST['formdata'] . "'");
Although, note that you'll need to use prepared statements to make this secure. See here and here.
I use PDO, but mysqli should be roughly the same
$formdata = $_POST['input'];
$stmt = $con->prepare('SELECT * FROM table WHERE field = ?');
$stmt->bind_param('s', $formdata);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// do something with $row
}
Related
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!
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
The application I'm building requires some users to be linked to eachother.
There will be users and mentors. The database field "mentor_link" has a value. This value determines which users the mentor is linked to.
What I'm trying to do is search the database for the users with a certain "mentor_link" value and save their usernames as php variables to be used later.
Using json_encode() AND print_r simply displays something that looks like this:
[{"userName":"dave","0":"dave"},{"userName":"ely","0":"ely"},{"userName":"mentor1","0":"mentor1"}]
What I'm looking for is to target each username and save it as a variable. For example: $user1 = dave; $user2 = ely; etc etc.
All the other examples I've found only allow me to display it the same way as above.
My code is as follows:
$stmt = $user_home->runQuery("SELECT userName FROM tbl_users WHERE mentor_link=101");
$stmt->execute();
$result = $stmt->fetchAll();
echo json_encode($result);
The database is connected fine and I'm able to pull single values based on the users details but I can't figure out how to get info on other users and display it/save it as a variable.
Oh and I'm using PDO to connect to the database.
After this line:
$result = $stmt->fetchAll();
You can do anything with that data
print_r($result[0]);//user1
print_r($result[1]);//user2
or
$user1 = $result[0];
$user2 = $result[1];
then
echo $user1['userName'];//dave
echo $user2['userName'];//ely
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 have a database (db_name=members) with a lot of fields but the relevant ones for this are:
security_question, security_answer, email
The php code is:
$email = $_COOKIE['site_user'];
$select_sa = mysql_query("SELECT security_answer FROM members WHERE email='".$email."'");
$result_sa = mysql_query($select_sa);
$arr_sa = mysql_fetch_row($result_sa);
$result2 = $arr_sa[0];
$get_sa = $result2;
If I
echo $select_sa;
It prints "Resource id #6" although in the table I can see the security answer as a word and not "Resource id #6".
If I
echo $get_sa;
It prints nothing.
Could you please help me to be able to read the securty_answer field from the database ?
Thanks,
Ray
You're doing the query twice, feeding the result handle from the first time into the query text parameter of the second one. That's invalid. Try this instead:
$select_sa = "SELECT security_answer FROM members WHERE email='".$email."'";
$result_sa = mysql_query($select_sa);
$arr_sa = mysql_fetch_row($result_sa);
$result2 = $arr_sa[0];
$get_sa = $result2;
Please also make sure that the $email field is being passed through mysql_real_escape_string() before being used in the query. All data fetched from the user, e.g. via $_GET, $_POST or $_COOKIE, must be escaped properly. If you don't escape it, you'll be open to SQL injection attacks.