Joining streamitem_creator in streamdata to users table - php

I have two tables. One which holds the user status content and the other holding the users. How do I write the query of the users to obtain the user record for their given streamitem in streamdata? At current times, its only grabbing the user that is at the top of the user table.
$check = "SELECT streamitem_id, streamitem_timestamp, streamitem_content FROM streamdata WHERE streamitem_creator="$user1_id." AND streamitem_id=".$last." AND streamitem_type_id=1 ORDER BY streamitem_timestamp DESC";
$check1 = mysqli_query($mysqli,$check);
$resultArr = mysqli_fetch_array($check1);
$json['streamitem_id'] = $resultArr['streamitem_id'];
$json['streamitem_timestamp'] = Agotime($resultArr['streamitem_timestamp']);
$json['streamitem_content'] = $resultArr['streamitem_content'];
mysqli_free_result($check1);
$check = "SELECT * FROM users";
$check1 = mysqli_query($mysqli,$check);
$resultArr = mysqli_fetch_array($check1);
$json['username'] = $resultArr['username'];
$json['id'] = $resultArr['id'];
$json['first'] = $resultArr['first'];
$json['middle'] = $resultArr['middle'];
$json['last'] = $resultArr['last'];
mysqli_free_result($check1);
-- Table structure for table `streamdata`
--
CREATE TABLE IF NOT EXISTS `streamdata` (
`streamitem_id` int(11) NOT NULL auto_increment,
`streamitem_type_id` int(11) NOT NULL,
`streamitem_creator` int(11) NOT NULL,
`streamitem_target` int(11) NOT NULL,
`streamitem_timestamp` datetime NOT NULL,
`streamitem_content` varchar(5000) NOT NULL,
PRIMARY KEY (`str
eamitem_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1953 ;
-- Table structure for table `users`
--
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL auto_increment,
`first` varchar(64) NOT NULL,
`middle` varchar(64) NOT NULL,
`last` varchar(64) NOT NULL,
`username` varchar(64) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=150 ;

Query to get user details and stream details for a given stream item:
$check = "
SELECT * FROM users u
INNER JOIN streamdata s ON
(s.streamitem_creator = u.id AND s.streamitem_id = {$last})";
Please note that it is bad practice to insert raw variable values into your queries. Especially if they come from user input. Look into mysqli_real_escape_string or try using prepared statements.

Related

select from 2 table and make ordering them

first, sorry for my English ...
what i want is to select from two SQL tables and then make them in a specific order , like in forums ...
i have two table, topic and users, i want to select from both of them a putt author info next to his topic
here is the SQL of Topic and users
CREATE TABLE IF NOT EXISTS `topics` (
`id` int(11) NOT NULL,
`id2` int(11) NOT NULL,
`title` varchar(256) NOT NULL,
`message` longtext NOT NULL,
`author_id` int(11) NOT NULL,
`timestamp` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `users` (
`id` bigint(20) NOT NULL,
`username` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`avatar` varchar(255) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
and the php code might look like this
<?php
$sql = mysql_query(' MySQL query ... ');
while($row = mysql_fetch_array($sql)) {
echo '<p>'.$row['username']'<br>';
echo $row['message'].'<br></p>';
}
?>
is there any way to do it ??
As I understood, what you are looking for is the correct SQL statement to execute. The following simple solution will.
<?php
$sql = mysql_query('SELECT users.username, topics.message FROM `users` INNER JOIN topics ON topics.author_id = users.id');
while($row = mysql_fetch_array($sql)) {
echo '<p>'.$row['username']'<br>';
echo $row['message'].'<br></p>';
}
?>
SELECT * FROM `users` INNER JOIN topics ON topics.author_id = users.id'

PHP something wrong with while loop

Okay so now its display results like 3 times in a row
$user_apps = mysql_query("SELECT a.name,a.download_url FROM user_apps as ua LEFT JOIN
apps as a ON (ua.app_id=a.app_id)
WHERE ua.user_id='$user_id'") or die(mysql_error());
while($raw = mysql_fetch_array($user_apps)){
$name = $raw['name'];
$url = $raw['download_url'];
echo $name;
echo "<br />";
echo $url;
}
Database Table Structure(since I am new to the site and did not know how to display the table structure I just exported the sql)
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;
CREATE TABLE IF NOT EXISTS `user_apps` (
`user_id` int(11) NOT NULL,
`app_id` int(11) NOT NULL,
KEY `user_id` (`user_id`,`app_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE IF NOT EXISTS `apps` (
`app_id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`description` text NOT NULL,
`icon` varchar(255) NOT NULL,
`download_url` varchar(255) NOT NULL,
`default` int(20) NOT NULL DEFAULT '0',
PRIMARY KEY (`app_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;
I'v tried different Join types but that does not seem to work.
Used the join query for get the result check bellow example query
$user_apps = mysql_query("SELECT DISTINCT a.name,a.download_url FROM user_apps as ua LEFT JOIN apps as a ON (ua.app_id=a.app_id) WHERE ua.user_id='$user_id'") or die(mysql_error());
while($raw = mysql_fetch_array($user_apps)){
$name = $raw['name'];
$url = $raw['download_url'];
echo $name;
echo $url;
}
change the join type as per your requirement. the above query for only example
INNER JOIN: Returns all rows when there is at least one match in BOTH
tables
LEFT JOIN: Return all rows from the left table, and the matched rows
from the right table
RIGHT JOIN: Return all rows from the right table, and the matched
rows from the left table
FULL JOIN: Return all rows when there is a match in ONE of the tables
more about join click here
AND also check this http://blog.codinghorror.com/a-visual-explanation-of-sql-joins/
You have used single quotes in query at user_id='$user_id' .
Are you sure your user_id is char, varchar or text? Just print_r($user_apps) and check it has any records or not? If user_id is int,tinyin than remove single quote.

Combine multiple sql queries in php

So, I've helped a friend with a ticket system for a charity event. On this page users can select the amount of tickets they want and then click on "register". There are no payments involved, they can just register tickets. There are two types of tickets: normal and vip tickets.
I've created three databases: customers, tickets and customer_tickets. Below are the dumps of these tables.
Customers:
CREATE TABLE `customers` (
`id` int(255) NOT NULL AUTO_INCREMENT,
`surname` varchar(2056) NOT NULL,
`lastname` varchar(2056) NOT NULL,
`email` varchar(2056) NOT NULL,
`street` varchar(2056) NOT NULL,
`house` int(255) NOT NULL,
`postal` varchar(2056) NOT NULL,
`city` varchar(2056) NOT NULL,
`desired_vip_tickets` int(1) NOT NULL DEFAULT '0',
`desired_normal_tickets` int(1) NOT NULL DEFAULT '0',
`order_id` varchar(2056) NOT NULL,
`status` varchar(2056) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=36 ;
Customer_tickets:
CREATE TABLE `customer_tickets` (
`id` int(255) NOT NULL AUTO_INCREMENT,
`order_id` int(255) NOT NULL,
`ticket_id` int(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
Tickets:
CREATE TABLE `tickets` (
`id` int(255) NOT NULL AUTO_INCREMENT,
`ticket_id` varchar(2056) NOT NULL,
`ticket_type` int(255) NOT NULL,
`bought` int(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
When a user clicks register, the code below is executed. However, only the first query is executed and none of the others. Additionally I'm worried if all these queries make the server suffer...
$sql = "UPDATE customers SET `status`='$status' WHERE `order_id`='$order_id'";
$qry = mysql_query($sql) or die (mysql_error());
$sql = "SELECT `desired_vip_tickets`, `desired_normal_tickets` FROM customers WHERE `order_id`='$order_id'";
$qry = mysql_query($sql) or die (mysql_error());
$array = mysql_fetch_array($qry);
$vip = $array[0];
$normal = $array[1];
$sql = "SELECT `ticket_id` FROM tickets WHERE `ticket_type`='1' AND `bought`='0' LIMIT ".$vip;
$qry = mysql_query($sql) or die (mysql_error());
while ($row = mysql_fetch_assoc($qry)) {
$ticket_id = $row['ticket_id'];
$ins = "INSERT INTO customer_tickets (`order_id`, `ticket_id`) VALUES ('$order_id', '$ticket_id)";
$query = mysql_query($ins) or die (mysql_error());
$upd = "UPDATE tickets SET `bought`='1' WHERE `ticket_id`='$ticket_id";
$query = mysql_query($upd) or die (mysql_error());
}
$sql = "SELECT ticket_id FROM tickets WHERE `ticket_type`='0' AND `bought`='0' LIMIT ".$normal;
$qry = mysql_query($sql) or die (mysql_error());
while ($row = mysql_fetch_assoc($qry)) {
$ticket_id = $row['ticket_id'];
$ins = "INSERT INTO customer_tickets (`order_id`, `ticket_id`) VALUES ('$order_id', '$ticket_id)";
$query = mysql_query($ins) or die (mysql_error());
$upd = "UPDATE tickets SET `bought`='1' WHERE `ticket_id`='$ticket_id";
$query = mysql_query($upd) or die (mysql_error());
}
You'll need to SQL join the different tables. Your sql would have to look something like this:
SELECT * FROM table1.customer_name, table2.amount_spent, recentpurchases
WHERE table2.amount_spent = recentpurchases.spendamount
I have used example tables for this anser. They are table1, table2 and recentpurchases. Apologies if this was not a helpful answer.

Cannot retrieve column information from database

I have two tables, namely user_info and comments. I want to join the tables, so i can relate the user_id from the from comments after the inner join has happened, which will join based on the id columns. The whole reason for this is so i can find out what the id is of a user who posts a comment on a users profile, which i store in user_id.
SHOW CREATE TABLE user_info
CREATE TABLE `user_info` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(12) COLLATE utf8_unicode_ci NOT NULL,
`pass` varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL,
`joined` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`))
ENGINE=InnoDB AUTO_INCREMENT=64 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci'
SHOW CREATE TABLE comments
'CREATE TABLE `comments` (
`id` int(11) DEFAULT NULL,
`comment` text COLLATE utf8_unicode_ci,
`date_posted` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`user_id` int(11) DEFAULT NULL)
ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci'
The query code
try {
$result = $db->prepare("SELECT user_id
FROM comments
INNER JOIN user_info USING (id)
WHERE id = :user");
$result->bindParam(':user', $post_session_user_id);
$result->execute();
$comment_details = $result->fetch();
}
How comment_details is stored
$comment_id = $comment_details[0];
and then i do a var_dump that returns NULL
var_dump($comment_id);
Any ideas what is wrong?
I think you should not be using USING as that works only when you have 2 fields, one in each table both having the same name.
In your tables comment.user_id holds the user_info.id
So your query should probably be
SELECT user_id
FROM comments
INNER JOIN user_info ON user_info.id = comments.user_id
WHERE comments.id = :user

Changing a field from a table depending on a mysql query

The prototype software I am creating uses the MVC framework.
I am trying to change the allowed field in the entrylog table to either "Y" (Yes) or "N" (no) depending on whether a card associated with a driver is authorised or not.
The four tables involved are card, driver, state and the entrylog table. Also there is a card_driver table which associates a card with a driver.
CREATE TABLE IF NOT EXISTS `card` (
`id` int(11) NOT NULL auto_increment,
`startdate` date NOT NULL,
`enddate` date NOT NULL,
`state_id` int(11) NOT NULL,
`referred_as` varchar(40) NOT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE IF NOT EXISTS `driver` (
`id` int(11) NOT NULL auto_increment,
`title` varchar(40) default NULL,
`supplier_id` int(11) NOT NULL,
`referred_as` varchar(40) NOT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE IF NOT EXISTS `card_driver` (
`card_id` int(11) NOT NULL,
`driver_id` int(11) NOT NULL
);
CREATE TABLE IF NOT EXISTS `state` (
`id` int(11) NOT NULL auto_increment,
`referred_as` varchar(40) NOT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE IF NOT EXISTS `entrylog` (
`id` int(11) NOT NULL auto_increment,
`vehicle_id` int(11) NOT NULL,
`driver_id` int(11) NOT NULL,
`venue_id` int(11) NOT NULL,
`supplier_id` int(11) NOT NULL,
`deliverydate` date NOT NULL,
`allowed` binary(1) NOT NULL default 'N',
PRIMARY KEY (`id`)
);
In the driver table I currently have code which checks the authorisation of a selected drivers associated card. I would like to apply this similiar code to the entry log, so that when using a form to enter a delivery it determines the 'allowed' field automatically. The code to check the drivers authorisation in the driver table is as follows:
if ($name == driver) {
?>
<? include('common.php') ?>
<?php
if(isset($_POST['check']))
{
$conn = mysql_connect($server, $db_user, $db_pass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$id = $_POST['id'];
$sql ="SELECT *
FROM driver AS d
INNER
JOIN card_driver AS cd
ON cd.driver_id = d.id
INNER
JOIN card AS c
ON c.id = cd.card_id
WHERE d.ID = $id";
mysql_select_db('damp');
$result = mysql_query( $sql, $conn );
$row = mysql_fetch_assoc($result);
switch($row['state_id'])
{
case "1":
echo "<strong><font color=\"green\">Authorisation Granted!</font></strong>";
break;
case "2":
echo "<strong><font color=\"red\">Your card has expired and authorisation is denied</font></strong>";
break;
case "3":
echo "<strong><font color=\"red\">Your card has been cancelled and authorisation is denied</font></strong>";
break;
default:
echo "<strong><font color=\"red\">The Card ID does not exist</font></strong>";
}
Thank you for any help or advise you can give me.
EDIT : Code from controller_create.php
if ($class_obj == "entrylog")
{
$id = $_POST['id'];
$driverid = MyActiveRecord::FindById('driver',$this_obj->driver_id);
$query = mysql_query("SUPDATE entrylog el
INNER JOIN driver AS d ON d.driver_id = el.driver_id
INNER JOIN card_driver AS cd ON cd.driver_id = d.id
INNER JOIN card AS c ON c.id = cd.card_id
SET el.allowed = CASE WHEN c.state_id = 1
THEN 'Y'
ELSE 'N'
END
WHERE el.ID = $entryLogId");
mysql_select_db('damp');
}
Not entirely clear on what you're asking but the following may help:
UPDATE entrylog el
INNER JOIN driver AS d ON d.id = el.driver_id
INNER JOIN card_driver AS cd ON cd.driver_id = d.id
INNER JOIN card AS c ON c.id = cd.card_id
SET el.allowed = CASE WHEN c.state_id = 1
THEN 'Y'
ELSE 'N'
END
WHERE el.ID = $entryLogId
From your most recent comment it sounds like this value should be calculated as part of your INSERT though, rather than an UPDATE later.

Categories