i'm coding a project and have some troubles when the system inform error:
Invalid argument supplied for foreach() in:
foreach($dbh->query($q1) as $row)
and can't get data from the database. How can i fix it, im a newbie, so if i don't understand, please teach me! thanks!
thank for your helps but i still can't fix it
<?php include("top.html"); ?>
<body>
<div id="main">
<h1>Results for <?php echo $_GET['firstname'] . " " . $_GET['lastname'] ?></h1> <br/><br/>
<div id="text">All Films</div><br/>
<table border="1">
<tr>
<td class="index">#</td>
<td class="title">Title</td>
<td class="year">Year</td>
</tr>
<?php
$dbh = new PDO('mysql:host=localhost;dbname=imdb_small', 'root', '');
$q1 = "SELECT id
FROM actors
WHERE first_name = '".$_GET['firstname']."' AND last_name = '".$_GET['lastname']."'
AND film_count >= all(SELECT film_count
FROM actors
WHERE (first_name LIKE'".$_GET['firstname']." %' OR first_name = '".$_GET['firstname']."')
AND last_name = '".$_GET['lastname']."')";
$id = null;
foreach($dbh->query($q1) as $row){
$id = $row['id'] ;
}
if($id == null){
echo "Actor ".$_GET['firstname']." ".$_GET['lastname']."not found.";
}
`
$sql2 = "SELECT m.name, m.year
FROM movies m
JOIN roles r ON r.movie_id = m.id
JOIN actors a ON r.actor_id = a.id
WHERE (r.actor_id='".$id."')
ORDER BY m.year DESC, m.name ASC";
$i = 0;
foreach($dbh->query($sql2) as $row){
echo "<tr><td class=\"index\">";
echo $i+1;
echo "</td><td class=\"title\">";
echo $row['name'];
echo "</td><td class=\"year\">";
echo $row['year'];
echo "</td></tr>";
$i++;
}
$dbh = null;
?>
</table>
</div>
</div>
<?php include("bottom.html"); ?>
</body>
</html>
Check that your query succeeded before iterating on the result:
if (false !== ($result = $dbh->query($d1))) {
foreach($result as $row){
$id = $row['id'] ;
}
}
By the way, I don't understand what you are trying to do with this pointless loop.
You could do this
$st = $dbh->query($q1);
if ( $st ) {
while ( $row = $st->fetch() ) {}
}
Try to make your code more readable
$result = $dbh->query($q1);
foreach($result as $row){$id = $row['id'];}
Related
Hello guys,
I've a problem and I hope anybody can help me.
My MySQL database looks like this:
I would like to output these data in a table this way:
My actual code looks like this:
<html>
<body>
<table>
<?php
$root = realpath($_SERVER["DOCUMENT_ROOT"]);
include "$root/config.php";
$stmt = $pdo->prepare('SELECT * FROM TestTable ORDER BY name');
$stmt->execute();
$results = $stmt->fetchAll();
if (empty($results)) {
echo 'Error!';
} else {
foreach( $results as $row ) {
echo
"
<tr>
<td class=\"left\">".$row['name']."</td>
<td class=\"right\">".$row['address']."</td>
</tr>
";
}
}
?>
</table>
</body>
</html>
Output looks like this actual:
What to do to have the name of the profession always on top, when the profession is not the same like in the row before?
To sove this issue I've this code:
<?php
$mysqli = new mysqli(host,username,password,db_name);
$sql = "SELECT * FROM TestTable ORDER BY profession, name";
$array = [];
$html = "";
if ($result = $mysqli->query($sql)) {
while($row = $result->fetch_assoc()) {
if (!isset($array[$row['profession']])) {
$array[$row['profession']] = array();
}
$array[$row['profession']][] = $row['name'];
}
}
foreach ($array as $profession => $name) {
$html .= '<p style="font-weight:bold">'.$profession.'</p>';
foreach ($name as $name) {
$html .= '<p class="name">'.$name.'</p>';
}
}
echo $html;
?>
But I need the street in this table too. And I need this code with PDO not MySQLi. I tried to manage this, but without success.
Can anybody help me please?
Greetings,
David.
try something like this:
$stmt = $pdo->prepare('SELECT * FROM TestTable ORDER BY profession, name');
$stmt->execute();
$results = $stmt->fetchAll();
if (empty($results)) {
echo 'Error!';
} else {
$profession = $row['profession'];
foreach( $results as $row ) {
if ($row['profession'] <>$profession) {
echo "<tr><td>". $row['profession']."</td></tr>";
}
echo "<tr>
<td class=\"left\">".$row['name']."</td>
<td class=\"right\">".$row['address']."</td>
</tr>
";
$profession = $row['profession'];
}
}
I have this date format in place in my files. It works great if I do a normal SELECT query, but when I do a prepared statement query that does not have a bind_param and assign it a bind_result variable, I cannot get this to work.
Here is the function. Which it displays in US Central time. How can I get that to Eastern time?
function fixDate($strDateTime) {
$strFormat = 'M, j, Y';
$strFormatTime = '\a\t g:ia';
$intTimeStamp = strtotime($strDateTime);
$strDate = date($strFormat, $intTimeStamp);
$strTime = date($strFormatTime, $intTimeStamp);
if($strDate == date($strFormat)) {
return "Today " . $strTime;
}
elseif($strDate == date($strFormat, strtotime('yesterday'))) {
return "Yesterday " . $strTime;
}
else {
return " on " . $strDate . " " . $strTime;
}
}
The function will work if I do this with a normal SELECT query.
$date = $row2['topic_date'];
$date = fixDate($date);
BUT if I have a bind_result of $date and try to do this
$date = fixDate($date);
It won't work.
How can I get this function to work with a prepared statement's bind_result variable?
UPDATE:
This works..
$query2 = mysqli_query($con,"SELECT * FROM forum_topics
INNER JOIN forum_categories ON
forum_topics.category_id = forum_categories.id
INNER JOIN users
ON forum_topics.topic_creator = users.id
ORDER BY forum_topics.topic_reply_date DESC
LIMIT 3")
or die ("Query2 failed: %s\n".($query2->error));
$numrows2 = mysqli_num_rows($query2);
if($numrows2 > 0){
$topics .= "<table class='top_posts_table'>";
$topics .= "<tr><th class='top_posts_th'>Topic Title</th><th class='top_posts_th'>Replies</th><th class='top_posts_th'>Views</th></tr>";
$topics .= "<tr><td colspan='3'><hr /></td></tr>";
while($row2 = mysqli_fetch_assoc($query2)){
$cid = $row2['cid'];
$tid = $row2['id'];
$title = $row2['topic_title'];
$views = $row2['topic_views'];
$replies = $row['tid2'];
$date = $row2['topic_date'];
$date = fixDate($date);
$creator = $row2['username'];
$topics .= "<tr><td class='top_posts_td'><a href='forum_view_topic.php?cid=".$cid."&tid=".$tid."'>".$title."</a><br /><span class='post_info'>Posted
by: ".$creator."<br>".$date."</span></td><td class='top_posts_td'>0</td><td class='top_posts_td'>".$views."</td></tr>";
$topics .= "<tr><td colspan='3'><hr /></td></tr>";
This doesn't work...
if ($announcements_stmt = $con->prepare("SELECT announcements.id, announcements.user_id, announcements.message, announcements.date, users.username FROM announcements
INNER JOIN users
ON announcements.user_id = users.id")) {
$announcements_stmt->execute();
$announcements_stmt->bind_result($announcements_id, $announcements_user_id, $announcements_messages, $announcements_date, $announcements_username);
if (!$announcements_stmt) {
throw new Exception($con->error);
}
}
$announcements_stmt->store_result();
$announcements_result = array();
$announcements_date = $announcements_date;
$announcements_date = fixDate($announcements_date);
?>
<div class="index_announcements_out">
<div id="announcements_title">League Announcements:</div>
<div class="index_announcements_wrap">
<table class="index_announcements_table">
<?php
while ($row = $announcements_stmt->fetch()) {
?>
<tr class="index_announcements_border">
<td class="index_announcement_pic"></td>
<td class="index_announcement_username_td">FROM: <?php echo $announcements_username; ?><br>on <?php echo $announcements_date; ?></td>
<td class="index_announcement_message_td"><?php echo $announcements_messages; ?></td>
</tr>
Basically, when using bind_result(), you need to do a fetch() before the variables get populated. In this case, you're trying to access them before that happens.
In the given code, it's not necessary to get the fixed $announcements_date outside the while loop, so just replacing <?php echo $announcements_date; ?> with <?php echo fixDate($announcements_date); ?> in the loop should do the trick.
$i = 1;
$sql = "
SELECT
heroes.char_id, characters.char_name, heroes.class_id, heroes.count,
heroes.played, heroes.active FROM heroes, characters
WHERE characters.obj_Id = heroes.char_id AND heroes.played = 1
";
$query = mysql_query($sql);
while($row = mysql_fetch_array($query))
{
echo "
<tr>
<td><span id='lefttop'><b><font color='#007aa2'>".$i++." </font></td><td><b><font color='#f6ff00'>".$row['char_name']."</font></td></span><div style='float:right;'><td><b> ".$row['count']."</td></div> <br />
</tr>
";
}
echo "";
?>
Anyone can help? im trying to make a hero status script on a java server, and i need to connect into 2 tables which is "heroes"(this is where i get the hero) and "character" (this is where i get the hero names)
Try this Temple:
<?php
$sql1 = "SELECT * your table1";
$query1 = mysql_query($sql);
while($row1 = mysql_fetch_array($query1))
{
echo "<tr>";
$sql2 = "SELECT * your table2";
$query2 = mysql_query($sql2);
while($row2 = mysql_fetch_array($query2))
{
echo "<td>[yor Vars here]</td>";
}
echo "</tr>";
}
?>
having trouble getting a script of mine to run correctly, I have 2 undefined index errors and an invalid argument supplied error that for the life of me I can't figure out why I'm getting. the 2 undefined index errors come from these lines.
if(!is_null($_GET['order']) && $_GET['order'] != 'courseTitle')
and
if (!is_null($_GET['page']))
and my invalid argument error is this
Warning: Invalid argument supplied for foreach() in
generated from this
<?php foreach ($books as $book) : ?>
my full code between the two classes is this.. any ideas of what I've done wrong? tearing my hair out over this.
index.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Catalog</title>
</head>
<body bgcolor="white">
<?php
/////////////////////////////////////////////////
//connect to db
/////////////////////////////////////////////////
$dsn = 'mysql:host=localhost;dbname=book_catalog';
$username = "php";
$password = "php";
$db = new PDO($dsn, $username, $password);
//get data
if(!is_null($_GET['order']) && $_GET['order'] != 'courseTitle')
{
$thesort = $_GET['order'];
$query = "Select * FROM book
INNER JOIN course
ON book.course = course.courseID
ORDER BY ".$_GET['order'];
}
else
{
$thesort = "courseTitle";
$query = "Select * FROM book
INNER JOIN course
ON book.course = course.courseID
ORDER BY $thesort";
}
//if page is null go to first page otherwise query for correct page
if (!is_null($_GET['page']))
{
$query = $query." LIMIT ".($_GET['page']*8-8).", 8";
}
else
{
$query = $query." LIMIT 0, 8";
}
//query result
$books = $db->query($query);
//get number of overall rows
$query2 = $db->query("SELECT * FROM book");
$count = $db->query("SELECT Count(*) As 'totalRecords' FROM book");
$count = $count->fetch();
$count = $count['totalRecords'];
?>
<table border =" 1">
<tr>
<th bgcolor="#6495ed"><a href="?order=course">Course #</th>
<th bgcolor="#6495ed"><a href="?order=courseTitle">Course Title</th>
<th bgcolor="#6495ed"><a href="?order=bookTitle">Book Title</th>
<th bgcolor="#6495ed"></th>
<th bgcolor="#6495ed"><a href="?order=price">Price</th>
</tr>
<?php foreach ($books as $book) : ?>
<tr>
<td><?php echo $book['course']; ?></td>
<td><?php echo $book['courseTitle']; ?></td>
<td><?php echo $book['bookTitle']; ?></td>
<td><?php
$bookcourse = $book['course'];
$isbn = $book['isbn13'];
$booklink = "<a href=\"course.php?course=$bookcourse&isbn=$isbn\">";
echo $booklink ;?><img src='images/<?php echo $book['isbn13'].'.jpg'; ?>'></a></td>
<td><?php echo $book['price']; ?></td>
</tr>
<?php endforeach; ?>
</tr>
</table>
<?php
//paging function... not sure if it works correctly?
for ($j=1; $j <= ceil($count/8); $j++)
{ ?>
<a href=<?php echo "?page=".$j."&order=".$thesort; ?>><?php echo $j; ?></a>
<?php
}?>
</body>
</html>
**course.php**
<?php
//get data from index.php
$course = $_GET['course'];
$isbn = $_GET['isbn'];
//connect to db
$dsn = 'mysql:host=localhost;dbname=book_catalog';
$username = "php";
$password = "php";
$db = new PDO($dsn, $username, $password);
//get data
$query = "Select * FROM book, course, author, publisher
WHERE book.isbn13 = $isbn AND book.course = '$course' AND book.course = course.courseID AND book.bookID = author.bookID AND book.publisher = publisher.publisherID
ORDER BY book.bookID";
//query results
$books = $db->query($query);
//error troubleshooting
if (!$books) {
echo "Could not successfully run query ($query) from DB: " . mysql_error();
exit;
}
//count the number of rows in the result
$results = $books->fetchAll();
$rowCount = count($book);
//get data from results
foreach($results as $book){
$bookID = $book['bookID'];
$bookTitle = $book['bookTitle'];
$isbn = $book['isbn13'];
$price = $book['price'];
$desc = $book['description'];
$publisher = $book['publisher'];
$courseTitle = $book['courseTitle'];
$courseID = $book['courseID'];
$credits = $book['credit'];
$edition = $book['edition'];
$publishDate = $book['publishDate'];
$length = $book['length'];
$firstName = $book['firstName'];
$lastName = $book['lastName'];
}
if($numrows > 1)
{
foreach ($books as $book)
{
$authorArray[] = $book['firstName'] + ' ' + $book['lastName'];
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>CIS Department Book Catalog</title>
</head>
<body bgcolor=white">
<table border="0">
<tr>
<td>
<img src='images/<?php echo $isbn.'.jpg'; ?>'>
</td>
<td>
<?php
echo "For Course: $courseID $courseTitle ($credits)";
echo "</br>";
echo "Book Title: $bookTitle";
echo "</br>";
echo "Price: $price";
echo "</br>";
echo "Author";
if ($numResults > 1)
{
echo "s:";
for ($i = 0; $i < $numResults; $i++)
{
if ($i!=0)
echo ", $authorArray[i]";
else
echo $authorArrat[i];
}
}
else
echo ": $firstName, $lastName";
echo "</br>";
echo "Publisher: $publisher";
echo "</br>";
echo "Edition: $edition ($publishDate)";
echo "</br>";
echo "Length: $length pages";
echo "</br>";
echo "ISBN-13: $isbn";
?>
</td>
</tr>
<tr>
<td colspan="2">
<?php echo "Description: $desc"; ?>
</td>
</tr>
</table>
</body>
</html>
You should be using isset not is_null to keep it from warning about undefined variables.
$books is never defined It was defined, just incorrectly ... foreach needs it to be an array. You really don't need it anyway, fetch each row into the array with a while loop. (see my example below). You're also redefining $count several times in your query.
And like #Brad said. Use prepared statements and placeholders. Your database will end up hacked with your current code.
EDIT
Answer to your question. query() returns a statement handle. (I've defined it as $sth). fetch() returns a result which you need to pass one of the fetch mode constants (or define it by default earlier with $db->setFetchMode())
To get the books you need to have
$books = array();
$sth = $db->query($query);
while( $row = $sth->fetch(PDO::FETCH_ASSOC) ) {
$books[] = $row; // appends each row to the array
}
Here's how your code should look to get a count.
// you're not using the $query2 you defined ... just remove it
$sth = $db->query("SELECT Count(*) As 'totalRecords' FROM book");
$result = $sth->fetch(PDO::FETCH_ASSOC);
$count = $result['totalRecords'];
Take a look at:
http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers Looks like a good guide to give you an in-depth understanding of how to use PDO. Pay special attention to error handling and to prepared statements!
I can't figure out how to format my table so that there is a header for each section of attributes. I only see one header when there are actually more that I need to see.
For example I'm able to get DROID 4 by MOTOROLA and all of it's attributes go from Full Retail Price to Voice Dialing. After Voice Dialing there should be a second header for another phone. Clearly my logic is messed up and I have been struggling for about 4 hours on it. I also need the two tables to be side by side, not in a long list like this.
This is what I'm trying to achieve:
My code looks like this:
<?
session_start();
if(!session_is_registered(myusername)){
header("location:main_login.php");
}
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="theme.css" />
</head>
<body>
<?php
include_once 'config.php';
$conf = new config();
mysql_connect($conf->getdbServ(), $conf->getdbUser(), $conf->getdbPwd()) or die(mysql_error());
mysql_select_db($conf->getDB()) or die(mysql_error());
$selectedPhones = $_POST['phones'];
$totalSelected = count($selectedPhones);
//echo $totalSelected;
$idList = "";
for($i=0;$i < $totalSelected; $i++){
$idList .= $selectedPhones[$i] . ",";
}
$idList = substr($idList,0,-1);
$query = "Select name from ".$conf->getproductTbl()." WHERE id='$idList'";
$res=mysql_query($query);
//echo $idList;
$data = mysql_query("SELECT ".$conf->getproductTbl().".id, ".$conf->getproductAttr().".* from ".$conf->getproductTbl()."
LEFT JOIN ".$conf->getproductAttr()." ON ".$conf->getproductTbl().".id=".$conf->getproductAttr().".prodFK
Where ".$conf->getproductTbl().".id IN(" . $idList . ");");
echo "<table width = 100% border = '1' cellspacing = '2' cellpadding = '0'>";
while ($result = mysql_fetch_assoc($res))
{
echo "<th colspan='2'>".$result["name"]."</th>";
}
while ($row = mysql_fetch_assoc($data)) {
echo "<tr><td>";
echo $row["Name"];
echo "</td><td>";
echo $row["value"];
echo "</td></tr>";
}
echo "</table>";
?>
</body>
</html>
1 - You might want to look into MYSQL JOIN to combine your two queries. (http://www.tizag.com/mysqlTutorial/mysqljoins.php)
2 - Use CSS to style your result set.
You can try something like this.. I hope that will help you.
<table>
<tr>
<?php
for($i=0;$i < $totalSelected; $i++){
//$idList .= $selectedPhones[$i] . ",";
?>
<td><?php
$data = mysql_query("SELECT ".$conf->getproductTbl().".id, ".$conf->getproductAttr().".* from ".$conf->getproductTbl()."
LEFT JOIN ".$conf->getproductAttr()." ON ".$conf->getproductTbl().".id=".$conf->getproductAttr().".prodFK
Where ".$conf->getproductTbl().".id = ".$selectedPhones[$i]);
echo "<table width = 100% border = '1' cellspacing = '2' cellpadding = '0'>";
while ($result = mysql_fetch_assoc($res))
{
echo "<th colspan='2'>".$result["name"]."</th>";
}
while ($row = mysql_fetch_assoc($data)) {
echo "<tr><td>";
echo $row["Name"];
echo "</td><td>";
echo $row["value"];
echo "</td></tr>";
}
echo "</table>";
?>
</td>
<?php }?>
</tr>
</table>