beginner needs help with sql and php - php

Im making a simple forum for my site but im having some problems
it wont print the posts. and i get no error very weird. It prints the thread title.
$id = isset($_GET['t']) ? intval($_GET['t']) : 0;
$query = "SELECT * FROM threads t INNER JOIN posts p ON p.tid = t.id WHERE t.id = $id";
$result = mysql_query($query);
// see if thread exists
if (!mysql_num_rows($result)) {
echo "The requested thread does not exist.";
return false;
}
// Fetch the rows
$row = mysql_fetch_assoc($result);
// Print title
echo '<h1>'.htmlspecialchars($row['title']).'</h1>';
// Print posts
while ($row2 = mysql_fetch_assoc($result)) {
echo $row2['message'];
}
The Tables:
CREATE TABLE IF NOT EXISTS `threads` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
)
INSERT INTO `threads` (`id`, `title`) VALUES
(1, 'My first thread!');
CREATE TABLE IF NOT EXISTS `posts` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`tid` int(10) unsigned NOT NULL DEFAULT '0',
`message` text NOT NULL,
PRIMARY KEY (`id`)
)
INSERT INTO `posts` (`id`, `tid`, `message`) VALUES
(1, 1, 'This is my first post in my first thread :)');

Check if your queries and db connections succeed. You're not doing that, so right now if the query fails, it'll do so silently and you're stuck in the dark:
$result = mysql_query($query) or die(mysql_error());
Something like that during development will save you a ton of hair and time.

the first message is in $row try this
// Fetch the rows
$row = mysql_fetch_assoc($result);
// Print title
echo '<h1>'.htmlspecialchars($row['title']).'</h1>';
echo $row['message'];
// Print posts
while ($row2 = mysql_fetch_assoc($result)) {
if($row['title'] == $row2['title'])
echo $row2['message'];
else
//start a new title

You probably want something like this:
$query = "SELECT * FROM threads t INNER JOIN posts p ON p.tid = t.id WHERE t.id = $id ORDER BY `tid` ASC";
$result = mysql_query($query);
if (!mysql_num_rows($result)) {
echo "The requested thread does not exist.";
return false;
}
$lastTID = null;
while ($row = mysql_fetch_assoc($result)) {
if ($lastTID != $row['tid']) {
echo '<h1>'.htmlspecialchars($row['title']).'</h1>';
$lastTID = $row['tid'];
}
echo $row['message'];
}
Note the ORDER BY clause and the $lastTID bit.

Related

Is there anyway to rearrange my uploads so that it'll show up first instead of last when I do upload it?

I am using MySQL and I think it has something to do with Id's. I want every new image I upload to show up first in a order. Here is my code:
This allows the images to display:
<?php
$db = mysqli_connect("localhost", "root", "", "photos");
$sql = "SELECT * FROM images";
$result = mysqli_query($db, $sql);
while ($row = mysqli_fetch_array($result)) {
echo "<a href='uploads/".$row['image']."'> ";
echo "<img id='img_div' src='uploads/".$row['image']."'/>";
echo "</a>";
}
?>
Here is my image structure:
CREATE TABLE `images` (
`id` int(11) NOT NULL,
`image` varchar(200) NOT NULL,
`text` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `images` (`id`, `image`, `text`) VALUES .....
ALTER TABLE `images`
ADD PRIMARY KEY (`id`);
ALTER TABLE `images`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=129;
$sql = "SELECT * FROM images ORDER BY id DESC";
Should do the trick!

add friend system in php

I am trying to build a friend system in php I have the tables, database and the logic in place. I am having trouble getting the friend request receiver's id.
I have registeredusers friends updates table. The registeredusers table looks like this,
CREATE TABLE `registeredusers` (
`id` int(11) NOT NULL,
`FirstName` varchar(50) NOT NULL,
`LastName` varchar(50) NOT NULL,
`UserName` varchar(50) NOT NULL,
`Email` varchar(50) NOT NULL,
`Password` varchar(255) NOT NULL,
`ResetPassword` int(7) DEFAULT NULL,
`friends` int(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
friends
CREATE TABLE `friends` (
`friend_one` int(11) NOT NULL,
`friend_two` int(11) NOT NULL,
`status` enum('0','1','2') DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
The requester's ID would be INSERTED into friend_two and receiver's ID would get into friend_one. here's my code
<?php
include 'dbh.php';
$sql = "SELECT * FROM registeredusers";
$result = mysqli_query($connection,$sql);
$row = mysqli_fetch_assoc($result);
$username = $row['UserName'];
$requesterU = $_GET['user'];
echo "the requester is ".$requesterU;
while($row=mysqli_fetch_array($result)){
$id = $row[0];
$username = $row[1];
echo "
<form action='list of users.php'>
$id $username<input type='submit' value='send request' name='friendsbanalo'></input></form>";
}
$sql = "SELECT * FROM registeredusers WHERE UserName = '$requesterU'";
$result = mysqli_query($connection,$sql);
$row = mysqli_fetch_assoc($result);
$requester_id = $row['id'];
echo "requester's id ".$requester_id;
if(isset($_POST['friendsbanalo'])){
$sql = "INSERT INTO friends (friend_one,friend_two) VALUES('$requester_id','$reciver_userid')";
$result = mysqli_query($connection, $sql);
}else{
echo "error";
}
?>
I am not able to get the receiver's ID, can anyone tell me how can I get receiver's ID? I tried searching for the solution and the answers were too complicated for me to understand. I tried (on a separate file) INNER JOIN but I couldn't get it to work.

i want to create status and comment system similar to facebook

i just want to build comment and status system similar to facebook. when i give a status its show and comment regarding this status its show. but when i give a new status it dose not show.
<?php
// show status.
mysql_connect("localhost","root","");
mysql_select_db("saif");
$sql="select id, st from status ";
$result=mysql_query($sql);
while($row= mysql_fetch_array($result))
{
echo $row['id']. " " .$row['st'];
echo "<br>";
//show comment;
mysql_connect("localhost","root","");
mysql_select_db("saif");
$sql="select com from comment ";
$result=mysql_query($sql);
while($row= mysql_fetch_array($result))
{
echo $row['com'];
echo "<hr>";
}
// end of show comment
//new comment area.
include('textarea.php');
echo "<hr>";
}
?>
Ok, this is my solution:
First I create two tables in my db and I populated them, then I create a connection to my db using MySQLi (MySQL is deprecated).
I SELECTED all the status, and for each status I selected the related comments. To do so, In the comments table I need something to make a relation between status and comments.
Just to understand to which status the comment is related.
First let's create and populate the tables:
SQL:
CREATE TABLE `status` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`st` text,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `status` (`id`, `st`)
VALUES
(1, 'This is the first status in your DB, let\'s say \"Hello World\"'),
(2, 'This is the second status');
CREATE TABLE `comment` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`id_status` int(11) DEFAULT NULL,
`com` text,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `comment` (`id`, `id_status`, `com`)
VALUES
(1, 1, 'This is just a comment to the first status'),
(2, 1, 'This is another comment to the first status'),
(3, 2, 'This is a comment to the second status'),
(4, 1, 'This is the third comment to the first status');
Ok, the php file:
<?php
$con = mysqli_connect("localhost","YourUsername","YourPassword","YourDB");
// Check connection
if (mysqli_connect_errno()) {
echo "Connection error: ".mysqli_connect_error();
exit();
}
$sql = "SELECT * FROM status";
$result = $con->query($sql);
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
echo $row['id']." ".$row['st']."<br>";
//show comment
echo "<ol>";
$id_status = $row['id'];
$query = "SELECT com FROM comment WHERE id_status = $id_status";
$comments = $con->query($query);
while($comment = $comments->fetch_array(MYSQLI_ASSOC))
{
echo "<li>".$comment['com']."</li>";
}
echo "</ol>";
// end of show comment
//new comment area.
include('textarea.php');
echo "<hr>";
}
?>
And this is the result (no text area in my output, cause I didn't have your textarea.php)
I hope this helps.

How to simplify (loop) if else statement and get mysql table column's name (PHP) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I need help,
Scenario: Hotel, Checking Guests In. data in MySQL database.
MySQL:
CREATE TABLE IF NOT EXISTS `hotels` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Name` varchar(50) NOT NULL,
`Date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`Room01` int(11) NOT NULL,
`Room02` int(11) NOT NULL,
`Room03` int(11) NOT NULL,
`Room04` int(11) NOT NULL,
`Room05` int(11) NOT NULL,
`Room06` int(11) NOT NULL,
`Room07` int(11) NOT NULL,
`Room08` int(11) NOT NULL,
`Room09` int(11) NOT NULL,
`Room10` int(11) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
$result = mysql_query("SELECT * FROM hotels WHERE Name = 'hotel1'");
$row = mysql_fetch_array($result);
$room01 = $row['room01'];
0 = empty, 1 = not empty.
here is my code:
<?php
//example
$room01=1;
$room02=1;
$room03=0;
$room04=0;
//example
if ($room01 == 0)
{
echo "Your room is room01.";
}
elseif ($room02 == 0)
{
echo "Your room is room02.";
}
elseif ($room03 == 0)
{
echo "Your room is room03.";
}
elseif ($room04 == 0)
{
echo "Your room is room04.";
}
else
{
echo "None!";
}
?>
Result: Your room is room03.
What if I have 100 Rooms?
How to simplify if else statement and get the room name?
Use array_filter to find all empty rooms from database result and then print first room name, if any. Here's how you can write code without assuming there are 100 or n number of rooms in your database.
const EMPTY_ROOM = 0;
const OCCUPIED_ROOM = 1;
$rows = mysql_fetch_array($result);
$emptyRooms = array_filter($rows, function($room_value) {
return EMPTY_ROOM === $room_value;
});
if(empty($emptyRooms) || !is_array($emptyRooms)) {
echo 'None!';
return;
}
$rooms = array_keys($emptyRooms);
echo 'Your room is ' . $rooms[0] . '.' . PHP_EOL;
Update: It's probably because strict check is failing (EMPTY === $room_value). When you get data from database $room_value holds string data. Here's updated code:
function readDatabase() {
$handle = mysql_connect('localhost', 'root');
mysql_select_db('stackexchange');
if(!$handle) {
exit(mysql_error($handle));
}
$result = mysql_query("SELECT * FROM hotels WHERE Name = 'hotel1'", $handle);
return mysql_fetch_array($result, MYSQL_ASSOC);
}
$row = readDatabase();
const EMPTY_ROOM = '0';//set to string value to compare against database value
//use `array_slice` to get rid of columns: `id`, `Name`, `Date`.
//We want to search only in remaining columns: Room01, Room02 .... RoomN.
$row = array_slice($row, 3);
$emptyRooms = array_filter($row, function($room_value) {
return EMPTY_ROOM === $room_value;
});
if(empty($emptyRooms) || !is_array($emptyRooms)) {
echo 'None!';
return;
}
$rooms = array_keys($emptyRooms);
echo 'Your room is ' . $rooms[0] . '.' . PHP_EOL;
This should work (small explanation inside):
$row = mysql_fetch_array($result);
$roomNumber = 1;
//Get data from array
foreach($row as $data){
//if room returns 0 (empty)
if($data == 0){
if($roomNumber < 10){
echo "Your room is room0". $roomNumber;
break;
} else {
echo "Your room is room". $roomNumber;
break;
}
} else {
$roomNumber++;
}
}
The benefit of this approach is that it doesn't matter how many rooms you have. You can add or remove as many as you like. It'll loop through all of them, without having to adept the code.
EDIT:
After #Strawberrys comment, I realise that although my answer will work, this is not the way you should continue. Database normalisation would be the way to go. For example:
CREATE TABLE `hotels` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`Name` VARCHAR(64) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
CREATE TABLE `rooms` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`Hotel_id` INT(11) NOT NULL,
`Date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`Room_number` INT(5) NOT NULL,
`Occupied` INT(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
Using this type of Database design, you can easily add and remove Hotels to your system. Using Hotel_id as a reference, you can now easily add and remove rooms to your Hotels, without having to use an insane amount of table columns.
To use it, you simply query the Hotel_id inside rooms to get all rooms returned. Afterwards it's just a matter of checking the first Room_number where Occupied returned 0.
use array_search
const EMPTY_ROOM = 0;
$roomNumber = array_search(EMPTY_ROOM, $row);
if(false === $roomNumber) {
echo 'None!';
return;
}
echo 'Your room is ' . $roomNumber . '.' . PHP_EOL;
Update
hmm, I used test data to generate input. With your table structure here's updated code:
function readDatabase() {
$handle = mysql_connect('localhost', 'root');
mysql_select_db('stackexchange');
if(!$handle) {
exit(mysql_error($handle));
}
$result = mysql_query("SELECT * FROM hotels WHERE Name = 'hotel1'", $handle);
return mysql_fetch_array($result, MYSQL_ASSOC);
}
const EMPTY_ROOM = 0;
const OCCUPIED_ROOM = 1;
$row = readDatabase();
//use `array_slice` to get rid of columns: `id`, `Name`, `Date`. We want to search only in remaining columns: Room01, Room02 .... RoomN.
$roomNumber = array_search(EMPTY_ROOM, array_slice($row, 3));
if(false === $roomNumber) {
echo 'None!';
return;
}
echo 'Your room is ' . $roomNumber . '.' . PHP_EOL;

Function to check to see if a field in a MySQL table equals 1

For the MySQL table below, what PHP function would simply test to see if 'subcheck' equals 1?
Thanks in advance,
John
`submission` (
`submissionid` int(11) unsigned NOT NULL auto_increment,
`loginid` int(11) NOT NULL,
`title` varchar(1000) NOT NULL,
`slug` varchar(1000) NOT NULL,
`url` varchar(1000) NOT NULL,
`displayurl` varchar(1000) NOT NULL,
`datesubmitted` timestamp NOT NULL default CURRENT_TIMESTAMP,
`subcheck` tinyint(1) NOT NULL,
PRIMARY KEY (`submissionid`)
)
You haven't provided much needed information such as the table name, your conditions for checking, so I'm just going to give you a simple query for you to work with...
$query = mysql_query('SELECT subcheck FROM your_table WHERE subcheck = "1"');
if ($query)
{
//your subcheck is 1
}
else
{
//your subcheck is not 1 / nothing was found
}
If you need to select only ones with a certain submissionid it would be best to change it to the following:
$submissionid = 809;
$query = mysql_query('SELECT subcheck
FROM your_table
WHERE submissionid = "' . $submissionid . '"');
if ($row = mysql_fetch_row($query))
{
if ($row[0] == 1) { } //your subcheck is one
else { } //your subcheck is not one
}
else { } //no matching records found
Remember to escape $submissionid if it's going to be based from an unsafe source such as user input!

Categories