How to I pull information from MySQL with PHP? - php

I am asking if it is not only possible to pull data from a MySQL table, but also display each row in either a table or a DIV, preferably a DIV. How would I do so?
Table:
ID |BodyText |Title |
1 |Hello World1 |Title1 |
2 |Hello World2 |Title2 |
etc..
I'd like to put each row into a DIV that has a title and also bodytext, but I want php to generate these tables and put the info into each DIV.
Possible to do?

We will use this table as an example data set:
Database Name: friends
-----------------------------
| firstname || lastname |
----------------------------
|Chris || Geizz |
|Steve || Michalson |
|Ken || Bohlin |
|Doug || Renard |
-----------------------------
First you must connect to your database as so:
http://www.w3schools.com/PHP/php_mysql_connect.asp
You would run a MYSQL query to get the data from the MySQL Database:
$query = mysql_query("SELECT * FROM friends");
Then you would use the following to put them into a table:
echo "<table><tr><td>First Name</td><td>Last Name</td></tr>";
while($row = mysql_fetch_array($query))
{
echo "<tr><td>";
echo $row['firstname'];
echo "</td><td>";
echo $row['lastname'];
echo "</td></tr>";
}
echo "</table>";
What this basically does is pulls the information that is returned with my mysql_query and puts it into an array that you can call with the $row variable we set. We do this in the while loop so that it repeats for all records in your database.
The code before the while loop and after the while loop are there so that way it is all in one table and we are just making rows instead of separate tables for each row in your database.
This will accomplish what you want. When you are doing the while loop you can use the variables ($row['firstname'] and $row['lastname']) as you wish. You could place them in seperate DIV's if you wish as well.
Hope this helps you! If you have any questions leave a comment and I will respond.

Basically you can do whatever you want, once you have the rowset. The general structure of such code (if layers not devided / MVC) looks like this:
connect to db
write query
retrieve results
loop for each row in resultset
{
echo html and column content as you wish
}
so for example you could use
foreach ($rowset as $row)
{
echo '<div>'.$row['column1'].' is a friend of '.$row['column2'].'</div>';
}

Here's the manual pages for how to access/query MySQL databases:
MySQL: http://www.php.net/manual/en/book.mysql.php
MySQLi: http://www.php.net/manual/en/book.mysqli.php
Using the functions there you can easily query and display the data as you see fit. If you are wanting to access column info (field names) you either need to use the access the information_schema tables or use queries like describe table.
Update: based on the comments, the question relates more to Tharkun's answer than this.

<?php
$result = mysql_query("SELECT * from table");
if($result && mysql_num_rows($result))
{
$numrows = mysql_num_rows($result);
$rowcount = 1;
while($row = mysql_fetch_assoc($result))
{
print "<div><b>$rowcount</b>";
foreach($row as $var => $val)
{
print"|$var: $val|";
}
print "</div>";
++$rowcount;
}
}
?>

Related

Selecting random rows using MySql and using the same row information on another page

I have a working quiz now, where I receive a selection of 3 random rows from a database currently of only 5 rows (expansion in progress). The database of format:
| id | question | option1 | option2 | option3 | answer |
--------------------------------------------------------
| 1 | What is my name? | Dave | Bob | Charles | Linda |
Within connect.php: (I am aware MySql statements are deprecated and will be updating to MySQLi in due course)
$query="SELECT * FROM (SELECT * FROM mytable ORDER BY rand() LIMIT 3) T1 ORDER BY id";
$result = mysql_query($query, $connect);
Then within quiz.php:
require (connect.php);
while($row = mysql_fetch_assoc($result)) {
echo '<p>';
echo $row['id'] . '. ';
echo $row['question'];
echo '</p>';
}
Radio buttons are generated within the while loop which associate the options with the generated question, this section works perfectly even with randomisation so is not included above.
Before I began attempting randomisation of the database row selections I could use the same while loop in quiz.php and quizresults.php as they would both select the same 5 rows which was perfect. But now I have decided to randomise the selection I can't use the same while loop within each page as it selects a random 3 rows for the quiz.php (the question section) and then selects a different random 3 rows for the quizresults.php which isn't ideal when the results don't match the questions...
So what I want to do is when the query is made in quiz.php, I want to assign all of $row 's values to a mutlidimensional array (i think) and then use that array within quizresults.php to echo those rows with all the values from the original query using I'm hoping the same format as within the results page.
Within quizresults.php:
require (connect.php);
while($row = mysql_fetch_assoc($result)) {
echo '<p>';
echo $row['id'] . '. ';
echo $row['question'];
echo '</p>';
}
It uses the same loop to print the questions but obviously with some radio button verification code, which I trimmed for the purpose of the question.
So to summarise, my question is: How can I achieve randomisation in the quiz.php (questions page) and then use the selection of random rows within the quizresults.php (answer page) without using the same query?

Deleting specific records after showing them

I am learning php and I am trying to learn how to show a sql table and be able to delete specific id's in a table.
In the code below, I am echoing a table called Project. My table is only showing Projects created by this user. All this works fine.
I would now like to let the user delete a specific project with a button shown next to each project.
<?php
if( isset($_COOKIE['user_id_cookie']) ){
$my_Query = "SELECT * FROM Project WHERE user_id=".$_COOKIE['user_id'];
$result = mysqli_query($con, $my_Query);
echo "<table id=\"table\"><thead class=\"thead\"><th>Project Name</th><th>Date Modified</th></thead>";
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
echo "<tbody><tr><td>".$row['Name_Project']."</td><td class=\"date\">".$row['Date_Project']."</td></tr></tbody>";
}
echo "</table>";
mysqli_close($con);
}
?>
I imagine it looking like this in the end:
||Project Name | Date Modified | ||
|| some name | some date | Delete ||
I would like Something looking like this
How would I best go about this?

Get row values as column names using Codeigniter and mysql

im using codeigniter and mysql as db. i know might can be solved with mysql query, but if anyone can solve with codeigniter query it will be awesome, otherwise normal PHP mysql query can work also.
I have Table with 3 columns, Well it have many feilds but i have shown here 4 enteries, i didnt wanted to make a table with many columns but only 1 row of data. so instead i went for this style of table as someone suggested me on this website.
Problem is i never worked with this kind of table.
SettingsID SettingsKey SettingsValue
----------------------------------------------------------------------
1 | facebookLink | facebook.com
2 | twitterLink | twitter.com
3 | youtubeLink | youtube.com
4 | googlePlusLink | googleplus.com
Now i want to run a query that should return me rows in to columns. i searched over net and found some solutions but i am not good with this new queries.
I suppose this guy had same kind of problem like i have but in his case he has same value repeated in column, where my SettingsKey has all the values unique.
Here is the link to similar kind of question :
mysql select dynamic row values as column names, another column as value
i cant understand his query and that query i am not sure if is any use of me.
Please can anyone help me build a query to return row values of SettingsKey as columns.
This should work:
<?php
$db = new PDO('mysql:host=localhost;dbname=DBNAME;charset=utf8', USERNAME, PASSWORD);
$stmt = $db->query("SELECT SettingsKey, SettingsValue FROM Settings");
$links = array();
while($row = $stmt->fetch()) {
$links[$row['SettingsKey']] = $row['SettingsValue'];
}
$db = null;
This code queries this table and for each row the SettingsKey and the SettingsValue will be shown.
Now you can get the facebookLink like this:
echo $links['facebookLink'];
Hope this helps.
$sql = "
SELECT SettingsKey, SettingsValue
FROM Settings
";
$q = $this->db->query($sql);
return $q->result_array();
Go to your controller
$data['settings'] = $this->model_selection->your_function();
$this->load->view('example', $data);
And lasty on your view
<?php if(!empty($settings)): ?>
<?php foreach($settings as $k => $v): ?>
//print your staff in here mix with html and go crazy
<?php endforeach; ?>
<?php endif ?>

Creating links with tables names that show table information when clicked

I'm trying to create a page that shows the name of multiple mysql tables and creates a link for each one. When a user clicks a link, he's taken to a page that shows him the table contents.
For example:
Link with table name.
Table name
The user clicks the link and is taken to the page contents.php. That page prints the table contents.
For example if I have a table with Name and Age columns and John and 24 inserted in the columns, the page would print John and 24.
I appreciate if anybody can help me.
It would be way easier to do this with a GET request rather than a post request.
Table name
Then in your contents.php file:
<?php
$tablename = $_GET["tableName"]
/* all your queries that you want to do with tablename goes here */
?>
try this one...
$result = mysql_query("show tables"); // run the query and assign the result to $result
while($table = mysql_fetch_array($result)) { // go through each row that was returned in $result
echo "<a href=\"content.php?tableName=".$table[0]."\" >".$table[0] . "</a><BR>"; // print the table that was returned on that row.
}
content.php...
if(isset($_GET["tableName"]))
{
$select="select *from ".$_GET["tableName"];
$result=mysql_query($select);
while($row=mysql_fetch_array($result))
{
echo $row["name"];
echo $row["age"];
}
}

MySQL while loop query inside other while loop query

<?php
include 'config.php';
$conn = mysql_connect("$hostname", "$username", "$password") or die ("Failed to connect to DB.");
mysql_select_db("$dbname",$conn);
$sql="SELECT * FROM opdrachten";
$result=mysql_query($sql,$conn);
while ($row= mysql_fetch_array($result))
{
echo $row['name'];
echo "<br>";
$opdrachtid = $row["id"];
$sql2="SELECT * FROM resultaten WHERE(opdrachtid='".$opdrachtid."')";
$result2=mysql_query($sql2,$conn);
while ($row2= mysql_fetch_array($result2))
{
echo "
<li>
<a href=\"result.php?id=".$row2["id"]."\">
<img src=\"".$row2["img"]." \"width=\"150\" height=\"150\">
<div><span>TEXT HERE</span></div>
</a>
</li>";
}
}
?>
What I want my code to do is (in a loop):
Fetch all rows from the table 'opdrachten' and echo their 'name'.
Grab the 'id' from each of the rows in 'opdrachten' > store in variable $opdrachtid
Fetch rows from table 'resultaten' where 'opdrachtid == $opdrachtid' (which I just stored)
Echo the 'id' and 'img' from the rows fetched from 3.
What I want to see on my page:
The name of the 'opdrachten' (objective) in table 'opdrachten'
with directly underneath
The images (the url's of which are stored in table 'resultaten')that are assigned to these objectives (WHERE opdrachten.id = resultaten.opdrachtid)
I've looked into JOIN since that's the answer to most of the related topic's I've read here, but that doesn't seem to be what I'm looking for since I'm echo'ing in the first while and declare variables that are used for the second query.
Tables used:
'resultaten'
id | opdrachtid | name
'opdrachten'
id | name
Again, resultaten.opdrachtid == opdrachten.id
Thanks in advance, appreciate the help :)
I would certainly suggest using a JOIN here that way you can get all this data in one go. I will add one caveat however - this would take more memory that querying the database in a loop like you are currently doing, so if you have a large number of rows in either table, this might not be a suitable approach.
The query would simply be:
SELECT * FROM opdrachen
INNER JOIN resultaten ON opdrachen.id = resultaten.opdrachenid
You can then set up an array that is keyed on each id very simply like this:
$array = array();
while ($row = mysql_fetch_array($result)) {
$array[$row['id']][] = $row;
}
This give you an easy way to iterate through the results, one id at a time like this:
foreach ($array as $id => $rows_for_id) {
// output stuff for row group
foreach ($rows_for_id as $resultaten_row) {
// output stuff for resultaten rows
}
}
A few other suggestions:
Don't use mysql_* functions as they are deprecated. Learn how to use mysqli or PDO.
Don't use SELECT * queries. Its is lazy and wastes bandwidth, transfer time, and system memory. Only query for the specific fields you are actually interested in. So replace the * in my example with the actual field you need.
SELECT opdrachten.*, resultaten.* FROM opdrachten
INNER JOIN resultaten
ON resultaten.opdrachtid = opdrachten.id;
just use this as the original sql statement and iterate over it.

Categories