Push MYSQL table onto another PHP page - 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.

Related

How can I extract all values in a database that start with the same letters as user input?

So I'm working on a stock quotes page, and in the "Find Symbol page", the user enters the symbol for a company and any symbols stored in the database that start with the exact same letters as user input will be output onto the table.
SOLVED- ANSWER BELOW
Your input in lowercase and it is stored in upper case
So change your query to convert the string into upper and then search
It is better to have upper in both sides of the where clause.
$query = "SELECT symSymbol, symName FROM symbols " .
"WHERE upper(symSymbol) LIKE '%".strtoupper($strSymbol)."%'";
What is this mess all about? Please see my comments in your code.
if(!$result)
{
print "Invalid Query Result<br />\n";
}
else
{
//============ This line is your main issue ============
$row = #$result->fetch_assoc(); //<-- pulling a row here advances the
//data set to row #2 (you never use the data from this row)
//======================================================
print "<table border='3' >\n";
print "<tr><th>Symbol</th>"
. "<th>Company Name</th>"
. "<th>Quotes Page</th" //<<--- unclosed </th>
. "<tr><th>History Page</th></tr>\n"; //<<--- misplaced <tr>
}//<<--- end if($result) block,
/*
anything below this is outside of the scope of the check for the result,
this will give you partial HTML and errors in the event of $result = false
*/
/*
because, you already advanced the dataset by one row, the loop starts on row 2
If you only had 1 row in your result set, then nothing is output from this block
While loops do not rewind, like a foreach ( besides I don't think you can rewind the DB result cursor )
*/
while($row = #$result->fetch_assoc())
{
extract($row); //<<--- avoid using this as it pollutes the scope, also where exactly are you using these variables it creates
print "<tr>";
print "<td>{$row["symSymbol"]}</td>";
print "<td align='right'>{$symName}</td>";
print "<td> Quotes Page</td>";
print "<td> History Page</td>";
print "</tr>\n";
}
print "</table>\n";
Lets start by cleaning that up
if(!$result){
print "Invalid Query Result<br />\n";
}else{
print "<table border='3' >\n";
/*
don't be afraid to indent or format things in a way that helps
keep track of the tags. Not like the "tab" police are going to
bust you for using all the tabs up.
*/
print "<tr>";
print "<th>Symbol</th>"
. "<th>Company Name</th>"
. "<th>Quotes Page</th>"
. "<th>History Page</th>\n";
print "</tr>\n";
while( $row = $result->fetch_assoc()){
/*
Try to use a consistent style for outputting, if possible.
*/
print "<tr>";
print "<td>{$row["symSymbol"]}</td>"
. "<td align='right'>{$symName}</td>"
. "<td> Quotes Page</td>"
. "<td> History Page</td>\n";
print "</tr>\n";
}
print "</table>\n";
}
You are basically throwing away the first row of your result set. When you call this ..}else{ $row = #$result->fetch_assoc(); .. you pull out the first row and move the internal pointer to row #2. Not only do you never use this data, but you overwrite $row with the value assigned in the while loop. Now while loops do not rewind back to the first result, so you pull row #2 and overwrite $row or you overwrite it with false. This is why when you have one match, you get none.
Some other thing to mention:
See how much clearer and concise my code is, well organized easy to read. Readability is the most important thing when coding ( IMO ).
Scope, keep the $result stuff inside the if block. If you don't do this then you're gonna have a bunch of errors, and invalid HTML.
Don't assign something if you are not gonna use it. While I understand, I was just "testing" that or "working" this out. That's all fine, but the first thing you should do when you have an issue, is go though your code, organize it and clean it up. Remove any "Fragments" from refactoring, and add comments to anything that is not clear just looking at the code it self.
Avoid using extract it pollutes your variable scope. That means you could overwite a variable without realizing it.
For example, say you have this code:
$name = 'John';
... bunch of other code ..
extract( $row );
... more code ...
echo $name; //outputs Tom
Now without being able to see the value of $row directly, you have no way to know that's what happened just by looking at the code. It's just a bad practice (IMO) to use it, because you don't want to use $row['name'].
Hope that helps.

Get proper column ids of the sql query passed through a link

Being a beginner in PHP, I have a table in a database which consists of 14 columns. I need to extract some of the columns through an 'href' link on another page. I am having a hard time trying to get the specific column ids for the specific column as I need the columns to be displayed as plain text separately on an html page.
So this is the fetch code to display columns 'A' and 'G' including two links in a table.
while($row=mysql_fetch_array($res))
{
echo "<tr>";
echo "<td>" . $row['A'] . "</td>";
echo "<td>" . $row['G'] . "</td>";
echo "<td>FASTA</td>";
echo "<td>Full Entry</td>";
echo "</tr>";
}
I am facing problems to get the columns A to M separately on the next php page of FullEntry.php and I need the data from the columns as plain text.
This is what I could come up with on FullEntry.php page.
$row = $_GET['rowid'];
<!--Here is where I need the multiple row ID's to get separate columnar data-->
echo $row;
?>
So How can use different id's for different columns from the original.php page to display results separately through the FullEntry.php page or If there can be any modifications with sql query as well. Help will be appreciated.
Any help would be appreciated.
Thank you in advance!
HereI have added a delimiter | bewteen $row reults like
echo "<td>Full Entry</td>";
And the result will be like Fullentry.php?rowid=a|b|c|d|e..... and you can access this by exploding the rowid.
$result = $_POST['rowid];
$result = explode("|",$result);
echo $result [0];
echo $result [1];...

Print MySQL table in PHP without knowing the columns

Im currently making a private "list management" system in which I store SQL queries in the database. So that I can via the front-end create new "lists" (which basicly are sql queries), and view them.
I have made the front end so you can save queries into the database, and im at the point where I want PHP execute and print out the results of one of my queries. This happens when I select one of my stored "lists" on my frontend. So when I press one of the lists, it should execute the SQL query. So far, so good.
But how can I, via PHP, print a table (like the one you get out from phpMyAdmin when viewing the contents of a table) without knowing how many / what columns exists? I want the script to be dynamic, so I can view results of all kinds of SELECT queries (on different tables).
Any tips or pointers?
Rather than using deprecated libraries, use PDO instead.
$db = new PDO($dsn); //$dsn is the database connection strings. Depends on your DB.
//it can be as simple as "odbc:CONN_NAME"
$stmt = $db->prepare("SELECT * FROM $tablename");
//be sure to sanitize $tablename! use a whitelist filter, not escapes!
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC); //fetch as associative array
if($rows){
//check if there are actual rows!
$first_row = reset($rows); //Resets the internal pointer, return the first elem.
$header_str = '<th>' . implode('</th><th>', array_keys($first_row)) . '</th>';
$table_body_rows = array();
foreach($rows as $row){
$table_body_rows[] = '<td>' .
implode('</td><td>', $row) .
'</td>';
}
$body_str = '<tr>' . implode('</tr><tr>', $table_body_rows) . '</tr>';
$tbl = "<table><thead><tr>$header_str</tr></thead><tbody>$body_str</tbody></table>";
} else {
//something went wrong
}
show tables is probably what you need
echo "<table><tr>";
$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql);
while ($row = mysql_fetch_row($result)) {
echo "<td> $row[0] </td>";
}
echo "</tr></table>"
mysql_free_result($result);
If you need to print a row with header (column names), you have to do it this way:
$result=mysql_query("SELECT * FROM yourtable WHERE 1");
if (mysql_num_rows($result)<1) echo "Table is empty";
else
{
$row=mysql_fetch_assoc($result);
echo "<table>";
echo "<tr>";
echo "<th>".join("</th><th>",array_keys($row))."</th>";
echo "</tr>";
while ($row)
{
echo "<tr>";
echo "<td>".join("</td><td>",$row)."</td>";
echo "</tr>";
$row=mysql_fetch_assoc($result);
}
echo "</table>";
}
This is just the basic concept. If your table has values which may contain HTML tags and other stuff, you'll need to apply htmlspecialchars() on all values of $row. This can be done with array_walk(). Furthermore you didn't mention what PHP version are you using and what MySQL API do you prefer. Some people suggested to use mysqli or PDO, that's up to you to rewrite the code according to your preferred API.

Html table returns empty after SQL query

I'm having problems with SQL query that returns no results instead of the data from the tables.
I have two tables on my DB, one is for Products and the other is Basket. The idea is to take the product id's from the basket and retrieve all the rest of the data from the product table. This is what i did:
$sql = sprintf("SELECT * FROM Basket");
$result = mysql_query($sql, $link);
while ($row = mysql_fetch_array($result)) {
$my_id = $row["Id"];
$prod_s=sprintf("SELECT * FROM Products WHERE Id='%s'",$my_id) ;
$prod= mysql_fetch_array($prod_s);
echo "<td>" . htmlentities($prod["Name"],ENT_QUOTES,"UTF-8") . "</td>";
echo "<td>" . htmlentities($prod["Size"]) . "</td>";
.
.
.
The table is being created but all fields are empty.
Thank you!
First of all, your current code is vulnerable to second-level SQL injections: if one of the IDs in the database is a malicious string (e.g. the good old ; DROP DATABASE foo), you're screwed.
Now, your actual problem is that you're not actually sending the second query to the SQL server. You'll want to run mysql_query() on it and use the result handle with mysql_fetch_array. You're already doing it correctly with the initial query. Just do the same thing again.
Finally, you might want to know that all of this can be done in a single SQL query, using joins. You may want to ask your favourite search engine about those. Good luck!
I think you still have to add a mysql_query for prod_s.
$my_id = $row["Id"];
$prod_s=sprintf("SELECT * FROM Products WHERE Id='%s'",$my_id) ;
$prod_q=mysql_query($prod_s);
$prod= mysql_fetch_array($prod_q);
echo "<td>" . htmlentities($prod["Name"],ENT_QUOTES,"UTF-8") . "</td>";
echo "<td>" . htmlentities($prod["Size"]) . "</td>";

Help retrieving information from php

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.

Categories