I have a single div and a unknown number(say n) of rows of data. i need to show that data on my html cards
and these cards are to be generated dynamically by the output value(n).
say if i have 10 rows of data.my div element needs to be created 10 times and each row data is to be displayed on each div
by the way i am using PHP for backend.
here is my codes
This is my div
<div class="row">
<div class="column">
<div class="card">
<h1><?php echo"$value"; ?></h1>
<h3><?php<?php echo"$description";?></h3>
</div>
</div>
</div>
and this is my php code
<?php
$conn=new mysqli("localhost","root","","programmingpioneers");
if(!$conn)
{
echo "connection_failed";
}
else{
//echo "sucess";
}
$query= "select title,description from problems where difficulty='hard'";
$result=mysqli_query($conn,$query);
$row=mysqli_fetch_array($result);
if (mysqli_query($conn, $query))
{
echo "sucess<br>";
while ($row=mysqli_fetch_array($result)) {
$title=$row[0];
$description=$row[1];
echo "$title <br> $description";
}
}
else {
echo "Error: " . $query . "<br>" . mysqli_error($conn);
}
?>
if i try to but my div inside
echo"$title <br>$description";
it is throwing the following error
Parse error: syntax error, unexpected 'row' (T_STRING), expecting ';' or ',' in C:\xampp\htdocs\myapp\useless.php on line 19
Use loop in the div you want to have again and again.Please check the code if it works for you.
enter image description here
enter image description here
Without having all your data available I'm unable to test it, but this should be the correct way of doing it. I left comments in the code and removed a bunch of syntax errors that you made:
<?php
// Create MySQLi object
$conn = new mysqli("localhost","root","","programmingpioneers");
// Verify MySQL connection
if ($conn->connect_errno) {
echo "Failed to connect to MySQL: (" . $conn->connect_errno . ") " . $conn->connect_error;
}
// Query
$query = "SELECT title,description FROM problems WHERE difficulty = 'hard'";
// Run query
if($result = $conn->query($query)) {
// Loop through query results
while ($row = $result->fetch_assoc()){
echo "<div class='row'>";
echo "<div class='column'>";
echo "<div class='card'>";
echo "<h1>". $row['title'] ."</h1>";
echo "<h3>". $row['description'] ."</h3>";
echo "</div></div></div>";
}
// Output query errors
} else {
echo "Failed to select title, description: (" . $conn->errno . ") " . $conn->error;
}
// Close the MySQLi connection
$conn->close();
?>
Related
Hi,
i am coding a homepage to learn php and javascript. I decided to use a livesearch using jQuery and php.
It is working well ,but i wonder how i can integrate to the found titles an onclick function that will redirect to the viewpost.php so it opens the clicked title and opens the post.
My HTML search part on index page:
<!-- Search Widget -->
<div class="card my-4">
<div class="card bg-success">
<h5 class="card-header">Search</h5>
<div class="card-body">
<div class="search-box">
<input type="text" autocomplete="off" placeholder="Search country..." />
<div class="result"></div>
</div>
</div>
</div>
</div>
jQuery part for livesearch that redirect to php page(backend-search.php)
<script type="text/javascript">
$(document).ready(function(){
$('.search-box input[type="text"]').on("keyup input", function(){
/* Get input value on change */
var inputVal = $(this).val();
var resultDropdown = $(this).siblings(".result");
if(inputVal.length){
$.get("backend-search.php", {term: inputVal}).done(function(data){
// Display the returned data in browser
resultDropdown.html(data);
});
} else{
resultDropdown.empty();
}
});
// Set search input value on click of result item
$(document).on("click", ".result p", function(){
$(this).parents(".search-box").find('input[type="text"]').val($(this).text());
$(this).parent(".result").empty();
});
});
</script>
PHP backend-search.php
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
require_once "pdoconfig.php";
// Attempt search query execution
try{
if(isset($_REQUEST["term"])){
// create prepared statement
$sql = "SELECT * FROM articles WHERE title LIKE :term";
$stmt = $db->prepare($sql);
$term = $_REQUEST["term"] . '%';
// bind parameters to statement
$stmt->bindParam(":term", $term);
// execute the prepared statement
$stmt->execute();
if($stmt->rowCount() > 0){
while($row = $stmt->fetch()){
echo "<p>" . $row["title"] . "</p>";
}
} else{
echo "<p>No matches found</p>";
}
}
} catch(PDOException $e){
die("ERROR: Could not able to execute $sql. " . $e->getMessage());
}
// Close statement
unset($stmt);
// Close connection
unset($db);
?>
That is my table structure called articles:
id title content categorie_id pubdate views short_details
And finally my viewpost.php
<?php
$stmt = $db->prepare('SELECT id, title, text, pubdate FROM articles WHERE id = :id');
$stmt->execute(array(':id' => $_GET['id']));
$row = $stmt->fetch();
//if post does not exists redirect user.
if($row['id'] == ''){
header('Location: ./');
exit;
}
echo "<br>";
echo "<div class='card mb-4'>" . "<div class='card-body'>";
echo "<h2 class='card-title'>";
echo $row['title'] . "</h2>";
echo "<div class='card-footer text-muted'>";
echo $row['pubdate'];
echo "</h2>";
echo "<p class='card-text'>";
echo $row['text'];
echo "</p>";
echo '</div>';
?>
Do i need to get the articles id with the jQuery and somehow post it onclick to viewpost.php ?
I do appreciate all help ..
You Need To Change This PHP "backend-search.php" File :
This Code To
if($stmt->rowCount() > 0)
{
while($row = $stmt->fetch())
{
echo "<p>" . $row["title"] . "</p>";
}
}
else
{
echo "<p>No matches found</p>";
}
This Code
if($stmt->rowCount() > 0)
{
while($row = $stmt->fetch())
{
echo "<p>". $row["title"] . "</p>";
}
}
else
{
echo "<p>No matches found</p>";
}
I have a database set up with several records and a table that displays each row of the record. For each row of the table, the only information that are displayed are the 'name', 'program' and 'course' taken from 'personal' and 'faculty' tables. I'm trying to add a button on each row that will retrieve and show all information regarding that specific row. here are my codes
<?php
$conn = mysqli_connect("localhost", "root", "", "project");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, Full_Name, Program, Course FROM personal, faculty";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo . $row["id"]. . $row["Full_Name"] .
. $row["Program"]. $row["Course"]. ;
}
} else { echo "0 results"; }
$conn->close();
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
</html>
Add a <a href link to each ID as it is output. I made up a name for the program to be called since you didn't tell us what it is.
while($row = $result->fetch_assoc()) {
echo '<a href="showdetails.php?id=' . $row['id'] . '">' .
$row['id'] . '</a>' .
$row['Full_Name'] .
$row['Program'] .
$row['Course'];
}
In my dropdown list, i put all the "pack_name(s)" the user has posted and I display it all in the list for the user to select and update. So when the user selects one and hits submit, i want to get that "value" submitted and use it for later purposes but ive been researching and only found "pre-set" values with html and the value was given using Jquery. So i wondering if its possible to basically take the "pack_name" selected and when the user hits submit, echo out the selected value.
PHP
<?php
session_start();
if(empty($_FILES) && empty($_POST) && isset($_SERVER['REQUEST_METHOD']) && strtolower($_SERVER['REQUEST_METHOD']) == 'post'){ //catch file overload error...
$postMax = ini_get('post_max_size'); //grab the size limits...
echo "<p style=\"color: #F00;\">\nPlease note files larger than {$postMax} will result in this error!</p>"; // echo out error and solutions...
return $postMax;
}
if(isset($_COOKIE['id'])){
if($_SESSION['came_from_upload'] != true){
setcookie("id", "", time() - 60*60);
$_COOKIE['id'] = "";
header("Location: developerLogin.php");
exit;
}
try{
// new php data object
$handler = new PDO('mysql:host=127.0.0.1;dbname=magicserver', 'root', '');
//ATTR_ERRMODE set to exception
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
die("There was an error connecting to the database");
}
$userid = $_SESSION['id'];
$stmt = $handler->prepare("SELECT * FROM pack_profile WHERE pack_developer_id = :userid");
$stmt->bindParam(':userid', $userid, PDO::PARAM_INT);
$stmt->execute();
echo "<select>";
while($result = $stmt->fetch()){
echo "<option>" . $result['pack_name'] ."</option>";
}
echo "</select>";
if($_SERVER['REQUEST_METHOD'] =="POST"){
$token = $_SESSION['token'];
}
}
?>
You need to give the select element a name attribute, and give each option element a value attribute.
For example:
echo "<select name=\"pack\">";
while($result = $stmt->fetch()){
echo "<option value=\"" . $result['pack_name'] . "\">" . $result['pack_name'] ."</option>";
}
echo "</select>";
Of course you should be escaping anything which could contain &, < or " with something like htmlspecialchars().
So I am creating an inbox in PHP and It displays Mail Id and Subject.
If you click that division(containing mail id and subject), it opens up a new page, read. PHP where the body and attachments are displayed.
I am facing some problem in getting to know which division is being clicked and how to display the mail of that particular person.
My concerned code is:
<?php
$conn = connect(); //Connects to the database
$sql = "select senderId, subject, body, attachment from mail where receiverId = '".$_SESSION["Email"]."' ";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
echo "<div class='mail' onclick='location.href=`read.php`;'>";
echo $row["senderId"] . " - " . $row["subject"];
echo "</div>";
echo "<hr />";
}
$conn->close();
?>
I have an idea of storing the variables using SESSION as:
if (isset($_GET['div'])) {
$_SESSION["body"] = $row["body"];
$_SESSION["attachment"] = $row["attachment"];
}
But where do I place the latter part of the code and suggest me if I can make an modifications please.
You can echo out the id during the while loop iteration.
echo "<div class='mail' onclick='location.href=`read.php?id=". $row['id'] ."`;'>";
And inside the read.php file, you can then grab that value by using $_GET['id'].
i am creating a form through php html and ajax that is specific for each row of a database table. I send the form data through ajax to another page which then takes that form data and uses it to pull data from another database based upon the results given and displays them.
I am fairly sure the problem is either with my select statement on the recipedisplay.php page or my syntax is wrong on how to echo out a returned variable.
select.php
<?php <script>
$('.button').click(function (e){
e.preventDefault();
var id = $(this).attr('id');
$.ajax({
type: 'POST',
url: 'pages/recipes/recipedisplay.php',
data: $('#f'+id).serialize(),
success: function(d){
$('#infodisplay').html(d);
}
});
});
</script>
<div id=\"a".$row['id']."\">
<form id=\"f" . $row['id'] . "\">
<input type=\"hidden\" name=\"recipeid\" id=\"recipeid\" value=\"" . $row['id'] . "\">
<div id=\"reciperesultbutton\" class=\"button\"><div id=\"centering\">" . $row['name'] ." </div></div>
<div id=\"reciperesulttext\"> " . $row['id'] ." " . $row['longdesc'] ."</div>
</form>
<br>
</div>
";
}
?>
recipedisplay.php
<?php
$con=mysqli_connect("localhost","test","test","test");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$id = mysqli_real_escape_string($con, $_POST['recipeid']);
$sql= "SELECT * FROM recipes WHERE 'id' ='".$id."'";
$row = mysqli_fetch_array($sql);
$name = $row['name'];
$longdesc = $row['longdesc'];
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
echo " fail ";
echo " . $name . ";
};
echo " . $id . ";
echo " work ";
echo " . $longdesc . ";
echo "$row[name]";
mysqli_close($con);
?>
The problem is in :
$row = mysqli_fetch_array($sql);
because mysqli_fetch_array() takes mysqli_query() result not your $sql query
So try to run your query first by this code :
mysqli_query($con,$sql);
$row = mysqli_fetch_array($mysqli_query);
Also you can use mysqli_fetch_assoc() that takes mysqli_query() too as a parameter