PHP MySQL query variables not returning - php

I store my testimonials in a database table and would like them to be displayed on my website via this for loop:
<?php
$count = mysql_fetch_assoc(mysql_query("SELECT COUNT(*) cnt FROM testimonials"));
for ($i = 1; $i <= intval($count['cnt']); $i++)
{
$sql = mysql_query("SELECT * FROM testimonials WHERE id='{$i}'");
?>
<li class="span4">
<div class="thumbnail thumbnail-1">
<section>
<a class="link-1" style="cursor:pointer;"><?php echo $sql['name'] ?></a>
<p><?php echo $sql['text'] ?></p>
<?php echo $sql['product'] ?>
</section>
</div>
</li>
<?php
}
?>
The issue is that the $sql variables product, name and text are not displaying. However the $count is getting the correct intval, so it knows there are entries.
It's also worth pointing out that the loop is working as I get the <li> <div> and <section> tags working, the only issue is the <a>'s and the <p> not getting the textual value from the echo
P.S. I know that mysql_* functions are depreciated however my php version 5.3 and they are only depreciated from 5.5 so they are ok for my website.

you missed to fetch second sql
add this line
$result= mysql_fetch_assoc($sql) ;
and then call your variables like that
<?php echo $result['name'] ; ?>
<?php echo $result['product'] ;?>
<?php echo $result['product'] ; ?>
^^-----dont forget `;` because you missed them also

Related

Print information from database table in shopping site

I tried my best but I stuck on this problem. Sorry for my bad english.
So here is the situation:
I am trying to make a little shopping site. My database table looks like this:
id pic titel desc price
1 gta5.png Grand Theft Auto 5 A open world game... 49.99
2 cod.png Call Of Duty: MW A Ego-Shooter game... 59.99
3 play4.png Playstation 4 Next-Gen Console... 249.99
4 contr.png Ps4 Controller Next-Gen Equipment... 69.99
On the Database Class file I have some function where I get the column information from the table:
public function getImg(){
while($row = mysqli_fetch_row($this->query)){
return $row[1];
}
}
public function getTitel(){
while($row = mysqli_fetch_row($this->query)){
return $row[2];
}
}
...
With getImg() I will get every information on the pic column like: gta5.png, cod.png etc.
My problem is starting here. I want to print out every column with a for loop on the index.php file. But I can't see any information. Here is the index.php file:
<ul>
<li>
<div class="container">
<div class="content">
<?php
for($i = 0; $i < $database->getTableLength(); $i++){
?>
<img src="image/<?php echo $database->getImg(); ?>"></img>
<h4><?php echo $database->getTitel(); ?></h4>
<h5><?php echo $database->getDesc(); ?></h5>
<h2><?php echo $database->getPrice(); ?>€</h2>
<input type="button" name="submit" value="Buy">
<?php
}
?>
</div>
</div>
</li>
</ul>
But as I said there is nothing. The getTableLength() function is the length of the table (In this case 4). I also tried to print it out one by one like this:
<ul>
<li>
<div class="container">
<div class="content">
<?php
for($i = 0; $i < $database->getTableLength(); $i++){
echo $database->getImg() . "<br>";
}
?>
</div>
</div>
</li>
</ul>
But again failed.. I can see even the br tag but not the information that I want to print out. When I put the echo line before the for loop, then I can see the first index of the column (gta5.png), but I want to have all columns.
Hope to see some solutions. Thanks for any kind of help!
EDIT:
It is working when I write 5 instead of the length function:
for($i = 0; $i < 5; $i++){
echo $database->getImg();
}
But I still want to use that function. The getTableLength() function isn't working as I expected. There is nothing to see when I insert the function. The getTable function looks like this:
public function getTableLength(){
$sql = "SELECT COUNT(*) AS num FROM `$this->table`";
$this->query = mysqli_query($this->connect, $sql);
if($this->query){
$row = mysqli_fetch_assoc($this->query);
return $row['num'];
}
}
When I call it on the index.php file like:
$database->getTableLength();
I can see nothing and everything is gone. It's like buggy.
Fixed. It was to complicated. Think simple and do it better..
Here is the solution:
<?php
$table = $database->getTableName();
$sql = "SELECT * FROM `$table`";
$connect = $database->getConn();
$result = mysqli_query($connect, $sql);
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result)){
?>
<form method="post" action="index.php?action=add&id=<?php echo $row["id"] ?>">
<ul>
<li>
<div class="container">
<div class="content">
<img src="image/<?php echo $row["bild"]; ?>"></img>
<h4><?php echo $row["titel"]; ?></h4>
<h5><?php echo $row["beschreibung"]; ?></h5>
<h2><?php echo $row["preis"]; ?>€</h2>
<input type="hidden" name="hidden_name" value="<?php echo $row["titel"]; ?>">
<input type="hidden" name="hidden_price" value="<?php echo $row["preis"]; ?>">
<input type="submit" name="add_to_cart" value="Kaufen">
</div>
</div>
</li>
</ul>
<?php

How to fix PHP/SQL search query only fetching one row of data instead of all associated rows?

I'm working on a little project and I want to be able to search my database for all items associated with my search
My problem is that when I use my code below, I get only one result rather than an array of all results that fit my query. I have seen some solutions that suggested using fetchAll() but that doesn't seem to output anything.
What the PHP query looks like.
if(isset($_POST['search'])){
if(preg_match("/^[a-zA-Z]+/", $_POST['sname'])){
$search = $_POST['sname']; //name in form
$pdo = & dbconnect();
$userid = $_SESSION['user_id'];
$sql = "SELECT * FROM movie_dets Where user_id=? and Title LIKE '%" .$search."%'";
$stmt=$pdo->prepare($sql);
$stmt->execute([$userid]);
if(!$stmt)
{
die("Database pull did not return data");
}
$row=$stmt->fetch();
}
}
Then I have a foreach loop in my html that looks like so
<div class="row">
<?php
$loop = 0;
foreach ($stmt as $row): //loop through result set ?>
<div class="column" >
<div>
<figure>
<img src="<?php echo "/.../".$row['Cover'] ?>" alt="<?php echo $row['Title']; ?> cover" />
<figcaption>
...
</figcaption>
</figure>
</div>
</div>
<?php
$loop++;
if ($loop % 4 ==0) //to display four results the wrap.
{
echo "</div> <div class='row'>";
}
?>
<?php endforeach ?>
</div>
In my database, there are two titles called frozen. This is supposed to output all rows when given the 'fr' search word. Instead, it only fetches one of them.

Mysqli query not working properly in if/else statement

I have a table in MySQL and I want to check in PHP whether there are any 'tasks' written (it's a todo list webapp). If there aren't I want to display a message 'You haven't added any tasks yet', problem is it's not displaying.
PHP is assuming that the list of tasks is never empty, when for user 1 (in PHP current user_id = 2), for instance, it is, since I haven't inserted any tasks in my MySQL for User 1 (all tasks are user 2).
<?php
global $connection;
$user = $_SESSION['user_id'];
$query = "SELECT * FROM to_do_list WHERE user = $user";
$items = mysqli_query($connection, $query);
?>
<div>
<?php if(!empty($items)): ?>
<ul id="myUL">
<?php foreach($items as $item): ?>
<li>
<span class="item<?php echo $item['done'] ? ' done' : '' ?>"><?php echo $item['task']; ?></span>
<?php if(!$item['done']): ?>
Done
<?php endif; ?>
</li>
<?php endforeach; ?>
</ul>
<?php else: ?>
<p>You haven't added any tasks yet.</p>
<?php endif; ?>
</div>
mysqli_query returns a "resource" not an array - so:
instead of foreach($items as $item): use while($item = mysqli_fetch_assoc($items))
and now every $item is an associated array of results (meaning - you can call the output using it's name like $item['done'])
also - instead of if(!empty($items)) you should use if(mysqli_num_rows($items) > 0)

PHP and MySQL dynamic query only returns results without where clause

I am hoping someone can assist with a dynamic query in PHP. The first page below is a page which displays a number of items from MySQL. Once an item is clicked on it goes to another page which queries the database to bring up the selected product details. The page displaying the items a user can select from works fine, but the page displaying the item clicked on only works if I remove the WHERE clause, but of course it is no longer dynamic then. The error statement is suggesting that the syntax is not right for the version, yet it works on the other page. Using MySQL 5.6.17 and PHP 5.5.12.
Can anyone see where it is that I have gone wrong here please?
---------------------------------
Main Page (functions as expected)
<?php
ini_set('display_errors', '0');
$message = '';
$db=new MySQLi('localhost', 'someone', 'xxx','abc');
if ($db->connect_error) {
$message = $db->connect_error;
} else {
$sql = 'SELECT * FROM items';
$result = $db->query($sql);
if ($db->error) {
$message = $db->error;
}
}
?>
<!--other parts of the site--->
<?php if ($message) { ?>
<h2 class="inline_block">Sorry, there seems to be a problem.</h2>
<?php } else { ?>
<div>
<?php
$i = 0;
while ($row = $result->fetch_assoc()) {
if ($i % 4 === 0) { ?>
<div>
<ul>
<?php } ?>
<li> <a href="includes/details.php?id=<?php echo $row['itemID']; ?>"> <img src="img/<?php echo $row['image']; ?>" alt="<?php echo $row['alt']; ?>" height="150" width="150">
<p><?php echo $row['product']; ?></p>
<p class="reset">From $<?php echo $row['water']; ?></p></a> </li>
<?php $i++;
if ($i % 4 === 0) { ?>
</ul>
</div>
<?php } // end if
} // end of loop ?>
</div>
</div>
<?php } // end of page ?>
</div>
<!--other parts of the site--->
-----------------------------------------------------------------
Dynamic Page (returns an SQL error "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1". Line 1 is the same first line as showing below. This is also used in the previous page without issue. When the WHERE clause is removed from the SQL query it works but is no longer dynamic. )
<?php
ini_set('display_errors', '0');
$message = '';
$db=new MySQLi('localhost', 'someone', 'xxx','abc');
if ($db->connect_error) {
$message = $db->connect_error;
} else {
$sql = 'SELECT * FROM items WHERE xitemID=' . $db->real_escape_string($_GET['xitemID']);
$result = $db->query($sql);
if ($db->error) {
$message = $db->error;
} else {
$row = $result->fetch_assoc();
}
}
?>
<!--other parts of the site--->
<ul>
<li>Home</li>
<li>Things</li>
<li>Mixeda</li>
<li><?php echo $row['product']; ?></li>
</ul>
</div>
<div id="col_1" role="main">
<?php if ($message) { ?>
<p> ERROR</p>
<?php echo "<p>$message</p>";
} else { ?>
<h2 class="inline_block"><?php echo $row['product']; ?></h2>
<p class="figure"><img src="../img/<?php echo $row['image']; ?>" alt="<?php echo $row['alt']; ?>" width="200" height="200">Price from $<?php echo $row['product']; ?></p>
</div>
<div id="col_2">
<h3>Details</h3>
<p><?php echo $row['details']; ?></p>
</div>
<?php } ?>
<!--other parts of the site--->
Note you need to put single quotes around the item in xitemID='itemHere':
$sql = "SELECT * FROM items WHERE xitemID='" . $db->real_escape_string($_GET['xitemID']) . "'";
That should fix your problem as long as $_GET['xitemID'] is defined.
You are concatenating an escaped
value outside your string.
$sql = 'SELECT * FROM items WHERE xitemID=' .
$db->real_escape_string($_GET['xitemID']);
This looks like a valid action however when xitemID is a character value, you still need to enclose it in quotes yourself.
Better is to use a prepared statement:
You are using MySQLi already, so:
$sql="SELECT * FROM items WHERE xitemID=?";
$pstmt=$db->prepare_statement($sql);
$pstmt->bind_param("s",$_GET['xitemID']);
$results=$pstmt->execute();
That way php takes care of any quoting etc and prevents eventual sql injection.

foreach mysql row from query echo out html with row values

So basicly what I'm trying to accomplish is that foreach row in mysql query it prints out the html with the data from that row. Here's what I have, it keeps giving me an error on my foreach.
<?php
$shots = mysql_query("SELECT * FROM shots") or die(mysql_error());
while($row=mysql_fetch_array($shots))
$data[]=$row;
foreach($shots as $data)
if (!empty($data)){
$id = $data["id"];
$shotby = $data["shot"];
$passby = $data["pass"];
$time = $data["time"];
?>
<div class="feedbody">
<div class="title"><?php echo $shotby; ?></div>
<div class="feed-data">: gets a pass from <span><?php echo $passby; ?</span> and he takes a shot!</div>
<img class="dot" src="images/dot.png" />
</div>
<?php
}
}
?>
Or something like that. Can anybody help point me in the right direction. I've been trying to find the answer.
EDIT: adding the error as requested.
Warning: Invalid argument supplied for foreach() in /home/content/93/7527593/html/fusionboard/includes/feed.php on line 7
First, if you want to access the data by name (instead of index), you need to include MYSQL_ASSOC as a second parameter to mysql_fetch_array, or use mysql_fetch_assoc.
Not really sure why you were copying the MySQL results to a second array just to loop through that later - you can loop through the results directly:
<?php
$shots = mysql_query("SELECT * FROM shots") or die(mysql_error());
while($row = mysql_fetch_assoc($shots)) { ?>
<div class="feedbody">
<div class="title"><?php echo $row["shot"]; ?></div>
<div class="feed-data">: gets a pass from <span><?php echo $row["pass"]; ?></span> and he takes a shot!</div>
<img class="dot" src="images/dot.png" />
</div>
<?php } ?>
Update after you posted the error message: the error from your original code was that you first went through and copied each result row into $data, but then in your foreach you tried to loop on $shots (again) and have it call each item $data.
What you probably wanted to do was have foreach ($data as $item) and then copy the properties from $item.
Something like this?
<?php
$shots = mysql_query("SELECT * FROM shots") or die(mysql_error());
while($row=mysql_fetch_assoc($shots))
{
$id = $row["id"];
$shotby = $row["shot"];
$passby = $row["pass"];
$time = $row["time"];
?>
<div class="feedbody">
<div class="title"><?php echo $shotby; ?></div>
<div class="feed-data">: gets a pass from <span><?php echo $passby; ?</span> and he takes a shot!</div>
<img class="dot" src="images/dot.png" />
</div>
<?php
}
?>
Perhaps you need another closing brace? (Another "}" at the end, I mean).
You saved your data in the $data variable, but your foreach uses the $shots variable.
Just change it to foreach($data as $something) and $something["id"] (for example) to retrieve a value
you are using one variable instead of another.
and many useless code.
while youneed only
<?php foreach($data as $row) { ?>
<div class="feedbody">
<div class="title"><?php echo $row['shotby'] ?></div>
<div class="feed-data">:
gets a pass from <span><?php echo $row['passby'] ?</span> and he takes a shot!
</div>
<img class="dot" src="images/dot.png" />
</div>
<?php } ?>

Categories