For some reason the code below provides me with the following error:
Warning: Invalid argument supplied for foreach(). I tested the query in PHPmyadmin and the query works on its own. For some reason it doesn't work in the context if this php document. Are there any specific mistakes that are leading to this?
Thanks
<!Doctype <!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<table>
<tr>
<th> Course </th>
<th> Instructor </th>
<?php
$db = new PDO("mysql:dbname = 282exam; host = localhost", "root", "root");
$rows = $db->query("SELECT c.Name, i.Name
FROM course c
JOIN instructor i ON i.CId = c.Code");
foreach ($rows as $row){
?>
<tr>
<td> <?php print $row["c.Name"] ?></td>
<td> <?php print $row["i.Name"] ?></td>
</tr>
<?php
}
?>
</body>
</html>
instead of
foreach ($rows as $row){
do
while($row = $rows->fetch()){
(I just found out that change is optional, your way should work fine but this is how I've always done it)
And you don't need to specify the table alias in the result array
$row["Name"]
But you should specify an alias for each column if they're both the same...
SELECT c.Name as cname, i.Name as iname
$row["cname"] , $row["iname"]
Also, what Fred said:
then there should not contain any spaces in new PDO("mysql:dbname =
282exam; host = localhost" and
php.net/manual/en/pdo.error-handling.php would have thrown you an
error about it. see the manual php.net/manual/en/pdo.connections.php –
Fred -ii-
In other words: Change this to..
$db = new PDO("mysql:dbname=282exam;host=localhost", "root", "root");
AND
Missing <doctype> at the top that may cause errors
Missing </table>
Also, you're using <th> tags but no table header tags. Check out one of these links to figure out the correct table syntax.
Related
I'm using the NinjaForm plugin on my Wordpress site, which is working well but we're looking to create a custom .php page to output some of the submitted data.
Our current file is
<?php
$username = "SQLuser";
$password = "SQLpass";
$host = "localhost";
$connector = mysql_connect($host, $username, $password)
or die("Unable to connect");
$selected = mysql_select_db("wordpress", $connector)
or die("Unable to connect");
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Report</title>
</head>
<body>
<!--right-->
<?php
//execute the SQL query and return records
$result = mysql_query("SELECT * FROM wp_postmeta WHERE Meta_Key LIKE '%field%'");
?>
<table>
<thead>
</thead>
<tbody>
<?php
while ($row = mysql_fetch_assoc($result)) {
echo
"<tr>
<td>{$row['post_id']}</td>
<td>{$row['meta_key']}</td>
<td>{$row['meta_value']}</td>
</tr>";
}
?>
</tbody>
</table>
</body>
</html>
<?php mysql_close($connector); ?>
Mostly butchered from Display data from mysql/phpmyadmin on html page but this is displaying data in one long list like this screenshot
Our aim is to get this data in a table with the headers for for each field
e.g.
_field_5 = Name,
_field_8 = Food,
_field_6 = Can attend
The DB format is like this image, so the data isn't kept in separate columns in the first place, so hopefully we're able to rearrange this using php.
Any advice?
So, first a couple of things to note relating to best / safest practice in WP.
Don't create 'custom' pages. Create a custom template then add your php to that. Now create a page in WP, and assign it the relevant page template. This way you can make use of WordPress properly.
Use the WP functions for querying the database rather than querying the db directly via PHP
<?php
$querystr = "SELECT * FROM wp_postmeta WHERE Meta_Key LIKE '%field%";
$output = $wpdb->get_results($querystr, OBJECT);
?>
Now, with that in mind you need to construct the page accordingly. Without full access to your current results page I can only vaguely guess at how to format your markup. But, something like this should get you most of the way:
<table>
<thead>
</thead>
<tbody>
<?php
if($output){
foreach ($output as $row){
echo
"<tr>
<td>{$row['post_id']}</td>
<td>{$row['meta_key']}</td>
<td>{$row['meta_value']}</td>
</tr>";
}
}
?>
</tbody>
</table>
I'm building an exam management website and one of the pages I'm working on is for adding students to a course. I have a dropdown menu for the student number (which fetches values from a table), however I'd like to make it so that when the teacher selects the student number from the dropdown menu, that student's name and major appear on a table below. I have pretty much all the code for it however I can't seem to make it work. The way it is right now it shows the head of the table but it doesn't show any lines.
The errors are always in the lines where I declare $sql1 and $sql2 and vary according to how I define the condition in the statement.
Code for my dropdown menu : (works fine)
<label class="control-label" for="number">Student Number</label>
<?php
$sql = "SELECT number FROM students";
$result = $conn->query($sql);
echo "<select class=".'"form-control"'.' id="number" name="number" for="number">';
while ($row = $result->fetch_assoc()) {
echo '<option value="' . $row['number'] . '">' . $row['number'] . "</option>";
}
echo "</select>";
?>
Code for my table : (shows only head of table, which is the best I got after moving around the code and getting conversion errors and such)
The errors are always in the lines where I declare $sql1 and $sql2 and vary according to how I define the condition in the statement.
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Major</th>
</tr>
</thead>
<tbody>
<?php
$sql1 = "SELECT name FROM students WHERE number='$row'";
$result1 = $conn->query($sql1);
$value = $result1->fetch_object();
$sql2 = "SELECT major FROM students where number='$row'";
$result2 = $conn->query($sql2);
$value1 = $result2->fetch_object();
echo "<tr>
<td>".$value."</td>
<td>".$value1."</td>
</tr>";
?>
</tbody>
</table>
Thank you for all your help!!
Before I can formulate a complete answer, I must advise you that there are a few logical errors in your code.
How does your page "know" that a user selected an option from the select? You should perhaps intercept the event and respond to that using an asynchronoys mechanism, e.g. via AJAX.
Anyhow, there's no need to run two queries when you can make it with just one:
SELECT name, major FROM students WHERE number = ...
Once you have described how you mean to address issue #1 we can continue discussing the complete solution.
Well, I think there will be no $row in the the second snippet.
It seems that you didn't pass your $row from 1st snippet to 2nd snippet.
You can read this:
PHP Pass variable to next page
You can use session, cookie, get and post.
Or can just simply use "include", then the variables you defined can be used in the second page.
<?php
include "page1.php";
?>
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Major</th>
</tr>
</thead>
<tbody>
<?php
$number = $row['number'];
$sql1 = "SELECT name, major FROM students WHERE number='$number'";
$result1 = $conn->query($sql1);
$value = $result1->fetch_object();
echo "<tr>
<td>".$value['name']."</td>
<td>".$value['major']."</td>
</tr>";
?>
</tbody>
</table>
According to godzillante's answer below, the mysql query should be like this:
Anyhow, there's no need to run two queries when you can make it with just one:
SELECT name, major FROM students WHERE number = ...
I notice that you use $row as the key of your second query.
But in the first snippet, the data you fetch is "$row" (it is an array, see PHP - fetch_assoc)
You should use $row['number'] instead.
So I'm trying to make a HTML table that gets data from a MySQL database and outputs it to the user. I'm doing so with PHP, which I'm extremely new to, so please excuse my messy code!
The code that I'm using is: braces for storm of "your code is awful!"
<table class="table table-striped table-hover ">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Description</th>
<th>Reward</th>
<th>Column heading</th>
</tr>
</thead>
<tbody>
<?php
$con = mysql_connect("localhost", "notarealuser", 'notmypassword');
for ($i = 1; $i <= 20; $i++) {
$items = ($mysqli->query("SELECT id FROM `items` WHERE id = $i"));
echo ("<tr>");
echo ("
<td>
while ($db_field = mysqli_fetch_assoc($items)) {
print $db_field['id'];
}</td>");
$items = ($mysqli->query("SELECT name FROM `items` WHERE id = $i"));
echo ("
<td>
while ($db_field = mysqli_fetch_assoc($items)) {
print $db_field['name'];
}</td>");
$items = ($mysqli->query("SELECT descrip FROM `items` WHERE id = $i"));
echo ("
<td>
while ($db_field = mysqli_fetch_assoc($items)) {
print $db_field['descrip'];
}</td>");
$items = ($mysqli->query("SELECT reward FROM `items` WHERE id = $i"));
echo ("
<td>
while ($db_field = mysqli_fetch_assoc($items)) {
print $db_field['reward'];
}</td>");
$items = ($mysqli->query("SELECT img FROM `items` WHERE id = $i"));
echo ("
<td>
while ($db_field = mysqli_fetch_assoc($items)) {
print $db_field['img'];
}</td>");
echo ("</tr>");
}
?>
</tbody>
</table>
However, this code is not working - it simply causes the page to output an immediate 500 Internal Server Error. IIS logs show it as a 500:0 - generic ISE. Any ideas?
You are mixing mysql and mysqli, not closing php code block and you are not selecting a database. Plus you don't have to run a query for each field
Try this:
<table class="table table-striped table-hover ">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Description</th>
<th>Reward</th>
<th>Column heading</th>
</tr>
</thead>
<tbody>
<?php
$con = new mysqli("host","user", "password", "database");
$execItems = $con->query("SELECT id, name, descrip, reward, img FROM `items` WHERE id BETWEEN 1 AND 20 ");
while($infoItems = $execItems->fetch_array()){
echo "
<tr>
<td>".$infoItems['id']."</td>
<td>".$infoItems['name']."</td>
<td>".$infoItems['descrip']."</td>
<td>".$infoItems['reward']."</td>
<td>".$infoItems['img']."</td>
</tr>
";
}
?>
</tbody>
</table>
<table class="table table-striped table-hover">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Description</th>
<th>Reward</th>
<th>Column heading</th>
</tr>
</thead>
<tbody>
<?php
$con = mysqli_connect("hostname","username",'password');
$sql= "SELECT * FROM `items` WHERE id <20 ";
$items = (mysqli_query($sql));
while ( $db_field = mysqli_fetch_assoc($items) ) {?>
<tr><td><?php echo $db_field['id'];?></td></tr>
<tr><td><?php echo $db_field['name'];?></td></tr>
<tr><td><?php echo $db_field['descrip'];?></td></tr>
<tr><td><?php echo $db_field['reward'];?></td></tr>
<tr><td><?php echo $db_field['img'];?></td></tr>
<?php}
</tbody>
</table>
Try these, not tested
Where is the question?
There's many problems with this code.
First, you are confused between PHP and HTML.
Code between is PHP. It's executed on the server, you can have loops and variables and assignments there. And if you want some HTML there you use "echo".
Code outside is HTML - it's sent to the browser as is.
Second - what you seem to be doing is querying each field separately. This is not how you work with SQL.
Here's more or less what you need to do:
//Query all rows from 1 to 20:
$items = $mysqli->query("SELECT id,name,descrip,reward,img FROM `items` WHERE id between 1 and 20");
//Go through rows
while ( $row = mysqli_fetch_assoc($items) )
{
echo "<tr><td>{$db_field['id']}</td>";
//echo the rest of the fields the same way
});
I'm going to go ahead and assume that the code isn't working and that's because there's several basic errors. I'd strongly suggest doing some hard reading around the topic of PHP, especially since you're using databases, which, if accessed with insecure code can pose major security risks.
Firstly, you've set-up your connection using the procedural mysql_connect function but then just a few lines down you've switched to object-orientation by trying to call the method mysqli::query on a non object as it was never instantiated during your connection.
http://php.net/manual/en/mysqli.construct.php
Secondly, PHP echo() doesn't require the parentheses. PHP sometimes describes it as a function but it's a language construct and the parentheses will cause problems if you try to parse multiple parameters.
http://php.net/manual/en/function.echo.php
Thirdly, you can't simply switch from HTML and PHP and vice-versa with informing the server/browser. If you wish to do this, you need to either concatenate...
echo "<td>".while($db_filed = mysqli_fetch_assoc($item)) {
print $db_field['id'];
}."</td>;
Or preferably (in my opinion it looks cleaner)
<td>
<?php
while($db_filed = mysqli_fetch_assoc($item)) {
print $db_field['id'];
}
?>
</td>
However, those examples are based on your code which is outputting each ID into the same cell which I don't think is your goal so you should be inserting the cells into the loop as well so that each ID belongs to its own cell. Furthermore, I'd recommend using echo over print (it's faster).
Something else that may not be a problem now but could evolve into one is that you've used a constant for you FOR loop. If you need to ever pull more than 20 rows from your table then you will have to manually increase this figure and if you're table has less than 20 rows you will receive an error because the loop will be trying to access table rows that don't exist.
I'm no PHP expert so some of my terminology might be incorrect but hopefully what knowledge I do have will be of use. Again, I'd strongly recommend getting a good knowledge of the language before using it.
Hi I'm using file_get_contents() to search an off site text file, which returns an array as follows:
$foo_data = file_get_contents('http://foo/data_csv.php?code='.$row->code);
$foo_code = explode(",",$foo_data);
$foo_id = $foo_code[9];
If I place the above lines before the MySQL Select statement then the $foo_data variable is empty as it hasnt been initialised yet.
How do I reference this variable in the MySQL statement eg:
SELECT `field1`, `field2`, COUNT(distinct $foo_id) AS Ref
I've tried:
SELECT `field1`, `field2`, COUNT(distinct {$foo_id}) AS Ref
SELECT `field1`, `field2`, COUNT(distinct '{$foo_id}') AS Ref
Anyone know if it's possable to reference a table row from the array obtained in the above file_get_contents() ?
Complete code as follows:
<?php
include $_SERVER['DOCUMENT_ROOT']. '/class2.php';
Global $currentUser;
$user_name = $currentUser['user_loginname'];
$user_call = strtoupper($user_name);
$user_region = $currentUser['user_region'];
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<?
include("db_uploadlog.php");
if (!file_exists("db_uploadlog.php")) {
echo "Error - Config file is missing!";
}
else
{
$db_2 = mysql_connect($database_host, $database_username, $database_password);
mysql_select_db("db_name") or die("Cannot select database");
$foo_data = file_get_contents('http://foo.com/data_csv.php?code='.$row->code);
$foo_code = explode("|",$foo_data);
$foo_id - $foo_code[9]
$result = mysql_query("SELECT `column1`, `column1_id`, `code`, `column1_region`, '{$foo_id}' AS score FROM $table GROUP BY `column1` ORDER BY score DESC", $db_2);
$rowpos = mysql_num_rows($result);
$mnum = 1;
$mnum2 = 1;
if(mysql_num_rows($result) > 0)
{
?>
<table width="100%" align="center" border="0" cellpadding="0" cellspacing="0">
<tr>
<td width="2%"><b>Pos</b></td>
<td><b>Code</b></td>
<td width="10%"><b>Score</b></td>
</tr>
<?
for($i = 0; $i < mysql_num_rows($result); $i++)
{
$row = mysql_fetch_object($result);
?>
<tr>
<td><? echo $mnum2; ?></td>
<td><? echo $row->column1; ?></td>
<td><? echo $row->score; ?></td>
</tr>
<?
$mnum2 = $mnum2 + 1;
$mnum = $mnum + 1;
}
mysql_free_result($result);
mysql_close($db_2);
?>
</table>
</div>
<?
}
}
?>
</body>
</html>
Edited according to comment:
Then your problem is that file_get_contents don't recover data, you have to activate the property allow_url_fopen, set this property to 1 on your php.ini and your code should work
But i recommend you to use curl instead of file_get_contents you will have more control and curl was designed for this isn't it?
"If I place the above lines before the MySQL Select statement then the $foo_data variable is empty as it hasnt been initialised yet. "
This is probably because you reference the results from the MySQL select in your file_get_contents.
Other than that it should work, you are basically making a string in PHP and sending it to the MySQL server for parsing. So to MySQL it wont matter if you type it in by hand or if you use some pregenerated value.
Though, you need to trust the source if you are assembling the string from external sources, otherwise you should use PDO with bindParam.
edit
I see my initial thought was correct,
$foo_data = file_get_contents('http://foo.com/data_csv.php?code='.$row->code);
Here $row->code hasn't been initialized yet so file_get_contents goes to "http://foo.com/data_csv.php?code=" (if it goes anywhere at all).
You need to have another select above $foo_data which sets $row->code.
PHP normally shows an error message, but you probably are running on production mode. If you are testing you can put this in the top of your document
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
?>
Which should help you debug your script a bit better.
I've been reading about what others have done with this error and have made changes to my php.ini file, added code to override another php setting, and still end up with this same error. Here is my code:
<html>
<body>
<table>
<?php error_reporting (E_ALL ^ E_NOTICE); ?>
<?php
function getRecords($query) {
$con = mysql_connect("localhost", "movie", "moviepw");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("movies", $con);
$result = mysql_query($query);
// THE ERROR IS REPORTED ON THIS LINE
return $result;
}
function buildQuery() {
$keyword = $_GET['keyword'];
$sql = "SELECT * from movies WHERE
(
'movie_title' LIKE '%keyword%'
OR
'movie_description' LIKE '%keyword%'
)";
return $sql;
}
$query = buildQuery();
$records = getRecords($query);
while($row = mysql_fetch_array($records)){ ?>
<tbody>
<table border='1'>
<tr>
<td><?= $row['movie_title']; ?></td>
<td><?= $row['movie_rating']; ?></td>
<td> <img src="<?= $row['movie_image'];?>"> </td>
<td><?= $row['movie_description']; ?></td>
<td>Return to Search</td>
</tr>
<? } ?>
</tbody>
</table>
</body>
</html>
Any idea why I'm getting this error?
The editor had added spaces that were not deletable. I had to delete several lines and rewrite them. So, this issue wasn't exactly with the code...just a text editor software problem.
The other error I had was a boolean error with my query. Turns out I was trying to query the database instead of the table.
Thanks for all the help with this!
Remove the single quotes from the column names in your query. This may not be the only error, if the PHP interpreter is still complaining about ASCII 29.
$sql = "SELECT * from movies WHERE
(
'movie_title' LIKE '%keyword%'
OR
'movie_description' LIKE '%keyword%'
)";
// Should be
$sql = "SELECT * from movies WHERE
(
movie_title LIKE '%keyword%'
OR
movie_description LIKE '%keyword%'
)";