new to php and sql, and struggling for resources.
Essentially all I need to do is SELECT data from a table and to format it in appropriate html.
I've got the general idea, just not setting up the loop.
I have the SQL connection set up to the databse and then to the table.
here is the code. http://pastebin.com/vdTJgU5z
and the layout of the table.
http://i.imgur.com/JIpfI3g.png
Thanks guys, if there's anything that seems way off let me know, because i'd rather correct it now rather than later down the track.
CODE:
$query = mysqli_query($con,"SELECT * FROM tablenamehere");
while(????){
$game = $temp['game'];
$stance = $temp['stance'];
$start = $temp['start'];
}
echo '<div id="accordion">
<h3> echo $game $stance $start </td></h3>
</div>';
We all suggest the use of PDO for your MySQL connectivity.
Here's a quick and dirty way to get started (not tested):
$pdo = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8', 'user', 'pass');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // all pdo errors will throw an exception
try {
$result = $pdo->query("SELECT * FROM myTable");
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
echo "<tr>";
echo " <td>" . $row['column_name'] . "</td>";
echo " <td>" . $row['column_name2'] . "</td>";
echo " <td>" . $row['column_name3'] . "</td>";
echo "</tr>";
}
} catch(PDOException $e) {
echo "Something went wrong with the query. {$e->getMessage()}";
}
I suggest taking a look at the PHP manual
http://www.php.net/manual/en/control-structures.intro.php
http://www.php.net/manual/en/control-structures.while.php
It is pretty straightforward once you get the hang of it and understand what it is supposed to be doing.
Try this
$query = mysqli_query($con,"SELECT * FROM tablenamehere");
while($query){
$game = $query['game'];
$stance = $query['stance'];
$start = $query['start'];
echo "<div id='accordion'>
<h3><tr><td>".$game."</td><td>".$stance."</td><td>".$start."</td></tr></h3>
</div>";
}
Related
I have this PHP code below that prints the result of a MySQL query in a HTML table. Furthermore, in the table, I create a link of the result that will be used in another query. Lets take a look at the code:
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "root", "DB1");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt select query execution
$sql = "SELECT * FROM fileDB";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
echo "<tr>";
echo "<th>filename</th>";
echo "<th>filepath</th>";
echo "<th>size</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td><a href='http://mysecreturl.com/test.php?path=" . $row['filepath'] . "'>" . $row['filename'] . "<a/></td>";
echo "<td>" . $row['filepath'] . "</td>";
echo "<td>" . $row['size'] . "</td>";
echo "</tr>";
}
echo "</table>";
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
This code works as intended, but now comes the problem: I want to implement the following: Once you click on the link, another query should be executed, this one to be specific: SELECT * FROM fileDB WHERE filepath = 'the one sent from the link'. I thought to use something like $_GET["filepath"] from the link to set the filepath in the second query. I have two main problems with this:
I don't know any PHP so I have no idea how clicking a link could run another query and generate a new table with results.
This is important to point out, filepath is a string of a Windows path, therefore it contains backslashes like this: C:\something\something etc. When I query this manually in phpMyAdmin I escape the backslashes by writing C:\\something\\something but when getting my result in the table from the code above, the string filepath will have one pair of backslash of course (as it is saved in the database). How could I then perform my second query if the backslashes apparently need to be escaped?
Any help is very appreciated!
I thought you want to download a file. well this is much simpler:
if (isset($_GET["path"])) {
$stmt = mysqli_prepare($link, "SELECT * FROM fileDB WHERE filepath = ?");
mysqli_stmt_bind_param($stmt, "s", $_GET["path"]);
}else{
$stmt = mysqli_prepare($link, "SELECT * FROM fileDB");
}
mysqli_stmt_execute($stmt);
if ($result = mysqli_stmt_get_result($stmt)) {
if(mysqli_num_rows($result) > 0){
...
oh and one more thing you should escape query component in your URL
echo "<td><a href='http://mysecreturl.com/test.php?path=" . urlencode($row['filepath']) . "'>" . $row['filename'] . "<a/></td>";
Now this could be done using get method like <a href="yourpage.php?path='your_filepath'"> then in your php use this <?php if(isset($_GET['filepath'])){//Run your php query here}?>
You can do something like this:
echo '<tr>
<td><form method="get" action="test.php">
<button type="submit" name="path" value="'.$row['filepath'].'">
'.$row['filename'].'</button>
</form></td>
<td>'.$row['filepath'].'</td>
<td>'.$row['size'].'</td>
</tr>';
Untested, but should in theory work. Why you have the link in the filename-table-cell, instead of in the table-cell with the actual path in it, god knows, but you can test it and see if it works.
I would, however, just make this into a $_POST, unless it's important to show the URI in the address bar.
To answer the first question, you can add variables to a link, e.g. if you want to pass a first name and last name in a link you would do this
<?php
$fname = "John"; // First name
$lname = "Doe"; // Last Name
echo "<a href='next_table.php?fname=$fname&lname=$lname'>Next Table</a>";
?>
Then to retrieve the first name and last name on another page you would use this:
<?php
$fname = $_GET["fname"];
$lname = $_GET["lname"];
?>
Let me know if this helps.
Just an if statement to check whether the filepath is set or not and str_replace function to escape backlashes.
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "root", "DB1");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt select query execution
// Check If filpath is set or not
if(!isset($_GET['filepath']))
{
$sql = "SELECT * FROM fileDB";
}
else
{
$filepath=$_GET['filepath'];
//replace backlashes with double backlashes using str_replace
$filepath=str_replace('\\','\\\/',$filepath);
$sql = "SELECT * FROM fileDB WHERE filepath='$filepath'";
}
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
echo "<tr>";
echo "<th>filename</th>";
echo "<th>filepath</th>";
echo "<th>size</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td><a href='http://mysecreturl.com/test.php?path=" . $row['filepath'] . "'>" . $row['filename'] . "<a/></td>";
echo "<td>" . $row['filepath'] . "</td>";
echo "<td>" . $row['size'] . "</td>";
echo "</tr>";
}
echo "</table>";
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
Change the code:
// Attempt select query execution
$sql = "SELECT * FROM fileDB";
if($result = mysqli_query($link, $sql)){
To:
// Attempt select query execution
if(isset($_REQUEST['file']) && $_REQUEST['file'] !='') {
$sql = "SELECT * FROM fileDB WHERE `file` = '".$_REQUEST['file']."';";
} else {
$sql = "SELECT * FROM fileDB";
}
if($result = mysqli_query($link, $sql)){
This should convey the basic idea, but take to heart about using parameterized queries.
I'm VERY new to SQL, I have a table called "accounts". I want to echo all account info on an HTML table, I've tried this but it didn't work? (There are the proper tags around the php code)
<?php
$query="SELECT * FROM acccounts";
$results = mysql_query($query);
while ($row = mysql_fetch_array($results)) {
echo '<tr>';
foreach($row as $field) {
echo '<td>' . htmlspecialchars($field) . '</td>';
}
echo '</tr>';
}
?>
I think the problem is pretty obvious; you either didn't connect to your database, or your system doesn't allow the use of the mysql_ API.
Or, you tried connecting with the mysqli_ or other API (which is unknown). If this is the case; those different MySQL APIs do not intermix.
Using the mysqli_ API on my own machine produced results:
Replace the following with your own credentials:
<?php
ini_set("display_startup_errors", 1);
ini_set("display_errors", 1);
$connect = mysqli_connect("your_host", "user", "pass", "db");
if (!$connect) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
$query="SELECT * FROM acccounts";
$results = mysqli_query($connect, $query);
if($results){
while ($row = mysqli_fetch_array($results)) {
echo '<tr>';
foreach($row as $field) {
echo '<td>' . htmlspecialchars($field) . '</td>';
}
echo '</tr>';
}
}
else{
echo "Your query failed: " . mysqli_error($connect);
}
Check for errors on the query and via PHP.
References:
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/function.error-reporting.php
Note: Even without the <table></table> tags, it will still produce results, on a successful query.
Plus, this requires the file to be executed using a webserver with php/mysql installed and used as http://localhost as opposed to file:///, should this be the case.
Other reference:
http://php.net/manual/en/function.mysqli-connect.php
Few things, First off, you need to connect to the database with the sql instance name, uid and passwd strings,
secondly
your query should be mysqli_query($connection, $query)
ie
$servername = 'yourinstance\sqlexpress';
$conndetails = ["Database" => "databasename", "UID" => 'loginid', "PWD" =>'passwd'];
$sqlconn = mysqli_connect($servername, $conndetails);
$query = "Select blah blah";
$query2 = mysqli_query($sqlconn, $query);
double check the syntax because i often get it backwards off the mark but without this setup you can't connect to the database,
PHP has to authenticate / login before it can make queries (otherwise anyone would be able to query your database)
Additional to this, you need to ensure sql is listening on the right ports (normally 1433) this is done through the sql manager (not the sql explorer).
the results are still in array format, so you need to call the specific field name.
in this case.
echo '<td>' . $field['id'] . '</td>';
should work, (this is the format i use)
while ($row = mysqli_fetch_array($query)) {
foreach ($row as $field) {
echo '<td>' .$field['id']. '</td>';
}
}
I have a searchpage, which works fine. Search results are displayed in a table with tr hover and a window.location to take the user to a different page.
What I am trying to achieve is a dynamic link for the window.location based on data from the array. All the data in the db belongs to 4 different categories, testkat, and I would like to direct the user to the right page depending on the value from testkat, and then using the 'testid' to fill in the data.
I have been trying numerous ways to achieve my goal, and searched both SE, Google etc, but no luck. I'm pretty new to PHP so using the right search term might have something to do with it.
From my point of view I'm thinking that I have to store the value from testkat in a variable, lets say $link. And from there make an IF statement, something like:
if ($results('testkat') == 'something') {
$link = "something.php?id='$testid'";
}
if ($results('testkat') == 'something_else') {
$link = "something_else.php?id='$testid'";
}
And from there put $link in the window.location
Here's my code:
<?php
$conn = mysql_connect("localhost", "root", "") or die("Couldn't do it: ".mysql_error());
mysql_select_db("db") or die(mysql_error());
mysql_set_charset('utf8',$conn);
$query = $_POST['query'];
$query = htmlspecialchars($query);
$query = mysql_real_escape_string($query);
$raw_results = mysql_query("SELECT * FROM db WHERE (`id` LIKE '%".$query."%') OR (`name` LIKE '%".$query."%') OR (`age` LIKE '%".$query."%')") or die(mysql_error());
$count = mysql_num_rows($raw_results);
if(isset($_POST['query'])) {
echo "<br>";
echo "Your search for <span class=\"bold\">" .$query. "</span> returned " . $count . " hits";
echo "<br>";
if(mysql_num_rows($raw_results) > 0){
echo "<br>";
echo "<table class=\"tbl-text\">";
echo "<tr class=\"tablelist\"><th>Heading 1</th><th>Heading 2</th><th>#</th><th>Heading 3</th><th>Heading 4</th><th>Heading 5</th>";
while($results = mysql_fetch_array($raw_results)){
echo "<tr onclick=\"window.location='#'\" style=\"cursor:pointer\" class=\"tr-hover\">";
echo "<td class=\"bordered\">" .$results['testid'] . "</td>";
echo "<td class=\"bordered\">" .$results['testkat'] . "</td>";
echo "<td class=\"bordered\">" .$results['intnr'] . "</td>";
echo "<td class=\"bordered\">" .$results['pro'] . "</td>";
}
echo "</table>";
}
else{
}
}
?>
Update:
Forgot to tell about the error. When doing it the way I think it should be done, I get an error message in the IF statement saying: Fatal error: Function name must be a string.
Referring to this one:
if ($results('testkat') == 'something') {
$link = "something.php?id='$testid'";
}
I know about MySQLi and PDO, working on it.
Eager to learn, so any hints and tricks are greatly appreciated :)
Chris
That method looks fine. You don't need the single quotations around $testid though
$link = "something_else.php?id=$testid";
As you've mentioned you should stop using mysql, get learning :)
Managed to fix it, and posting if someone else are having the same problem.
First, rewrote the whole thing to MySQLi.
Then I put an IF statement after the WHILE LOOP like this:
Connecting to db ->
if(isset($_POST['query'])) {
$query = $_POST['query'];
$query = htmlspecialchars($query);
$sql = $db->query("SELECT * FROM db WHERE (`?` LIKE '%".$query."%') OR (`?` LIKE '%".$query."%') OR (`?` LIKE '%".$query."%')");
$result = mysqli_query($db, sql);
$hits = $sql->num_rows;
echo "<br>";
echo "Your search for <span class=\"bold\">" .$query. "</span> returned " . $hits . " results";
echo "<br>";
if($sql->num_rows > 0){
echo "<br>";
echo "<table class=\"tbl-text\">";
while ($row = mysqli_fetch_array($sql)) {
if ($row['category'] == 'cat01'){
$link = 'cat01.php?id=' . $row['testid'] . '';
}
if ($row['category'] == 'cat02'){
$link = 'cat02.php?id=' . $row['testid'] . '';
}
if ($row['category'] == 'cat03'){
$link = 'cat03.php?id=' . $row['testid'] . '';
}
if ($row['category'] == 'cat04'){
$link = 'cat04.php?id=' . $row['testid'] . '';
}
echo "<tr onclick=\"window.location='$link'\" style=\"cursor:pointer\" class=\"tr-hover\">";
echo "<td class=\"bordered\">" .$row['testid'] . "</td>";
>>> more echo
}
There are probably more efficient ways to do this, but at least I got the results I was after, and the script is also more secure now using MySQLi
I have problem with my code.
I use nested while in my code and the nested while doesn't work, only the outer while is work
I don't know where is the bug of my code.
This is the piece of my code :
$database = new mysqli('127.0.0.1', 'user', 'user', 'mini_email');
$query = 'SELECT * FROM mails';
$query2 = 'SELECT * FROM users';
$result_set = $database->query($query);
$result2 = $database->query($query2);
while ($row2 = $result2->fetch_assoc()) {
if ($row2['username'] == $_SESSION['user']) {
$id_email = $row2['id'];
}
}
if (isset($_SESSION['is_logged_in'])) {
echo('<center><font size="10">Mailing List</font></center><br><br>');
echo('<center><table border="3" bgcolor="#f0cdfa">');
echo('<tr>');
echo ('<td>No</td>');
echo ('<td>ID</td>');
echo ('<td>From</td>');
echo('<td>Subject</td>');
echo ('<td>Message</td>');
echo ('<td>Action</td>');
echo ('</tr>');
$i = 1;
while ($row = $result_set->fetch_assoc()) {
if ($row['to_user_id'] == $id_email) {
echo('<tr>');
echo ('<td>' . $i . '</td>');
echo ('<td>' . $row['id'] . '</td>');
while($row2 = $result2->fetch_assoc()){
if($row2['id']== $row['from_user_id']){
echo ('<td>' . $row2['username'] . '</td>');
}
}
echo ('<td>' . $row['subject'] . '</td>');
echo ('<td>' . $row['message'] . '</td>');
echo ('<td>View</td>');
echo ('</tr>');
$i++;
}
}
Your initial
while ($row2 = $result2->fetch_assoc()) {
is looping through all the records to the end of the set,
so looping a second time won't retrieve any further records because you're already at the end of the resultset
Resultset pointers aren't automatically reset when you initiate a new loop, but you can reset them manually using
$result2->data_seek(0);
before each subsequent loop
But iterating the point made in the comments by #Sirko you'd be better using a JOIN to make a single query
If I may help, I think you shouldn't even perform the queries when your if statement with the session returns false.
In the first lines or your script you should define a function with all this code, and write it like this :
function YourFunction()
{
if (isset($_SESSION['is_logged_in'])) {
return false;
}
// Database connection and queries
// your business
}
This will be more clean.
Next, your query doesn't seem to be correct. You get all the mails of your website, and then in a loop you check if the mail user id is the user id you have in session. Imagine the lack of performance if you have 35 000 mails in your database.
Improve your query with a WHERE statement : http://www.w3schools.com/sql/sql_where.asp
then, are you sure that $_SESSION['user'] contains an id ? I think your second if statement never returns true because of that.
I tried this but didn't work for me...I mean I am getting my table and the row count is Correct. But when I use $row['ColumnName']... I keep getting the ACTUAL name of the column and not the data itself.
If I add more rows of data to the table, I get the row count up but the data is still the same. Only Column names.
Anyone has had this issue? and how to solve it?
php version: 5.3 and mysql version: 5.5
$connection = mysql_connect('localhost', 'root', '');
mysql_select_db('employeedb');
$query = "SELECT * FROM employee"
$result = mysql_query($query);
echo "<table>"; // start a table tag in the HTML
while($row = mysql_fetch_array($result)){ //Creates a loop to loop through results
echo "<tr><td>" . $row['name'] . "</td><td>" . $row['age'] . "</td></tr>";
//$row['index'] the index here is a field name
}
echo "</table>"; //Close the table in HTML
mysql_close(); //Make sure to close out the database connection
mysql_ is deprecated, here is some code in PDO.
//Open PDO connection
try {
$db = new PDO("mysql:dbname={'employeedb'}; host={'localhost'}", 'root', '');
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
} catch (PDOException $Exception) {
echo "There was an error.";
}
//Query prep
$query = $db->prepare("
SELECT *
FROM employee
");
//Query execution; try to use prepared statements always
$query->execute();
//create string $output
$output = "<table>";
//for rows of indeterminable quantity, use foreach()
foreach($query as $table) {
//append to $output
$output .= "<tr><td>";
$output .= htmlspecialchars($table["name"]);
$output .= "</td><td>";
$output .= htmlspecialchars($table["age"]);
$output .= "</td></tr>";
}
$output .= "</table>";
//print $output
echo $output;
//close PDO connection
$db = null;
As an aside, make sure to escape all output by using htmlspecialchars(). I would also consider having some kind of try/catch complex to ensure error handling is done correctly and pertinent info isn't revealed to the user.
Oh, looks like you solved it. If you're working within an undefined amount of rows, instead of using a while() loop, consider a foreach() loop instead.
can u try using numeric indexes than coloumn name. like shown below
while($row = mysql_fetch_array($result)){
echo "<tr><td>" . $row[0] . "</td><td>" . $row[1] . "</td></tr>";
}
Try this:
$db = new PDO ('localhost', 'root');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "SELECT * FROM employee"
$statement = $db->prepare($query);
$statement->execute();
echo '<table>';
foreach($statement as $row){
echo '<tr>';
echo '<td>', $row['name'],'</td>';
echo '<td>',$row['age'],'</td>';
echo '</tr>';
}
echo '</table>';