I want to show some titles for two users in each of their "profile div".
Let's say there are five titles belonging to user 1 and only two titles belonging to user 2.
The titles are in a table which I joined through user id.
How can I know when the titles foreign key (the user id) switches from one to two? in other words, how can I check for when I start echoing titles for a new user.
I want to implement a new div when the switch is made, so that the titles belonging to user one can be found in his div, and so on for the other user(s)
Below is my query, it works fine showing my data.
For the sake of simplicity I used an example of two users, but in the future I would have more than two users.
$result = mysqli_query($con,$sqltwo)or die(mysqli_error());
while($row = mysqli_fetch_array($result)) {
echo $row['title'];
echo $row['user_id'];
//I want to echo a new div here when the user_id switches to new
value
//and then echo the new titles data for the new user_id.
echo "<br>";
}
EDIT: A succesful scenario would be an output that looked something like this:
<div class="userone">
title1<br>
title2<br>
title3<br>
title4<br>
title5<br>
</div>
<div class="usertwo">
title6<br>
title7<br>
</div>
It can be done with a basic algorithm :
$current_id = '';
while ($row = mysqli_fetch_array($result)) {
if ($current_id != $row['user_id']) {
//new user detected
$current_id = $row['user_id'];
}
}
And so to fit your needs :
$current_id = '';
while ($row = mysqli_fetch_array($result)) {
if ($current_id != $row['user_id']) {
//ignore the first instance where no div has been created yet
if ($current_id != '') {
echo '</div>';
}
echo '<div class = "user'.$row['user_id'].'">';
$current_id = $row['user_id'];
}
//fill your div with your stuff from current user
echo $row['title'] . '<br>';
}
//check if you have at least one row to deal with, and then close the last opened div
echo '</div>';
Related
The title is not most suitable, but this is the best I could think of. Feel free to suggest EDIT.
Summary:
I have come from Android development where I have used RecyclerView to show a grid of various items from the database. There I could use the onClickListener()and Position to get which RecyclerView item (first,second,third..) is clicked by user and can proceed with actions.
Set up:
I am new to web development and by far I have managed to create an HTML table and I am firing appropriate query to get items from the database. I am then showing these data from database in each table cell. The data consists of image link (from a folder in same directory) and other text data about that image. My table looks something like this. Click here
Problem:
I want to add an options like Accept in each cell of the table such that when user clicks on that, a query fires to set the Boolean isAccepted for that item in DB as true. I can manage the query part but I am facing problem how to set this up in my php script.
What do I ecpect?
That's absolutely OK if I dont get the ready made code. I want to be guided as what technology to be used and if possible a link to the guiding tutorial. I hope it can be done usng PHP and HTML only.
My php script:
<table id="customers">
<?php
$MAX_COLS = 5;
$query = "select * FROM `complaints`";
$result = mysqli_query($conn,$query);
$i = 0;
while($row = mysqli_fetch_row($result)){
if($i % $MAX_COLS == 0){
echo "<tr>";
}
echo "<td>";
echo "<img src='SCB2/Images/temp2.jpg' alt='Sample image' style='width:200px;height:200px;' >";
echo "<br>"."Image ID: ".$row[0];
echo "<br>"."Latitude: ".$row[2];
echo "<br>"."Longitude: ".$row[3];
echo "<br>"."Zip: ".$row[4];
echo "<br>"."Done by: ".$row[8];
echo "<td>";
$i++;
if($i % $MAX_COLS == 0){
echo "</tr>";
}
}
?>
</table>
You can add the link to the HTML that is outputted:
echo "<td>";
// ...
echo "<br><a href='/some/path/to/accept.php?imageid={$row[0]}'>Accept</a>";
echo "<td>";
And then in the accept file you can deal with it:
// /some/path/to/accept.php
// Get the image id from the query string
$imageid = filter_input(INPUT_GET, 'imageid', FILTER_VALIDATE_INT);
try {
// Create a database connection
$db = new PDO(
'mysql:dbname=databaseName;host=localhost',
'username', 'pa55w0rd',
array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)
);
// Create a prepared statement and bind the image id to it
$stmt = $db->prepare('UPDATE complaints SET isAccepted = 1 WHERE Id = :id');
$stmt->bindValue(':id', $imageid, PDO::PARAM_INT);
// Execute the statement
if ($stmt->execute()) {
die('SUCCESS!');
} else {
die($stmt->error);
}
}
catch (\PDOException $e) {
die('PDO Exception: ' . $e->getMessage());
}
You should obviously do some checks that the user is allowed to accept the image.
I have a problem on selecting an id on div. I use a while loop on my div.
So i'am creating a unique ID using the id row on my sql. My question is, is it possible to select the id using Javascript? I use bootstrap modal to update my information details (i dont actually know how to ask this question because my english is poor).
example:
while($row = mysqli_fetch_array($result)) {
<div id="'details-'<?php echo $row['Room_ID'];?>">
//code
</div>
}
To fix your Php code:
while($row = mysqli_fetch_array($result)) {
echo "<div id='details-" . $row['Room_ID'] ."'>";
// CODE
echo "</div>";
}
The problem you got in the id, where you stopped the value by ' already, so the result was something like:
<div id='details-'28>//Code</div> and fixed to <div id='details-28'>//Code</div>
and to select the ID with pure JavaScript use document.getElementById( ID )
If you are not sure of the ID and you just wanna select all items, add a class to the item and select them all by document.getElementsByClassName
So to select all your stuff by javascript:
1) Add into your PHP code class called "details"
2) Create a javascript to select all items with the class name "details"
3) Do a foreach loop for the selected items and split them by "-" to devide the "details" from the actual ID
4) Do whatever you want now with the ID
Practical showcase:
Php:
while($row = mysqli_fetch_array($result)) {
echo "<div class='details' id='details-" . $row['Room_ID'] ."'>";
// CODE
echo "</div>";
}
JavaScript:
<script>
var itemDetails = document.getElementsByClassName("details");
for(var i = 0; i < itemDetails.length; i ++) {
var ID = itemDetails[i].getAttribute("id").split("-")[1];
// Now you got the ID stored in the variable ID
</script>
Here you got an example on JSFiddle
As for as my understanding from your code, you are want to create a div with id details from your database. For that you should correct your code as given blew
<?php
while($row = mysqli_fetch_array($result)) {
echo "<div id='details-'". $row['Room_ID'];">";
//code
echo "</div>";
}
?>
If it is problem to select it and perform some manipulations using jQuery/javascript you may consult the official API documentation at
This link
I'm probably asking a very simple question here - I know the basics of calling an array but I think I'm probably not doing it in the most efficient way... I'm calling some data into an array at the start of my page and then I want to be able to use this data-set multiple times throughout the page without wrapping everything in PHP if possible.
At present I'm doing it like this -
A variable ('video') is passed to my page through the URL which I get like so:
<?php
$video = $_GET['video'];
?>
My <title> tag is pulled from the selected database (also titled 'video')
<?php
$title = mysql_query("SELECT * FROM video WHERE ID = '{$video}'") or die(mysql_error());
mysql_real_escape_string($video);
while($head = mysql_fetch_array( $title )) {
echo "{$head['title']} - BY XXXXX</title>";
echo "<meta property=\"og:title\" content=\"{$head['title']} - BY XXXX\"/>";
}
?>
I then want to use the {$video} data later on the same page, but defining a slightly different variable like so:
<?php
$data = mysql_query("SELECT * FROM video WHERE ID = '{$video}' ORDER BY added DESC") or die(mysql_error());
mysql_real_escape_string($video);
while($info = mysql_fetch_array( $data )) if ($info['ytembed'] == 'yes') {
echo "{$info['embedcode']}";
echo "<div class=\"videobox1\">";
echo "<div class='video-title'>{$info['title']}</div>";
echo "<div class='video-subtitle'>{$info['subtitle']}</div>";
echo "<div class='video-credits'>{$info['cast']}</div>";
echo "<div class='back'>«back</div></div>";
} else {
echo "no embed code";
}
?>
So at the moment every time I want to pull from that data I'm calling the whole array again - it would be amazing if instead of doing this I could just print/echo selected items
Is there a way to make my code more efficient and do this?
I'm also looking to Validate the ID and if it doesn't exist within the video DB send the user to a 404 page - but perhaps that's a separate question.
Hello this is refined code
Replace first 1 with this.
$video = $_GET['video'];
$video = mysql_real_escape_string($video);
$videodata = mysql_query("SELECT * FROM video WHERE ID = '{$video}' LIMIT 1") or die(mysql_error());
// execute the query and check if video id exist or not
if(mysql_num_rows($videodata) == 0){
// 404 redirect code.
}
Replace Second with
$videodataArray = array(); // created array for storing video data
while ($head = mysql_fetch_array($videodata))
{
$videodataArray = $head ; // store the value in video data array for to use in fulll page
echo "{$videodataArray['title']} - BY XXXXX</title>";
echo "<meta property=\"og:title\" content=\"{$videodataArray['title']} - BY XXXX\"/>";
}
Replace last one with
echo "{$videodataArray['embedcode']}";
echo "<div class=\"videobox1\">";
echo "<div class='video-title'>{$videodataArray['title']}</div>";
echo "<div class='video-subtitle'>{$videodataArray['subtitle']}</div>";
echo "<div class='video-credits'>{$videodataArray['cast']}</div>";
echo "<div class='back'>«back</div></div>";
I am trying to combine two things which are already know how to do, but can't figure out how to combine them. Here is what I want to achieve:
I have a database with locations and events. There are several events in each location. I will be using PHP to query the database and output the code needed to display search results. I want something similar to the below:
<div id="location">
<p>Location1</p>
<div id="event">Event1</div>
<div id="event">Event2</div>
<div id="event">Event3</div>
</div>
<div id="location">
<p>Location2</p>
<div id="event">Event4</div>
<div id="event">Event5</div>
<div id="event">Event6</div>
</div>
I know that I can use select distinct to get the unique value of each location, and know that I can use a normal select statement to get all the events, however how do add all the events inside the location div?
My current PHP looks like this:
$sql ="SELECT location, event from events";
$res = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_assoc($res)){
$location = $row['location'];
$event = $row['event'];
echo "<div id="location">
<p>$location</p>
<div id="event">$event</div>
</div>";
}
My current code adds duplicates of the same location with 1 unique event in each. Even if I use select distinct I get the same results. How do I group the events have have the same location?
I think you should write something like:
$sql ="SELECT location, event from events";
$res = mysql_query($sql) or die(mysql_error());
$prevlocation = "";
while($row = mysql_fetch_assoc($res))
{
$location = $row['location'];
$event = $row['event'];
if ( $prevlocation != "" ) // Close previous div if needed
{
echo "</div>";
}
if ( $location != $prevlocation )
{
echo "<div id='location'><p>$location</p>";
$prevlocation = $location;
}
else
{
echo "<div id='event'>$event</div>";
}
}
echo "</div>"; // Close last div
If you have join of two tables, let's assume that your query looks like this:
$sql ="SELECT * FROM events
JOIN locations ON
locations.id=events.loc_id";
And then, within one loop, get events and location arrays:
$res = mysql_query($sql) or die(mysql_error());
$locations = array();
$events= array();
while($row = mysql_fetch_assoc($res))
{
$location = $row['location'];
$event = $row['event'];
$loc_id=$row['loc_id'];
$id=$row['id'];
$events[]=$loc_id.'%'.$event;
if(!in_array($id.'%'.$location,$locations)) { // avoid duplicate entries
$locations[]=$id.'%'.$location;
}
}
And, another loop (+loop inside loop):
for($i=0;$i<count($locations);$i++) {
$location=explode('%',$locations[$i]);
echo "<div class='location'>\n
<p>$location[1]</p>\n";
for($j=0;$j<count($events);$j++) {
$event=explode('%',$events[$j]);
if($event[0]==$locations[$i][0]) {
echo "<div class='event'>".$event[1]."</div>";
}
}
echo "</div>";
}
Not so elegant, but it is working, and produces valid HTML. :)
First, i wanted to make two associative arrays, and to compare keys, but i couldn't, because i couldn't convert ID keys to strings, so i made it with explode (% is separator between key and value).
I am writing a script that allows users to create teams, send contracts to others that are registered, so on and so forth. I want the logged in user to be able to withdraw from a team. The html tables are dynamically populated from mysql using php. I can get it to apply my delete option to all the users within the <td></td> but not just the one that is logged in. Here is some code snippets to help I hope. Basically I want only the user that is logged in to have the delete option.
Id Player
1 User 1 - No Delete Option
2 User 2 - Delete Option (Is the logged in user)
3 User 3 - No Delete Option
session_start();
$get_users_name = $_SESSION['username_u'];
$sql = ("SELECT id, username FROM user WHERE username='$get_users_name'");
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$grab_id = $row['id'];
$grab_user = $row['username'];
//the rest of the table generation done here such as <tr> etc
echo "<td>";
if ($grab_user == $get_users_name) {
echo ''.$grab_user.'';
}
else
{
echo $grab_user;
}
echo "</td>";
//the rest of the table generation done here such as </tr> etc
}
**Edited to fix echo problem caught by #easteregg
Just be sure you will style your code for readability ,then you will notice that you have your if condition inside the echo ;)
Try this it should work!
echo "<td>";
if ($grab_user == $get_users_name) {
echo ''.$grab_user.'';
} else {
echo $grab_user;
}
echo "</td>";
Be aware of the fact, that you should check again in the user_delete.php if a user has the right to delete something , otherwise you will run into some strange sort of trouble ;)