URL and link text from database - php

I am currently still learning PHP so some things I still struggle with.
I have been taking it slowly and reading tutorials which has helped but I can't figure this one out.
I have a database table (in mysql) with let's say, 100 urls. There is a column called 'url' and a second column 'text'. I already have the pagination code which works, so will also be using that.
What I want to do is echo out the URLs (which are all in folder called blog in the root of my site), but use the text as the link.
So for example the first three rows in my table might be:
url
001.php
002.php
003.php
text
random text
some random text
more text
when echoed out the links show the text from the column text like:
random text
some random text
more text
and will open to the relevant url when clicked
I'm guessing it will need some kind of loop to collect all the URLs and save me adding the link text in manually, and then my pagination code will split them up.
This is my first time asking a question on here, so if it wasn't clear enough or you need more info, let me know.
I have done multiple searches on the internet but can't seem to find a tutorial.

Assuming you connect to a local mysql server with username "root" and password "root", and have your url's stored in a table named url_table in a database named url_database you could do something like:
$connection = mysql_connect("127.0.0.1","root","root"); // Connect to the mysql server
mysql_select_db("url_database"); // Open the desired database
$query = "SELECT url,text FROM url_table"; // Query to select the fields in each row
$result = mysql_query($query); // Run the query and store the result in $result
while($row = mysql_fetch_assoc($result)) // While there are still rows, create an array of each
{
echo "<a href='".$row['url']."'>".$row['text']."</a>"; // Write an anchor with the url as href, and text as value/content
}
mysql_close($connection); // close the previously opened connection to the database

What you need is to:
get your result array from the database. Use something like
$query = "SELECT * FROM urls";
$result = mysql_query($query);
For every row in your results table, show the corresponding url. Note that calling mysql_fetch_array on a result resource, returns the first row of the results table when called for the first time, the second on second time etc. The function returns false when there are no more rows to return.
(See more on that in the mysql_fetch_array() documentation)
While( $row = mysql_fetch_array($result) ){
echo '<a href='.$row['url'].'>'.$row['text'].'</a>';
}

Here is a sample you can start with:
$con = mysql_connect("host","user","password");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT the_url, the_text FROM my_table");
while($row = mysql_fetch_array($result))
{
echo '"' . $row['the_text'] . ' <br />';
}
mysql_close($con);

First, you want to select only the relevant lines in your database for the page that the user is currently viewing. For example, if the user is viewing page 2, with entries 15-30 present, we only want to pull those entries from the database. This is an efficiency concern.
The code you're after is something like this:
$link = mysql_connect(/*connection parameters go here*/);
if ($link === false)
die;
mysql_select_db('my_database');
$result = mysql_query("SELECT text, url FROM my_table LIMIT 15,30");
print "<ul>\n";
while ($row = mysql_fetch_assoc($result)) {
print "<li>{$row['text']}</li>\n";
}
print "</ul>\n";
mysql_close();
The first three lines establish a connection to the database, and exit the script if an error occurs.
The next line selects the appropriate database on the server.
The next block runs the appropriate query for the second page. After the query is run, a 'result' is stored in $result. This result is comprised of a number of rows, and mysql_fetch_assoc($result) obtains those lines one at a time. It then formats these lines into the appropriate link format and outputs them. The entire set of links is wrapped in a dot-point list.
Finally, mysql_close() closes the connection to the database.

I'm assuming since you just started you're probably doing all this procedurally.
First you want to query the database and get the info you need.
<?php
$result = mysqli_query($link, "SELECT url, text FROM table_name");
while ($row = mysqli_fetch_array($result)) $hrefs[] = $row;
foreach ($hrefs as $href) {
echo "".$href['text']."";
}
?>
Please note I've done no error handling here.

Related

Obtain Column name(s) of database via PHP

I have a postgresql database and I am connecting to and reading from it via php. Ive put in php codes that give me back the result to the query i pass from my code.
Ex- My code :(Note - My HTML page uses a form which asks for input and searches for the given input in the database)
<?php
$result = pg_prepare($dbh, "Query1", 'SELECT * FROM test.bact WHERE disease = $1');
$result = pg_execute($dbh, "Query1", array($disease));
if (!$result) {
die("Error in SQL query: " . pg_last_error());
}
//$rows = pg_fetch_all($result)
/*// iterate over result set
// print each row*/
while ($row = pg_fetch_array($result)) {
echo $row[0]." ".$row[1]. "<br />";
}
From the above piece of code I get my information as strings separated by a space ( echo $row[0]." ".$row[1])
example: Information at row[0]<space>Information at row[1]
What I want - I want the retrieved data in a more organised form i.e. with the column name.
How it should look like -
Name of Column : Data
Name of column : Data ...and so on.
I know there is way in mysql using the mysql_fetch_field, but I wanted something for postgresql. Since I am new to php n databases I am not really sure as to how will I use this.
Any help would be appreciated.
You can use pg_field_name or pg_fetch_assoc

MySQL: multiple search/select queries at the same time?

I have a question on how to go about the next phase of a project I am working on.
Phase I:
create a php script that scraped directory for all .txt file..
Open/parse each line, explode into array...
Loop through array picking out pieces of data that were needed and INSERTING everything into the database (120+ .txt files & 100k records inserted)..
this leads me to my next step,
Phase II:
I need to take a 'list' of several 10's of thousand of numbers..
loop through each one, using that piece of data (number) as the search term to QUERY the database.. if a match is found I need to grab a piece of data in a different column of the same record/row..
General thoughts/steps I plan to take
scrape directory to find 'source' text file.
open/parse 'source file'.... line by line...
explode each line by its delimiting character.. and grab the 'target search number'
dump each number into a 'master list' array...
loop through my 'master list' array.. using each number in my search (SELECT) statement..
if a match is found, grab a piece of data in another column in the matching/returned row (record)...
output this data.. either to screen or .txt file (havent decided on that step yet,..most likely text file through each returned number on a new line)
Specifics:
I am not sure how to go about doing a 'multiple' search/select statement like this?
How can I do multiple SELECT statements each with a unique search term? and also collect the returned column data?
is the DB fast enough to return the matching value/data in a loop like this? Do I need to wait/pause/delay somehow for the return data before iterating through the loop again?
thanks!
current function I am using/trying:
this is where I am currently:
$harNumArray2 = implode(',', $harNumArray);
//$harNumArray2 = '"' . implode('","', $harNumArray) . '"';
$query = "SELECT guar_nu FROM placements WHERE har_id IN ($harNumArray2)";
echo $query;
$match = mysql_query($query);
//$match = mysql_query('"' . $query . '"');
$results = $match;
echo("<BR><BR>");
print_r($results);
I get these outputs respectively:
Array ( [0] => sample_source.txt )
Total FILES TO GRAB HAR ID's FROM: 1
TOAL HARS FOUND IN ALL FILES: 5
SELECT guar_nu FROM placements WHERE har_id IN ("108383442","106620416","109570835","109700427","100022236")
&
Array ( [0] => sample_source.txt )
Total FILES TO GRAB HAR ID's FROM: 1
TOAL HARS FOUND IN ALL FILES: 5
SELECT guar_nu FROM placements WHERE har_id IN (108383442,106620416,109570835,109700427,100022236)
Where do I stick this to actually execute it now?
thanks!
update:
this code seems to be working 'ok'.. but I dont understand on how to handle the retirned data correctly.. I seem to only be outputting (printing) the last variable/rows data..instead of the entire list..
$harNumArray2 = implode(',', $harNumArray);
//$harNumArray2 = '"' . implode('","', $harNumArray) . '"';
//$query = "'SELECT guar_num FROM placements WHERE har_id IN ($harNumArray2)'";
$result = mysql_query("SELECT har_id, guar_num FROM placements WHERE har_id IN (" . $harNumArray2 . ")")
//$result = mysql_query("SELECT har_id, guar_num FROM placements WHERE har_id IN (0108383442,0106620416)")
or die(mysql_error());
// store the record of the "example" table into $row
$row = mysql_fetch_array($result);
$numRows = mysql_num_rows($result);
/*
while($row = #mysql_fetch_assoc($result) ){
// do something
echo("something <BR>");
}
*/
// Print out the contents of the entry
echo("TOTAL ROWS RETURNED : " . $numRows . "<BR>");
echo "HAR ID: ".$row['har_id'];
echo " GUAR ID: ".$row['guar_num'];
How do I handle this returned data properly?
thanks!
I don't know if this answers your question but I think you're asking about sub-queries. They're pretty straightforward and just look something like this
SELECT * FROM tbl1 WHERE id = (SELECT num FROM tbl2 WHERE id = 1);
That will only work if there is one unique value to that second subquery. If it returns multiple rows it will return a parse error. If you have to select multiple rows research JOIN statements. This can get you started
http://www.w3schools.com/sql/sql_join.asp
I am not sure how to go about doing a 'multiple' search/select statement like this?
With regards to a multiple select, (and I'll assume that you're using MySQL) you can perform that simply with the "IN" keyword:
for example:
SELECT *
FROM YOUR_TABLE
WHERE COLUMN_NAME IN (LIST, OF, SEARCH, VALUES, SEPARATED, BY COMMAS)
EDIT: following your updated code in the question.
just a point before we go on... you should try to avoid the mysql_ functions in PHP for new code, as they are about to be deprecated. Think about using the generic PHP DB handler PDO or the newer mysqli_ functions. More help on choosing the "right" API for you is here.
How do I handle this returned data properly?
For handling more than one row of data (which you are), you should use a loop. Something like the following should do it (and my example will use the mysqli_ functions - which are probably a little more similar to the API you've been using):
$mysqli = mysqli_connect("localhost", "user", "pass");
mysqli_select_db($mysqli, "YOUR_DB");
// make a comma separated list of the $ids.
$ids = join(", ", $id_list);
// note: you need to pass the db connection to many of these methods with the mysqli_ API
$results = mysqli_query($mysqli, "SELECT har_id, guar_num FROM placements WHERE har_id IN ($ids)");
$num_rows = mysqli_num_rows($results);
while ($row = mysqli_fetch_assoc($results)) {
echo "HAR_ID: ". $row["har_id"]. "\tGUAR_NUM: " . $row["guar_num"] . "\n";
}
Please be aware that this is very basic (and untested!) code, just to show the bare minimum of the steps. :)

Save image URLs in MySQL?

I actually have a few questions here: My end goal is to write a script that will automatically display all the images that i have saved inside my database(If i add new images to my database(image URLs), each time i refresh the page i would like those "new" images to be instantly displayed as well).
What is the proper way to save an image URL inside MySQL? Currently i set my input type to VARCHAR; is that okay for image URLs?
Also, at the moment i'm working with WAMP server just to test how the site is working; so i put an image inside the www folder(within the same folder as my php script) and inside the database table i simply put the URL as follows: image.png is this the correct way to enter an image URL inside my database?
What is the best way to display these images in a sequence? The following code is what i have so far:(the image widths will take up about 70% of the page so the images will not be next to each other; they will be in a column form.)
<?php
$db_host="host";
$db_user="user";
$db_pass="pass";
$db_name="name";
$db_table="table";
mysql_connect($db_host, $db_user, $db_pass) or die(mysql_error());
mysql_select_db($db_name) or die(mysql_error());
$query = mysql_query("SELECT * FROM tablename");
$result = mysql_query($query);
$num = mysql_num_rows($result);
for($count = 0; $count < $num; $count++)
{
//output the rows one by one(the actual images, not the URLs)
mysql_fetch_row($result);
echo("<br/>");
}
?>
I don't know if i should be using mysql_fetch_row in there..
I want my images to have some space in between; i was thinking the best way to accomplish that would be to add a "br" tag at the end of my loop so that every time a new image is displayed, a line break will be added to the end of the page.. Is that the best way to do it?
Thanks a bunch in advance!
To your first question, yes. To your second, also yes, if all your images are stored in the same directory. Mostly it's a matter of preference though.
Your for loop should look like this:
for($count = 0; $count < $num; $count++) {
$row = mysql_fetch_assoc($result);
echo "<img src='". htmlspecialchars($row["image"]) ."' alt='image' />";
}
br tags would probably be a bad idea. Set the images' display property to block in your CSS file. There are plenty of CSS manuals online.
With
$query = mysql_query("SELECT * FROM tablename");
$result = mysql_query($query);
$num = mysql_num_rows($result);
you do some things twice. You do not want $query to be the result of a mysql_query() call and then apply mysql_query() again.
In this case, the second call would happen with a resource object instead of a string - you got informed about it. By putting "" around, you turn it into a string again, but one which doesn't make sense to mysql.
To verify that, try to put or die(mysql_error()) to the problematic calls.
And to fix that, you can try
$query = "SELECT * FROM tablename";
$result = mysql_query($query) or die(mysql_error());
$num = mysql_num_rows($result);
BTW: you don't need $num when you replace the for loop with
while ($row = mysql_fetch_row($result))
// do stuff with $row
}
I've done a previous project based on image storage in a SQL database. the best way to store the images would be as a link, ie, '/stored_images/imagefilename.png'. When you need to reference the images just get the images into a while loop for each row in the table.
ie.
to get the images
<?php
$query = mysql_query("SELECT * FROM tablename");
while ($row = mysql_fetch_array($query)) {
echo '<img src="' . $row['column of url storage in SQL'] . '" />';
}
That will output all the images in the database, just change 'column of url storage in SQL' with the actual column name that you store in the SQL DB. also replace 'tablename' in the SQL query with the name of the table the images are being stored in.

Run script in php for items not modified yet in mysql

I have db with column named "link".
Links have redirect urls, which I want to change.
I have php script, which would take the link and gives me output as follows:
$redo = get_redirect('htp://www.mydomain.com/long/url/here&ID=123');
print_r($rez);
this is the output:
Array
(
[0] => htp://www.otherdomain.com
)
how do I loop all items in my database, and run this script for each item.
my db is called "apps" and table is called "items" and column containing urls is called "link" above php script is called getredirect.php
Also when I run script I need to run without the "&ID=123&otherstuff=whatever"
(htp supposed to be http... I can't add links per board rules)
how do I loop all items in my database, and run this script for each item
Can you just do a simple select and put it in an array, and loop through it?
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT link FROM apps");
while($row = mysql_fetch_array($result))
{
$url=implode('&', $row[0]);
include 'getredirect.php?url='.$url;
}
mysql_close($con);
Not sure whether it helps, your question is kinda unclear to me.
If you aren't sure of the output, you can put a print_r statement, i.e.,
while($row = mysql_fetch_array($result))
{
print_r($row);
include 'getredirect.php?url='.$url;
}
This would help you understand the PHP code clearer
Looks like your get_redirect is just a function that connects to DB and gets the redirect URL for a given URL.
You can write a SQL query to get redirects for all the items:
Select urls,link from apps.items;
You could also modify the function defenition so it expects multiple items and returns approporate redirects:
function get_multiple_redirect($aItems){
$SQL = "Select urls,link from apps.items WHERE url IN ('" . implode("','",$aItems) ."')";
#... add mysql calls here
print_r( get_multiple_redirect(array("http://abc","http://def")) );
}

Extract all the data from a database

Hey, I am wondering how to extract the data from a table in a database onto a table in a page (users.php),
For example:
I want to be able to get all of the usernames and all the id's from my database onto a table.
So if I have in my database:
1 - Fred
2 - Frank
3 - Margret
It will see that I have them user's and id's in the database and print them onto a table.
Any help would be great,
Thanks.
Connect to your database. Host is the location, like localhost if its on your computer, or on the same server as your code. User and Password are self explanatory.
mysql_connect("host", "user", "pass");
The name of the database you want to access.
mysql_select_db("database");
The actual mysql query.
$result = mysql_query('SELECT `User_Name`, `User_ID` FROM TABLE');
Sort it into an array
while($temp = mysql_fetch_array($result)
{
$id = $temp['User_ID'];
$array[$id]['User_ID'] = $id;
$array[$id]['User_Name'] = $temp['User_Name'];
}
Turn the array into a table. (You could skip the last step and go right to this one.
$html ='<table><tr><td>User ID</td><td>User Name</td></tr>';
foreach($array as $id => $info)
{
$html .= '<tr><td>'.$info['User_ID'].'</td><td>'.$info['User_Name'].'</td></tr>';
}
echo $html . '</table>';
Or, the formatting you wanted
$html ='User Id - User Name';
foreach($array as $id => $info)
{
$html .= $info['User_ID'].' - '.$info['User_Name'].'<br>';
}
echo $html;
(For this answer, I will use the mysqli extension -- you could also want to use PDO ;; note that the mysql extension is old and should not be used for new applications)
You first have to connect to your database, using mysqli_connect (And you should test if the connection worked, with mysqli_connect_errno and/or mysqli_connect_error).
Then, you'll have to specifiy with which database you want to work, with mysqli_select_db.
Now, you can send an SQL query that will select all data from your users, with mysqli_query (And you can check for errors with mysqli_error and/or mysqli_errno).
That SQL query will most likely look like something like this :
select id, name
from your_user_table
order by name
And, now, you can fetch the data, using something like mysqli_fetch_assoc -- or some other function that works the same way, but can fetch data in some other form.
Once you have fetched your data, you can use them -- for instance, for display.
Read the pages of the manual I linked to : many of them include examples, that will allow you to learn more, especially about the way those functions should be used ;-)
For instance, there is a complete example on the page of mysqli_fetch_assoc, that does exactly what you want -- with countries insteand of users, but the idea is quite the same ^^
You can do something like the following (using the built-in PHP MySQL functions):
// assuming here you have already connected to the database
$query = "SELECT id,username FROM users";
$result = mysql_query($query, $db);
while ($row = mysql_fetch_array($result))
{
print $row["id"] . " - " . $row["username"] . "\n";
}
which will give you (for example):
1 - Fred
2 - Frank
3 - Margret
Where I've put the print statement, you can do whatever you feel like there eg put it into a table using standard HTML etc.

Categories