MySQL/PHP foreach still only displaying first in database - php

I am querying results from a database, where more than one result should be queried. However, when I tried displaying the result of the query, only one result showed, so I tried to use a foreach function, but it's still not working. I'm beat, no idea what I'm doing wrong. Anyone have a good idea of what's going wrong?
Here's the MySQL query code:
<?php
//Database Information
$dbhost = "";
$dbname = "";
$dbuser = "";
$dbpass = "";
//Connect to database
mysql_connect ( $dbhost, $dbuser, $dbpass)or die("Could not connect: ".mysql_error());
mysql_select_db($dbname) or die(mysql_error());
$filename = $_GET['filename'];
$new_captions = mysql_query("SELECT * from captions where image = 'http://math.stanford.edu/inc/img/PalmDrive.png' ORDER BY idnum DESC LIMIT 5");
while($rows = mysql_fetch_array($new_captions)){
$caption = $rows;
}
?>
And here's the foreach:
<?php foreach($caption as $rows) {?>
<div id="set_caption" style="width:<?php echo $caption['width'];?>px; height:<?php echo $caption['height'];?>px; left:<?php echo $caption['posleft'];?>px; top:<?php echo $caption['postop'];?>px;"><?php echo $caption['text'];?></div>
<?php } ?>

I think $caption is an array, so your code should be like this
while($rows = mysql_fetch_array($new_captions)){
$caption[] = $rows;
}
EDIT:
Your foreach loop is also wrong.
Your variable is $rows not $caption.
<div id="set_caption" style="width:<?php echo $rows['width'];?>px; height:<?php echo $rows['height'];?>px; left:<?php echo $rows['posleft'];?>px; top:<?php echo $rows['postop'];?>px;"><?php echo $rows['text'];?></div>
<?php } ?>

You have following mistakes.
$caption is not declare before.
use array_push or $caption[] = $rows; to make caption array.
Use $row variable in the foreach.
//Database Information
$dbhost = "";
$dbname = "";
$dbuser = "";
$dbpass = "";
//Connect to database
mysql_connect ( $dbhost, $dbuser, $dbpass)or die("Could not connect: ".mysql_error());
mysql_select_db($dbname) or die(mysql_error());
$filename = $_GET['filename'];
$new_captions = mysql_query("SELECT * from captions where image = 'http://math.stanford.edu/inc/img/PalmDrive.png' ORDER BY idnum DESC LIMIT 5");
$caption = array();
while($rows = mysql_fetch_array($new_captions)){
$caption[] = $rows;
}
foreach($caption as $row) {
<div id="set_caption"
style="width:<?php echo $row['width'];?>px;
height:<?php echo $row['height'];?>px;
left:<?php echo $row['posleft'];?>px;
top:<?php echo $row['postop'];?>px;">
<?php echo $row['text'];?>
</div>
}

Related

echo something out MySQL database

I am trying to get a question with answers out of my database. I just want to get one thing out of the database and not with a row. I thought this would work but it puts out this: Resource id #4 can someone explains what I am missing.
Thanks :)
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db('lotto');
$sql = 'SELECT id, vraag, AntwA, AntwB, AntwC, AntwD FROM vraag1';
$test = mysql_query($sql);
echo $test;
?>
As said at least 10000 times everywhere in internet, never use MySQL_ ! (If your are trying to learn something new by using tutorials over internet, don't use old ones)
I recommend to use PDO which is modern API in PHP and a lot more secure when using it correctly with prepared statement ! But you can also use MYSQLI which is more similar to the MYSQL !
You have to export your data from return array :
Using PDO :
$db = new PDO ("mysql:host=".$hostname.";dbname=".$dbname, $username, $password);
$query = $db -> prepare ("SELECT * FROM vraag1");
$query -> execute (array ());
$rows = $query -> fetchAll (PDO::FETCH_ASSOC);
foreach ($rows as $row)
{
echo $id = $row["id"];
echo $vraag = $row["vraag "];
echo $AntwA = $row["AntwA "];
echo $AntwB = $row["AntwB "];
echo $AntwC = $row["AntwC "];
echo $AntwD = $row["AntwD "];
}
Using MYSQLI :
$db = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
$query = "SELECT * FROM vraag1";
$rows = mysqli_query($db, $query);
while($row = mysqli_fetch_assoc($rows))
{
echo $row["id"];
echo $row["vraag"];
echo $row["AntwA"];
echo $row["AntwB"];
echo $row["AntwC"];
echo $row["AntwD"];
}
First of all the mysql function you are using is depreciated and no longer supported. you should use mysqli or pdo instead with prepared statements.
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "lotto";
// Create connection
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT id, vraag, AntwA, AntwB, AntwC, AntwD FROM vraag1";
$test = mysqli_query($conn, $sql);
if (mysqli_num_rows($test) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($test)) {
echo "ID : ".$row['id']."<br>";
echo "vraag :".$row['vraag']."<br>";
echo "AntwA :".$row['AntwA']."<br>";
echo "AntwB :".$row['AntwB']."<br>";
echo "AntwC :".$row['AntwC']."<br>";
echo "AntwD :".$row['AntwD']."<br>";
}
} else {
echo "no results found";
}
mysqli_close($conn);
?>
For select function mysql_query() returns a resource on success, or FALSE on error.
so your assignment statement
$test = mysql_query($sql);
assign the resource to $test.
if you want the data inside the resource you can do
while($row= mysql_fetch_assoc($test)):
print_r($row);
endwhile;
also you can access the $row['column_name']
If you want to return only one row you can do this limit in query
$sql = 'SELECT id, vraag, AntwA, AntwB, AntwC, AntwD FROM vraag1 limit 1';
You need to add something like the following:
while($row = mysql_fetch_array($result)){
echo $row['id'];
echo $row['vraag'];
echo $row['AntwA'];
echo $row['AntwB'];
echo $row['AntwC'];
echo $row['AntwD'];
}
use mysqli instead of mysql
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
mysqli_select_db('lotto');
$sql = 'SELECT id, vraag, AntwA, AntwB, AntwC, AntwD FROM vraag1';
$test = mysqli_query($sql);
echo $test;
?>

How to show table from MySQL database using php and html

I am trying to connect my html page with MySQL database to show data from one specific table to my page, but I always get an error actually it just goes to die part of an SQL code. I am really new to PHP programming so please can someone help me, what am I doing wrong?
Here is my code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>AJDE</title>
</head>
<?php
$servername = "localhost";
$username = "******";
$password = "*****";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$query = "select * from PERCENTILE";
$result = mysqli_query($conn,$query);
if(!$result) {
die ("Umro!");
}
/* close connection */
$mysqli->close();
?>
<body>
</body>
</html>
Thank you!
Do you want to show the table as a HTML table or just an array?
The following is what I did to display my table as a HTML table:
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '*****';
$dbname = 'dbname';
$selectedTable = 'whateverTableYouWant';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname);
if (!$conn){
die('cannot connect to mysql');
}
$query = "SELECT * FROM $selectedTable";
if ($result = mysqli_query($conn , $query)) {
echo("<div class = 'data_wrapper'>");
// Display Header of the table
$fieldcount=mysqli_num_fields($result); //value = number of columns
$row = mysqli_fetch_assoc($result); //Fetch a result row as an associative array:
//array to string conversion
echo("<table id='example' class='table table-striped table-bordered' cellspacing='0' width='100%'>");
echo("<thead> <tr>");
foreach($row as $item){
echo "<th>" .$item. "</th>";
}
echo("</tr> </thead>");
//Footer
echo("<tfoot> <tr>");
foreach($row as $item){
echo "<th>" .$item. "</th>";
}
echo("</tr> </tfoot>");
//Display Data within the table
echo("<tbody>");
while ($row = mysqli_fetch_assoc($result)){
echo "<tr>";
foreach ($row as $item){
echo "<td contenteditable = 'true'>" . $item . "</td>"; //Change contenteditable later
//Editable data should be constricted, int = numbers only, string = words, date = date
}
echo "</tr>";
}
echo("<tbody>");
echo "</table>";
echo("</div>");
}
The following is just displaying as an array:
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '*****';
$dbname = 'dbname';
$selectedTable = 'whateverTableYouWant';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname);
if (!$conn){
die('cannot connect to mysql');
}
$query = "SELECT * FROM $selectedTable";
if ($result = mysqli_query($conn , $query)) {
while ($row = mysqli_fetch_array($result)){
print_r($row);
}
}
Please change the connection string like mentioned below.
<?php
$con = mysqli_connect("localhost","username","password","dbname");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
Please let me know if you've any queries.
I Think you need to select a database where you will run the query:
Try with this code:
<?php
$username = "your_name";
$password = "your_password";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
//select a database to work with (so replace the database name examples)
$selected = mysql_select_db("examples",$dbhandle)
or die("Could not select examples");
//execute the SQL query and return records
$result = mysql_query("SELECT * FROM PERCENTILE");
//fetch the data from the database and display results
//replace id,name,year with the columns you have on your table PERCENTILE and you want to show
while ($row = mysql_fetch_array($result)) {
echo "ID:".$row{'id'}." Name:".$row{'name'}."Year: ". $row{'year'}."<br>";
}
//close the connection
mysql_close($dbhandle);
?>
Hope it helps,
Vince.

How to retrieve images from database in php

I have a database which has a table called 'propImages' and there are two columns.- 'pid' and 'location'.
And i have data in the database where multiple images can contained by single pid.
image contains database data
now i want to retrieve images from database according to given pid. there can be more than one image.
All i know it there should be an iteration to retrieve images.
I want to display images in HTML .
can you please show me the way to do it in php?
Thanks in advance guys
This may help you
<?php
include 'inc/database.php';
$conn = new mysqli($servername, $username, $password, $database);
$propid = $_GET['propid'];
$sql = "SELECT * FROM propImages WHERE propid='" . $propid . "';";
$result = $conn->query($sql);
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<img src=" . $row['image'] . ">";
}
}
else {
echo "No results";
}
?>
in the inc/database.php :
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "database";
?>
To see how it works try visiting : file.php?propid=22
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "databasename";
// Create connection
$con = mysqli_connect($servername, $username, $password, $dbname);
//create sql
$sql = "SELECT * FROM `propImages` where pid='$YOUR_PID'";
$result = mysqli_query($con, $sql);
$row = mysqli_num_rows($result);
//retrive data print here
if($row > 0){
while($col = mysqli_fetch_assoc($result))
{
echo $col['location'];
}
} else {
echo 'no result found.';
}
?>
wish it helps

How to delete a record from mysql using a button?

I would like to be able to delete a row using the delete-button I display at the end of each row. I need two queries to delete a person from my database completely since I have a n-m relationship between Persons and Functions.
The queries are as follows:
delete from `Persons` where `Person ID` = '1';
I would like to implement these queries using the delete-button provided in the actual code, how can I do this?
UPDATE:
I made changes according to what Kristian Hareland wrote, and it reloads but the person isn't deleted, what should be changed to make it work?
showall.php:
<table>
<thead>
<tr>
<?php
// Variables
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "root";
$dbname = "CISV";
$dberror1 = "Could not connect to database: ";
$dberror2 = "Could not select database: ";
$dberror3 = "Could not execute query: ";
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ($dberror1 . mysql_error());
$select_db = mysql_select_db('CISV') or die ($dberror2 . mysql_error());
$query = "SELECT p.`Person ID`, p.`First Name`, p.`Last Name`, p.Gender, p.`Date Of Birth`, p.Email, p.`Phone Number`, c.Region, c.Country, p.`Delegation ID`
FROM Persons as p, Chapters as c
WHERE c.`Chapter ID`=p.`Chapter ID`
ORDER BY p.`Delegation ID";
$result = mysql_query($query) or die($dberror3 . mysql_error());
$row = mysql_fetch_assoc($result);
foreach ($row as $col => $value) {
echo "<th>";
echo $col;
echo "</th>";
}
?>
</tr>
</thead>
<tbody>
<?php
mysql_data_seek($result, 0);
while ($row = mysql_fetch_assoc($result)) {
?>
<tr>
<?php
foreach($row as $key => $value){
echo "<td>";
echo $value;
echo "</td>";
}
?>
<td>Delete</td>
</tr>
<?php } ?>
DeletePerson.php:
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "root";
$dbname = "CISV";
$dberror1 = "Could not connect to database: ";
$dberror2 = "Could not select database: ";
$dberror3 = "Could not execute query: ";
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ($dberror1 . mysql_error());
$select_db = mysql_select_db('CISV') or die ($dberror2 . mysql_error());
$UserId = mysql_real_escape_string($_GET['id']);
if(isset($UserId)){
//DELETE QUERY
$Del = mysql_query("DELETE FROM `Persons` WHERE `Person ID` = '$UserId'");
if($Del){
$Flag = TRUE;
}
else{
$Flag = FALSE;
}
header("Location: /showall.php?delete=$Flag");
}
else{
die("Error");
}
I would use JavaScript and Ajax here.
Make a Html-button with an onclick function like delete_user();
delete_user() calls a .php file to validate the rights and execute some mysql-delete promts.
The .php file returns a boolean to the JavaScript.
You could catch that boolean up and inform the user about the result.
IMHO best way is create separate file functions.php
<?php
//functions.php
$id = filter_this($_POST[id]);
mysql_query("delete from Persons_Functions where `Person ID` = '$id');
?>
and send there via JQuery:
function deleteuser(id){
$.post("admin_action.php", {action:'delete_user',id:id}, function(data){
if(data.trim()=="done"){
console.log("OK!");
});
}}
Without JS You can use HTML (just change BUTTON to A):
<a href='script.php?action=delete&id=12'>DELETE</a>
and PHP:
$id = $_GET[id];//filter this value
mysqli_query($link, "DELETE FROM users WHERE ID='$id'"); //use mysqli
I would use the GET method for this
<?php foreach ($results as $result): ?>
Delete
<?php endforeach; ?>
At the top of index.php
if (isset($_GET['action']) && $_GET['action'] == 'delete') {
if (isset($_GET['id']) && intval($_GET['id']) != 0) {
$id = intval($_GET['id']);
$stmt = "delete from table where id='{$id}'";
}
}
Just use a link:
<tbody>
<?php
mysql_data_seek($result, 0);
while ($row = mysql_fetch_assoc($result)) {
?>
<tr>
<?php
foreach($row as $key => $value){
echo "<td>";
echo $value;
echo "</td>";
}
?>
<td>Delete</td>
</tr>
<?php } ?>
</tbody>
DeletePerson.php:
<?php
$UserId = mysql_real_escape_string($_GET['id']);
if(isset($UserId)){
//DELETE QUERY
mysql_query("DELETE FROM Persons WHERE Person ID = '$UserId'");
mysql_query("DELETE FROM Persons_Functions WHERE Person ID = '$UserId'");
header("Location: /showall.php?flag=deleted");
}
else{
die("Error");
}

mysql_fetch_array($result) echo $rows in html

So I have these specific rows that I'm pulling if a code matches the database but I have no idea on how to echo this to my full html, is there anyway to make this $rows a $_POST or $_get to html?
thanks
<?php
$db_hostname = 'localhost';
$db_database = 'codedb';
$db_username = 'root';
$db_password = '';
$table = 'users';
$field = 'code';
$test = 'first_name';
// Connect to server.
$connection = mysql_connect($db_hostname, $db_username, $db_password) OR DIE ("Unable to
connect to database! Please try again later.");
// Select the database.
mysql_select_db($db_database,$connection)
or die("Unable to select database: " . mysql_error());
$query = "SELECT * FROM $table WHERE $field = '{$_GET["qcode"]}'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0) {
while($row = mysql_fetch_array($result)) {
$name = $row["$field"];
$test = $row["$test"];
echo "Hello: $name $test";
}
} else {
echo "error msg";
}
mysql_close($connection);
?>
You just need to update your while loop
Following code is to create your result Array, by that result array you can use the values in HTML too.
$resArr = array();
while($row = mysql_fetch_array($result)) {
$resArr[] = $row;
}
echo "<pre>";print_R($resArr);exit;
try
$query = "SELECT * FROM '$table' WHERE '$field' = '".$_GET["qcode"]."'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0)
{
while($row = mysql_fetch_assoc($result))
{
$name1 = $row[$field];
$test1 = $row[$test];
echo "Hello:" .$name1. $test1;
}
}
else { echo "error msg"; }
Also use mysql_real_escape_string() to prevent sql injection or better to use mysqli or PDO
You have two alternatives :
i) Use a .php file and write the html part there. This way you run php code with simple, php tags and display stuff where you need.
example :
Create a file called test.php and put this code in it and run.
</head>
<body>
<?php
$db_hostname = 'localhost';
$db_database = 'codedb';
$db_username = 'root';
$db_password = '';
$table = 'users';
$field = 'code';
$test = 'first_name';
// Connect to server.
$connection = mysql_connect($db_hostname, $db_username, $db_password) OR DIE ("Unable to
connect to database! Please try again later.");
// Select the database.
mysql_select_db($db_database,$connection)
or die("Unable to select database: " . mysql_error());
$query = "SELECT * FROM $table WHERE $field = '{$_GET["qcode"]}'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0)
{
while($row = mysql_fetch_array($result)) {
$name = $row["$field"];
$test = $row["$test"];
echo "<p>".$name." ".$test."</p>";
}
}
else { echo "error msg"; }
mysql_close($connection);
?>
</body>
</html>
This example puts the content in a paragraph in the html.
ii) echo the content from php by encoding it JSON and receive it using jquery from your html form. I'll not elaborate on this since it is not in the scope of the question.
And DO REMEMBER TO USE THE mysql_real_escape_string() to keep your code robust and prevent sql injection.

Categories