简体   繁体   中英

How can I usefully retrieve values from a mysql column in php?

I'm new to programming and trying to make my first web app. I'm building a site where users can login, see a list of links, and save/bookmark links from this list to their account. Eventually, I'd also like to be able to add functionality where users can create their own links.

So far, I'm planning on storing the information in 3 tables like these:

Users table user_id | username | password

Links table link_id | link_name | link_URL

Bookmarks table bookmark_id | user_id | link_id

I figured I would run a query to get a list of all the link_ids from the bookmarks table that belong to a certain user_id, like so:

$connection = mysql_connect('localhost', 'root', 'password') or die(mysql_error());
mysql_select_db("array-test",$connection) or die(mysql_error());

$query_link_id = "
SELECT link_id FROM bookmarks WHERE user_id =2
";
$query_result = mysql_query($query_link_id,$connection);

$link_id_array = mysql_fetch_array($query_result, MYSQL_BOTH);

If I echo out the array, it only has 1 value, the first row from the column. If I run the same query directly in phpadmin, I see the column with multiple values. I'm not sure what I'm doing wrong here.

Is storing the values in an array the correct way to do this? I have to somehow get the link_ids into an array, turn them each into variables, then run another query to get the rest of the link information - which I really have no idea how to do. I'm feeling pretty stuck on this and I've been searching for a solution for a few days. I appreciate any help and insight. Thanks!

mysql_fetch_array() - Returns an array that corresponds to the fetched row and moves the internal data pointer ahead - http://php.net/manual/en/function.mysql-fetch-array.php

You need to loop through the array.

while($link_id_array = mysql_fetch_array($query_result, MYSQL_BOTH)){
  $new_array[] = $link_id_array;
}

Note, from the docs
This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM