SQL echo table row error? - php

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>';
}
}

Related

Run a MySQL query trough pressing a link and escaping backslash

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.

MAMP - All MySQL Queries Return Null

I recently installed MAMP. But my I can't successfully execute MySQL queries from php. I can connect to MySQL from php, but all my queries come back as NULL. I don't get any error message or other message that would help me diagnose the problem.
Oddly, I can successfully query MySQL with phpMyAdmin and MySQLWorkbench.
Here is my code:
<?php
$link = mysqli_init();
$con = mysqli_real_connect($link, 'localhost', 'root', 'root', 'mrmk', 8889);
$db = 'mrmk';
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
echo "Host information: " . mysqli_get_host_info($link) . PHP_EOL;
$sql = "SHOW TABLES FROM `$db`";
$result = mysqli_query($con, $sql);
echo "</br>" . "1. MySQL Error: " . mysqli_error();
echo "</br>" . "result: ";
var_dump($result);
$sql = "SHOW TABLES FROM $db";
$result = mysqli_query($con, $sql);
echo "</br></br>2. MySQL Error: " . mysqli_error();
echo "</br>" . "result: ";
var_dump($result);
$sql = "SELECT * FROM `transactionTable` WHERE `attorneyName` LIKE \'%howard%\'";
$result = mysqli_query($con, $sql);
echo "</br></br>3. MySQL Error: " . mysqli_error();
echo "</br>" . "result: ";
var_dump($result);
if (!$result) {
echo "</br></br>" . "4. MySQL Error: " . mysqli_error();
exit;
} else {
echo "we should have results.";
}
while ($row = mysqli_fetch_row($result)) {
echo "Table: {$row[0]}\n";
}
mysqli_free_result($result);
?>
When I access the page through localhost I get this:
Host information: Localhost via UNIX socket
1. MySQL Error:
result: NULL
2. MySQL Error:
result: NULL
3. MySQL Error:
result: NULL
4. MySQL Error:
When I execute the same queries from phpMyAdmin, they execute successfully and return non-NULL results.
I have two questions:
What code can I add to help diagnose this problem?
Do I have a error in my code that is causing me to get NULL results.
Have you enabled mysqli extension in PHP? Check apache error log. Look at this question for example. mysqli is disabled by default, you need to uncomment line
extension=php_mysqli
in php.ini file.
To answer question #1, you might find it helpful to echo your $sql variables, to make sure your queries are valid and what you intended them to be.

Import data from a txt file in a MySQL database with PHP on visit

I'm using PHPMyAdmin to run my MySQL database.
Suppose we have this txt file "people.txt", a MySQL database and a PHP page in which are showed the data from the database. Suppose that data in the text file are stored with this syntax:
2015/16/01|Alex|Paris
2015/13/01|Johnny|Berlin
2015/11/01|Mary|Oslo
You can notice that each field is separated with a |
Is there any way to import these data using a PHP script? I want to show you a different script that, when the page is visited, send data to the database:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "my_db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO `People` (data, name, city)
VALUES ('2015/10/01', 'Will', 'Rome')";
if ($conn->query($sql) === TRUE) {
$last_id = $conn->insert_id;
echo "OK!";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
I want to emulate this script in order to let check, each time the page is visited, the txt file. Any help?
I tried to merge the PHP script that shows my data and the one that import them from the txt file but it doesn't seem to work properly..
<?php
$con=mysqli_connect("localhost","username","","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed: " . mysqli_connect_error();
}
$sql = "
LOAD DATA INFILE 'people.txt'
INTO TABLE `People`
FIELDS TERMINATED BY '|'
";
$result = mysqli_query($con,"SELECT * FROM `People`");
echo "<table class='people'>
<tr class='titles'>
<th>Data</th>
<th>Name</th>
<th>City</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['Data'] . "</td>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['City'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
Use the "LOAD DATA INFILE" statement to just load the data into the table every time the page is visited.
$sql = "
LOAD DATA INFILE 'people.txt'
INTO TABLE `People`
FIELDS TERMINATED BY '|'
";
One part of the SQL to look into are the REPLACE or IGNORE option, which determines what will happen if the script tries to insert a row that duplicate an existing unique key, if your table has any.
Also, if your input file has fields in a different order than your database table, then you can provide a list of columns at the end of the SQL, like (data, name, city).
Other than those things, I think you should simply be able to replace the $sql variable in your posted code with something like the above SQL, then run (as in your original code):
if ($conn->query($sql) === TRUE) {
echo "OK!";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

PHP problems getting data from table in mysql... only showing column names as data

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>';

PHP loop pulling from SQL (beginner)

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>";
}

Categories