Extract all the data from a database - php

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.

Related

Viewing all of table with php and mysql

So, I have pretty limited knowledge when it comes to mysql. Usually when dealing with content on our site, I'm used to loading it from expressionengine, our cms, which I know fine. But recently I have to update this page that loads its data directly from our database. I took a course on mysql a while back, but I still don't really know how to use it.
The page doesn't need to use too much information, its basically just a list of awards presented to different businesses. I assume the table on the database just has a column for Business name, City, Year, and Type of award won. Stuff like that.
Now accessing the database doesn't seem like it would be too hard, and I feel like I could google around and find what I need. But to get started, I would just like to see the actual table! Why is it so complicated of a procedure to do?
The code on the file that I'm working on was set up like this to access the database:
$user_name = "xxxxxxxxxx";
$password = "xxxxxxxxxx";
$server = "xxxxxxxxxx";
$database = "xxxxxxxxxx";
$conni = new mysqli($server, $user_name, $password, $database);
if (mysqli_connect_errno()) {
printf("<center>
<strong>No connection to database possible!<br />
Please contact us!</strong>
</center>");
exit();
}
I figured out how to view all tables on the database, by doing this:
$result = mysql_query("show tables");
while($table = mysql_fetch_array($result)) {
echo($table[0] . "<BR>");
}
So I know the name of the table I'm dealing with. I found a way to see all the column names:
$query = "select * from my_tablename";
$result = mysql_query($query);
$numcolumn = mysql_num_fields($result);
for ( $i = 0; $i < $numcolumn; $i++ ) {
$columnnames = mysql_field_name($result, $i);
echo $columnnames . "<br>";
}
But I still can't find how to just display the table itself. I might be thinking about this wrong, or not have the full idea, but what I want is a simple way to display the entire table, like with an html table. How can that be done?
You can build the <thead> of a table with the column names you have above, however to display the results in a table format, use the mysql_fetch_row function on the $result of SELECT * FROM my_tablename. To reuse the $result after you've got the field names as in your last block, use mysql_data_seek:
mysql_data_seek($result, 0);
And then you can iterate through your results to get the contents of the table:
while ($row = mysql_fetch_row($result)) {
echo '<tr>';
foreach ($row as $value) {
echo '<td>' . $value . '</td>';
}
echo '</tr>';
}
mysql_fetch_row will get a numerically indexed array with where each value is the column value in MySQL, therefore by running foreach you get the value of each column. Put it inside of a <td>, wrap it all in a <tr> and you have yourself a table!
Just for good measure, you should switch to using mysqli in PHP as the mysql_ functions are deprecated in later versions. To switch over, use the PHP documentation to search for the mysql_ functions you're currently using, there will be a pink message which will direct you to the mysqli equivalents

How to Display Joomla database table using native joomla 2.5 php objects

I am trying to display data from a MySQL database table using the native joomla PHP objects, however I can never get it to work right. It never displays any data.
I know how to display the data by connecting to the database the old fashion way, like below...
$con = mysqli_connect("localhost","xxxxxx_user10","$dbpass","xxxxxxx_final");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} else {
//What is the base model
$sku = $finish;
// Select The Correct Table
$result = mysqli_query($con,"SELECT * FROM BAH_finish WHERE color_value='$sku' GROUP BY uniqueID ORDER BY uniqueID ASC");
$row = mysqli_fetch_array($result);
$finishname = $row['color_name'];
$finishtype = $row['color_type'];
However i'd like to display content like I have above, but by using the joomla native php objects, so iv'e created a sample php table with the following fields.....
| ID | Last | First | Address | City | State | ZIP
and tried to display it (ALL ROWS) / OR (ONE ROW) using the following joomla code.....but nothing happens....no matter how I try to switch it up or change out parts of the code....So my thinking is that i'm missing a fundamental part of how this should work....Thanks again for your help! Also please do not quote joomla 2.5 component tutorial from joomla.org...that is where I've gotten this code and IMO it lacks a lot of information.
<?php
// Get a db connection.
$db = JFactory::getDbo();
// Create a new query object.
$query = $db->getQuery(true);
// Select all records from the user profile table where key begins with "custom.".
// Order it by the ordering field.
$query->select($db->quoteName(array('Last', 'First', 'Address', 'City', 'State', 'ZIP')));
$query->from($db->quoteName('111testnames'));
$query->where($db->quoteName('Last') . $db->quote('buffet'));
// Reset the query using our newly populated query object.
$db->setQuery($query);
// Load the results as a list of stdClass objects (see later for more options on retrieving data).
$results = $db->loadObjectList();
echo $results;
?>
You have to correct: $query->from($db->quoteName('111testnames'));
to $query->from($db->quoteName('#__111testnames'));
using #__ automatically adds the suffix of your table.
Another error that I could see is the where clause doesn't have have an operator. Please try to correct it to $query->where($db->quoteName('Last') ." = ". $db->quote('buffet'));.
In order to have a proper view of the results you have to use print_r($results); instead of echo $results; as there is an object array you have to display not a string.
Good Luck!

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. :)

URL and link text from database

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.

Categories