column of table cells text to links - php

I'm creating a table dynamically from a mysql database that gets fields name, email, city. The email column has emails that I'd like to have as "mailto:" links. Currently they display the email without the hyperlink. There's a 'filter' form on the page as well that when submitted will display only results that correspond with a name specified in the form textbox by the user.
I'm very novice at creating anything dynamic. What's the easiest way to display the email column as hyperlinks? I was thinking about using javascript to do a getElementByID loop for the second td of every tr and amend a "mailto:" the beginning using string manipulation. Maybe this is more practically done in PHP instead?
edit:
I realized the obvious solution to my question. I simply concatenated the a href mailto: before the echo of the php command that gets my email field from the sql db and displays it in the table.

This is, indeed, more practically done in PHP. You can use something like the following, assuming that $result contains the result of a MySQL SELECT statement which fetches the users.
while ($u = $result->fetch_assoc()) {
// Output other data
// ...
echo '' . $u['email'] . '';
// ...
}
If you're still using mysql instead of mysqli (which you shouldn't really be doing), then replace
while ($u = $result->fetch_assoc()) {
with
while ($u = mysql_fetch_assoc($result)) {

$db = new PDO(//your dsn, host and password);
$query = $db->prepare('SELECT name,email from users');
$query->execute(); while($row = $query->fetch(PDO::FETCH_ASSOC))
{
echo ''.$row['name'].'';
}

Related

How do I get only one value for the data I fetched from database using fetch function

I am new to php and had chosen to stick to PDO format. I have been able to set up a workable registration and login system, but my challenge is fetching data from my database which would be used in other page of the user profile page I created. I had tried all the many examples and methods I was able to get on the internet but there are not working, or rather I don't know how to use it, where I want to insert the variable will still be empty.
The only fetch function I was able to get will select all the row, for instance, if it is email, it will fetch all the registered emails in the database which is not suppose to be. The email should only be for the user whose profile is opened.
Here are the codes. I am sure someone will help me figure this out. Thanks
$data = $pdo->query("SELECT * FROM databaseName")->fetchAll();
//this one is in the body where i want to insert the email
foreach ($data as $row) {
echo $row['email']."<br />\n";
}
I tried everything my little knowledge of php but all to no avail. If i decide to use any other one, nothing will show.
You can try other alternative to achieve the same,
$stmt = $pdo->query('SELECT * FROM databasetable');
while ($row = $stmt->fetch())
{
echo $row['email'] . "\n";
}
If you are only interested in the email from the returned results, I would look to do the following:
$stmt = $pdo->query('SELECT `email` FROM databasetable');
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo $row['email'] . "\n";
}
Or
$stmt = $pdo->query('SELECT `email` FROM databasetable');
$data = $stmt->fetchAll(PDO::FETCH_ASSOC))
foreach($data as $row)
{
echo $row['email'] . "\n";
}
If you want to check that the data coming back is good, I would add a "print_r($data);".
You can just take the first element of the results.
$stmt = $pdo->query('SELECT `email` FROM databasetable LIMIT 1');
$data = $stmt->fetchAll(PDO::FETCH_ASSOC)[0];
or use fetch()
$stmt = $pdo->query('SELECT `email` FROM databasetable LIMIT 1');
$data = $stmt->fetch(PDO::FETCH_ASSOC);
I´ve also put a LIMIT at the end of your query, so you dont fetch unneeded data.
Unless I am missing something then surely you should be specifying a where in your SQL query, why would you get the entire database and loop through it until you find the email you want?
When you redirect the logged in user you must(or if you aren't then you should) be passing something about the user, e.g setting the userid in the session. Then you can use this to create more useful profile data with a query that says select email from table where userid = :userid - then when you fetch the result you will have the data you need.
Naturally I can't write the exact query without knowing your structure but getting a whole tables worth of data every time is unscalable

Stuck retrieving dynamic column in mysql using php

I had a custom field where user can insert text into it and thus change the database column name.
One of my pages function is to retrieve the value inside the custom column.The problem that I facing now is that i unable to retrieve the value.
For your information, I already create a function to get the name of the column.
In normal cases, i retrieve the value like this.
while($row = mysqli_fetch_assoc($result)) {
$companys[$i]['check_existing_user'] = $row['id'];
}
But for the dynamic one, I try to do something like this but it still wouldn't work.
while($row = mysqli_fetch_assoc($result)) {
$custom_field_1 = '\'customized_field_name("custom_field_1")\''; // return the column name and look like this -> 'custom_field_1'
$companys[$i]['custom_field_1'] = $row[$custom_field_1];
$i++;
}
I feel that the way I directly insert the variable is wrong but then I don't know what else i should do. Any help will be very appreciated.
if it's a PHP function you are talking about, then you have to call it like a PHP function:
$companys[$i]['custom_field_1'] = $row[customized_field_name("custom_field_1")];
or better first store the custom name in a variable and then use
$custom_field_1 = customized_field_name("custom_field_1");
while($row = mysqli_fetch_assoc($result)) {
$companys[]['custom_field_1'] = $row[$custom_field_1];
}

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

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

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