my php script save list of userid in a SESSION ARRAY variable for the purpose of creating html link on that page.
when we click that html link another PHP script should display all user information for that userid in a html table.
I need yo know best practice to create SELECT query for this
1) SELECT * from `users` WHERE
`user_id` = '$array_valuer1' OR
`user_id` = '$array_valuer2' OR
`user_id` = '$array_valuer3' OR
`user_id` = '$array_valuer4' OR
`user_id` = '$array_valuer5' OR
`user_id` = '$array_valuer6' OR
----
----
`user_id` = '$array_valuern';
2) select all user --> SELECT * from `users`
then using php script display only the userid in the SESSION array and skip other userid
which is best practice? the SESSION array is temporary and i do not to want to save in a database.
thanks
If you are storing few user ids in a session its okay. But if the number is huge dont store them in SESSION. Its better to fetch them using a query.
About the query you can use following form.
$q = "SELECT * from `users` WHERE `user_id` IN ('".implode("','", $array)."')";
shiplu.mokadd.im answer is good, but using PDO is better:
$db = new PDO("...");
$statement = $db->prepare("SELECT * from `users` WHERE `user_id` IN (':list')");
$statement->execute(array(':list' => implode("','", $array)));
$row = $statement->fetch();
Related
i am doing a mini project of social networking , i am having a doubt about table .
let see , i need to provide post in their page. to do this,should i have to create table for each user or just create one table and use it for multiple users (data can be fetched by selecting particular user name and display it in their page ).
which is the best way?
my php code:
<?php
$query="select * from table_name where user=$username order by time desc;";
?>
To answer your question
It's best to just use 1 table of users and have a separate able for your posts. Your users table should have all the information for each specific users with 1 unique value that is automatically generated by the MySQL database. (Use auto-increment) And in the posts table you should have all the data for each post with a user_id column that holds the unique value from the users table, this way you know who posted it.
Here is a mockup table structure:
Users table:
uid | name | email
Posts table:
uid | user_id | message
user_id in the posts table should always be equal to some uid in the users table.
Every single table should always have some unique value that is assigned its primary value
My real concern
I am very concerned with the security of your application. Prepared statements are WAY easier to use, and WAY more secure.
In the code snippet that you shared:
<?php
$query="select * from table_name where user=$username order by time desc;";
?>
this query is very insecure, as Bobby Tables would tell you. I'm not sure why type of database connection you are using, but I suggest PDO. I wrote a function that makes this very very easy, here is the snippet for that:
This is a file I usually call connection.php that you can import on any page you need to use your database.
<?php
$host = 'localhost';
$db = '';
$user = '';
$pass = '';
$charset = 'utf8';
$dsn = "mysql:host={$host};dbname={$db};charset={$charset}";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new PDO($dsn, $user, $pass, $opt);
function pdoQuery($query, $values = []) {
global $pdo;
if(!empty($values)) {
$stmt = $con->prepare($query);
$stmt->execute($values);
} else {
$stmt = $con->query($query);
}
return $stmt;
}
?>
This function allows you to EASILY use prepared statements by just
including the connection.php page and writing queries in a way that is
readable, clean, and secure. As I'm sure a lot of people reading this are not used to Prepared Statements or know how they
work, the rest of this post will explain that.
One of the biggest differences here is that instead of using String
Interpolation in
your query, you will set variables as question marks ?, so your
query looks like this: UPDATE table SET user=? instead of UPDATE
table SET user='$user' - and the variables will be sent later for
safety, so this prevents SQL Injection.
This it the way your query would look now:
pdoQuery("SELECT * FROM `table_name` WHERE user=? ORDER BY `time` DESC", [$username]);
This is basically how it works:
pdoQuery(string $query, array $variables)
If you pass no variables, it automatically uses the query() function, if you do pass variables it automatically binds and executes the statements. No matter what query you do, the function always returns the query as an object, so you can act on it using any method you can normally use on a PDO query after the execute.
If you know how these work, you can stop reading here :) I put some
exmaples below of some of the ways you can manipulate the return data
to do what you need to do.
This function returns the object of the query you requested, so if you wanted to loop through all of the results of your query you use it like this:
$stmt = pdoQuery("SELECT * FROM `table_name` WHERE `user`=? ORDER BY time DESC", [$username])->fetchAll();
foreach($stmt as $row) {
$row['name']."<br>";
}
Or if you just wanted to get a single column from a specific row, you could use it like this:
$username = pdoQuery("SELECT `username` FROM `users_table` WHERE uid=? ORDER BY `time` DESC", [$uid])->fetchColumn();
Which will return the username from user where uid=$uid as a string
or if you wanted several values from 1 specific row, you could do
$user = pdoQuery("SELECT `username`,`name`,`email` FROM `users_table` WHERE uid=? ORDER BY time DESC", [$uid])->fetch();
Which will return to $user as an array that has the username, name, and email of the user.
You can also use this function to INSERT, UPDATE, or basically any type of query you can think of. This is how you insert:
pdoQuery("INSERT INTO `table_name` (`name`,`col2`, `col3`) VALUES (?,?,?)", [$name, $col1, $col2]);
My PDO Class
Since writing this post, I have created a new database wrapper class called GrumpyPDO (Hosted on Github).
This class method returns the object of the query you requested, so if you wanted to loop through all of the results of your query you use it like this:
Fetch All
GrumpyPDO Long Syntax
$stmt = $db->run("SELECT * FROM `table_name` WHERE `user`=? ORDER BY time DESC", [$username])->fetchAll();
GrumpyPDO Short Syntax
$stmt = $db->all("SELECT * FROM `table_name` WHERE `user`=? ORDER BY time DESC", [$username]);
Loop:
foreach($stmt as $row) {
$row['name']."<br>";
}
Single Column Return
Or if you just wanted to get a single column from a specific row, you could use it like this:
//Long Syntax
$username = $db->run("SELECT `username` FROM `users_table` WHERE uid=? ORDER BY `time` DESC", [$uid])->fetchColumn();
//Short
$username = $db->cell("SELECT `username` FROM `users_table` WHERE uid=? ORDER BY `time` DESC", [$uid]);
Which will return the username from user where uid=$uid as a string
Entire Row Return
or if you wanted several values from 1 specific row, you could do
//Long Syntax
$user = $db->run("SELECT `username`,`name`,`email` FROM `users_table` WHERE uid=? ORDER BY time DESC", [$uid])->fetch();
//Short Syntax
$user = $db->row("SELECT `username`,`name`,`email` FROM `users_table` WHERE uid=? ORDER BY time DESC", [$uid]);
Which will return to $user as an array that has the username, name, and email of the user.
DML Queries
You can also use this function to INSERT, UPDATE, or basically any type of query you can think of. This is how you insert (All DML's are similar):
$db->run("INSERT INTO `table_name` (`name`,`col2`, `col3`) VALUES (?,?,?)", [$name, $col1, $col2]);
I am trying to design a very simple table that stores the data of friends in a community.
Therefor I store the userId of 2 friends respectively.
Goal
User wants to load his/her friends list.
t_friends Option 1:
Query
SELECT * FROM t_friend WHRE user_id = 10
10 is the current userId of the user which is looking for his friends list and he has 1 friend userId(20)
This way userId (10) finds his friend (20) BUT what if userId(20) were looking for his friends?
The query is coupled with userId.
That leads me to another design that contains redundant data:
t_friends option 2:
userId (10) loads now:
SELECT * FROM t_friend WHRE user_id=10
Similiar to that the query for userId(20) would then be:
SELECT * FROM t_friend WHRE user_id=20
But what about the redundancy? That leads me then to that query using table design option 1:
SELECT * FROM t_friend WHERE user_id=10 OR friend_id=10
I have a feeling that there is a smarter way to solve that. Do You have any experiences with that structure?
Thanks
Add field friendship_key:
ALTER TABLE t_friend ADD friendship_key decimal(22,11);
CREATE UNIQUE INDEX friendship_key_unique ON t_friend (friendship_key);
And php part:
$friends = [$userId, $friendId];
$key = min($friends).'.'.max($friends);
$q = "SELECT * FROM t_friend WHERE friendship_key = ".$key;
insert:
$friends = [$userId, $friendId];
$key = min($friends).'.'.max($friends);
$q = "INSERT INTO t_friend (friendship_key, userId, friendId) VALUES (".implode(',', [$key, $userId, $friendId]).")";
Instead of using VARCHAR for friendship key I've used decimal to minimize data for relation key.
To keep it simple just create functions:
function insertFriendship($user1, $user2) {
$key = min([$user1, $user2]).'.'.max([$user1, $user2]);
$q = "INSERT INTO t_friend (friendship_key, userId, friendId) VALUES (".implode(',', [$key, $user1, $user2]).")";
mysql_query($q);
}
function getFriendsOf($user) {
$q = "SELECT * FROM t_friends WHERE ".$user." IN (userId, friendId)";
return mysql_query($q);
}
function areFriends($user1, $user2) {
$key = min([$user1, $user2]).'.'.max([$user1, $user2]);
$q = "SELECT 1 FROM t_friends WHERE friendship_key = ".$key." LIMIT 1";
$q = mysql_query($q);
return (mysql_num_rows($q)>0);
}
I think this is the only way to store data about the relationships. When you are storing the relationship try to store the min value as the userId and max value as the friendId. make both values altogether unique and you will not get any duplicate values. When you search for users use something like below
SELECT * FROM t_friend WHERE user_id=10 OR friend_id=10
You may want to use the following query which verify if your user is not already a friend of another first :
INSERT INTO t_friend (userId, friendId)
SELECT 10, 20
WHERE NOT EXISTS ( SELECT userId
FROM t_friend
WHERE userId = 20
AND friendId = 10)
Thanks to this (french) topic about redundancy verification here.
i am struggling to Pass Parameter('User_ID') from PHP page to View (SELLER_INFORMTION ) at MySQL DB. can you please guide me.
Code Below:
<?php
session_start();
userid = $_SESSION['userid'];
include '../Database.class.php';
$dbe_obj = new Database_Executer();
$query = "SELECT * FROM SELLER_INFORMATION('$userid')";
$data = $dbe_obj-> select_query_executer($query);
?>
CREATE VIEW SELLER_INFORMATION
AS SELECT `PRODUCT`.PRODUCT_NAME,`CATEGORY`.CATEGORY_NAME,`SELLER_PRODUCT`.QUANTITY,
`SELLER_PRODUCT`.UNIT_PRICE,`SELLER_PRODUCT`.CURRENCY
FROM `PRODUCT`,`SELLER_PRODUCT`,`CATEGORY`,`USERS`
WHERE SELLER_PRODUCT.Category_ID=CATEGORY.CATEGORY_ID
AND SELLER_PRODUCT.Product_ID = PRODUCT.PRODUCT_ID
AND SELLER_PRODUCT.User_ID=`USERS`.USER_ID
AND SELLER_PRODUCT.User_ID = '$userid'
GROUP BY
`PRODUCT`.PRODUCT_NAME,`CATEGORY`.CATEGORY_NAME,`SELLER_PRODUCT`.QUANTITY,
`SELLER_PRODUCT`.UNIT_PRICE,`SELLER_PRODUCT`.CURRENCY
ORDER BY `CATEGORY`.CATEGORY_NAME DESC
Change your view to:
CREATE VIEW SELLER_INFORMATION
AS SELECT DISTINCT
`PRODUCT`.PRODUCT_NAME,
`CATEGORY`.CATEGORY_NAME,
`SELLER_PRODUCT`.QUANTITY,
`SELLER_PRODUCT`.UNIT_PRICE,
`SELLER_PRODUCT`.CURRENCY,
SELLER_PRODUCT.User_ID
FROM `PRODUCT`
JOIN `SELLER_PRODUCT` ON SELLER_PRODUCT.Product_ID = PRODUCT.PRODUCT_ID
JOIN `CATEGORY` ON SELLER_PRODUCT.Category_ID=CATEGORY.CATEGORY_ID
JOIN `USERS` ON SELLER_PRODUCT.User_ID=`USERS`.USER_ID
ORDER BY `CATEGORY`.CATEGORY_NAME DESC
Then use the query:
SELECT * FROM SELLER_INFORMATION WHERE User_ID = '$userid'
You can't have a PHP variable inside a view definition. You need to return the column in the SELECT list of the view, so you can compare with it in a WHERE clause.
Another possible option, you can pass parameters to your views in a simple manner by creating a Function to GET your values from Session Variables. See https://www.stackoverflow.com/questions/14511760 for the technique. This is a copy of my create function you may wish to pattern after.
DELIMITER //
CREATE FUNCTION fn_getcase_id()
RETURNS MEDIUMINT(11)
DETERMINISTIC NO SQL
BEGIN
see stackoverflow.com/questions/14511760 and read ALL the info TWICE or MORE. wh 04/13/2017
RETURN #sv_case_id;
END//
DELIMITER ;
You will need to create a similar FN (one for each variable).
What I'm trying to do is take a whole table and find out what the id is of the member whose email address is in the value of emails.from and put their id in there instead. I'm trying to improve my performance by using IDs instead of email addresses but am unable to complete this task.
$mysql = new mysql();
$mysql->query('SELECT `from` FROM `emails` ORDER BY `id` ASC' );
while($row = mysql_fetch_array($mysql->result)){
$mysql2 = new mysql();
$mysql2->query('SELECT `id` FROM `exchange` WHERE `email` = "'.$row['from'].'"');
$details = mysql_fetch_assoc($mysql2->result);
$mysql2->query('UPDATE `emails` SET `from` = '.$details['id'].' WHERE `from` = "'.$row['from'].'"');
}
No need to look it up if you're doing the whole table.
UPDATE emails SET from=id
Will do each row in the table.
If I understand your code, you could try something like this:
UPDATE `emails`
INNER JOIN `exchange` ON `exchange`.`email` = `emails`.`from`
SET `emails`.`from` = `exchange`.`id`
The query below should do the trick :)
update emails
set `from`=(select e.id from exchange as e where e.email=em.`from`)
from emails as em
order by em.id asc
Hey guys sorry if this is an amateur question but I'm having a little trouble with this.
How do I display comments towards a specific page? (page.php?id=48)
Because right now, every time i post a comment, it displays on all pages instead of the one i wanted it to post on
Heres the code:
$userfinal=$_SESSION['username'];
$rs = mysql_query("SELECT id FROM searchengine") or die(mysql_error());
$rec = mysql_fetch_assoc($rs);
$id = $rec['id'];
// get the messages from the table.
$get_messages = mysql_query("SELECT messages_id FROM messages WHERE to_user='$id' ORDER BY messages_id DESC") or die(mysql_error());
$get_messages2 = mysql_query("SELECT * FROM messages WHERE to_user='$id' ORDER BY messages_id DESC") or die(mysql_error());
$num_messages = mysql_num_rows($get_messages);
// display each message title, with a link to their content
echo '<ul>';
for($count = 1; $count <= $num_messages; $count++){
$row = mysql_fetch_array($get_messages2);
// if the message is not read, show "(new)"
// after the title, else, just show the title.
if($row['message_read'] == 0)
Any help would be appreciated, thanks
take a look at my sample code.
Consider a table comments with the basic structure.
CREATE TABLE `comments` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`comment` text NOT NULL,
`article_id` int(11) NOT NULL,
PRIMARY KEY (`id`)
);
comment column will hold the text of your comment
article_id holds the foreign key of the article it belongs to.
now lets say you want to retrieve the comment from a particular articleid article.php?id=48
here is how you should be doing it.
$articleId = mysql_real_escape_string($_GET['id']);
$query = 'SELECT id,comment FROM comments WHERE article_id ='.$articleId;
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
echo nl2br($row['comments']);
}
although my codes does not relate to your question at all, but it should give you the basic idea on how to implement the logic.
EDIT :
you should not use the code for production, the code is only meant to explain you to implement the logic, remember this code is vulnerable to SQL injections, if you want a temporary fix you could use mysql_real_escape_string() function to avoid it. check my updated code.
TIP : you should try and use PDO for all your database queries here is the tutorial to get you started http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/