How to display all data from a table? - php

Well i've been searching google, but I still can't find out how to do this.
I'm a beginner in php so i'm really stumped.
Anyways what I need to do is get all the data from a table and display it on my page.
Like
Contents of row 1
Contents of row 2
etc.
Well that's nice, get down voted for asking for help.

This might help you
print_r() displays information about a variable in a way that's readable by humans.
print_r(), var_dump() and var_export() will also show protected and private properties of objects with PHP 5. Static class members will not be shown.
Remember that print_r() will move the array pointer to the end. Use reset() to bring it back to beginning.
http://php.net/manual/en/function.print-r.php

This is pretty much PHP DB access 101
$pdo = new PDO('mysql:host=localhost;dbname=myDbName', 'username', 'password');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare('SELECT * FROM a_table');
$stmt->execute();
$resultSet = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($resultSet as $idx => $row) {
echo '<p>Contents of row ', $idx + 1, '</p><dl>';
foreach ($row as $col => $val) {
printf('<dt>%s</dt><dd>%s</dd>',
htmlspecialchars($col),
htmlspecialchars($val));
}
echo '</dl>';
}

I think google should have given you your answer since this is a rather easy to answer question, but when starting, you don't always know what to search for.
Anyways, hope this helps.
<?php
// connect with you database, returns boolean so you know if you succeeded or not
$con = mysql_connect($database,$username,$password);
if(!$scon){
die('Could not connect to database'); // Stop execution if connection fails
}
//create your query
$query = "Place your database query here";
//get the results
$result = mysql_query($query);
//now you want to go through each row of the result table and echo the contents, or
//use them for whatever reason
while($row = mysql_fetch_array($result)){
echo $row['field_you_want_to_display'];
echo $row['another_field_you_want_to_display']; //You see where this is going
}
//After doing what you want, close the connection to the database
mysql_close($con);
?>
Also, you may want to take a look at the documentation of php for find out what functions you have not seen before do.

Related

Moving Query to MySQLi

I'm updating some old code that has deprecated MySQL functions. But for some reasons I cannot get all the results from the column. The strange part is that if I run the query directly on the server I get all results fine. So this is an issue with PHP getting the results, not the MySQL server or my query.
Here is the new and old code:
My current updated code:
$sql = "SELECT user, monitor FROM users WHERE `status` = 'y'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
// This works. It shows all results
echo $row["user"];
// This does not work! Only shows one result:
$account= $row["user"];
}
else {
echo 'No results';
}
When I use that query directly on DB server, I get all results. So the SQL query is correct. I actually also get all results as well in PHP if I echo the row directly like:
echo $row["user"];
But for some reason when I try to use it with a PHP with variable it only lists one user result.
In the past I used this but the mysql_fetch_array function is now deprecated
while ($row = mysql_fetch_array($result)) {
array_push($data, $row["user"]);
}
foreach($data as $value) {
$account = $value
}
I cannot use my previous code anymore as those MySQL functions are obsolete today. I need to write the results into a file and my old method worked fine. The new one using mysqli does not.
Any suggestions?
You just need to add one of these [, and one of these ].
$account[] = $row["user"];
// ^^ right here.
$account= $row["user"]; means you're storing the value of $row["user"] in $account each time the loop executes. $account is a string, and it gets a new value each time.
$account[] = $row["user"]; means you're appending each value of $row["user"] to an array instead.
You should not use array_push for this. It's overkill for appending a single value to an array. And if the array isn't defined beforehand, it won't work at all.

Query for multiple SQLite tables with PHP

Forgive me if my question sounds stupid as I'm a begginer with SQLite, but I'm looking for the simplest SQLite query PHP solution that will give me full text results from at least three separate SQLite databases.
Google seems to give me links to articles without examples and I have to start from somewhere.
I have three databases:
domains.db (url_table, title_table, date_added_table)
extras.db (same tables as the first db)
admin.db (url_table, admin_notes_table)
Now I need a PHP query script that will execute a query and give me results from domains.db but if there are matches also from extras.db and admin.db.
I'm trying to just grasp the basics of it and looking for a starting point where I can at least study and learn the first code.
First, you connect to 'domains.db', query what you need, save however you want, than if there were a result in the first query, you connect to the others and query them.
$db1 = new SQLite3('domains.db');
$results1 = $db1->query('SELECT bar FROM foo');
if ($results1->numColumns() && $results1->columnType(0) != SQLITE3_NULL) {
// have rows
// so, again, $result2 = $db2->query('query');
// ....
} else {
// zero rows
}
// You can work with the data like this
//while ($row = $results1->fetchArray()) {
// var_dump($row);
//}
Source:
http://php.net/manual/en/sqlite3.query.php
http://php.net/manual/en/class.sqlite3result.php
Edit.: A better approach would be to use PDO, you can find a lot of tutorials and help to use it.
$db = new PDO('sqlite:mydatabase.db');
$result = $db->query('SELECT * FROM MyTable');
foreach ($result as $row) {
echo 'Example content: ' . $row['column1'];
}
You can also check the row count:
$row_count = sqlite_num_rows($result);
Source: http://blog.digitalneurosurgeon.com/?p=947

Can someone explain the principle behind this simple code please?

Im having difficulty comprehending a line of code that i am using to retrieve results from a mysql database.
I connect to the database with
<?php
try
{
$pdo = new PDO('mysql:host=localhost;dbname=****', '****',
'****');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('SET NAMES "utf8"');
}
catch (PDOException $e)
{
$error = 'Unable to connect to the database server.' . $e->getMessage;
echo $error;
exit();
}
this is fine. the connection works.
to retrive the results i use this code....
$sql = 'SELECT joketext FROM joke';
$results = $pdo->query($sql);
this also is fine but then i use a foreach loop to loop through the result set as so...
foreach ($results as $result){
$jokes[] = $result['joketext'];
}
and then another foreach to loop through $jokes as so...
foreach ($jokes as $joke) {
echo $joke;
}
now this all works it displays the joketext i wanted from the mysql table. However i dont understand the line...
$jokes[] = $result['joketext'];
does this means I am assigning the result set to an array? what does $jokes[]= mean? and why do i have to do this?
I thought i was retrieving strings of text from the database table. The table has an id, joketext, jokedate, and authorid as columns. But if im only selecting the joketext column surely that retrieves a list of all the joketext entries and therefore i can just loop through with a foreach echoing out the results?
The $jokes[] syntax is appending the joke text string to the $jokes array. If the array doesn't exist, it will be created.
It's the same as doing:
array_push($jokes, $result['joketext']);
If you don't need to create a new array, you can just work with the joke text directly in the $results foreach, if you prefer.
your query only selects for one column joketext so you don't have any of the other column data in your result set.
Using $jokes[] = .. is a shorthand way of assigning a value to a new element in the $jokes array. You don't necessarily need to do this. It is just commonly done so that you can use the data later on, in multiple places if you want. Alternatively, you can just work with the result set directly each time. That isn't as commonly done though since the result set is an object or resource that contains more than what you may actually need. But if you're just looking to output the joketext immediately, then you can skip putting it into a separate array and just echo $result['joketext']; in your first loop
$jokes[] = appends a new value to an array and is the same as doing $jokes[count($jokes)] (not completely correct but is a simple way of explaining it).
Technically, you don't have to put all the values in a new array, you could use the original loop instead.
array_push has the same functionality, you can read up about it here
If I understand you correctly then I believe you are correct. The second foreach is not needed, you can simply echo the $result['joketext'] during the first foreach and skip the second one altogether.
so delete the second foreach and edit the first one as follows:
foreach ($results as $result){
echo( $result['joketext'] );
}

Problems getting MySql data into an index using Zend_Search_Lucene

Trying to use Zend_Search_Lucene to search a MySql database and display the results. Running the following code and can't figure out why I'm not getting any info into my index. Quite new with PHP, MySql and Zend but I've spent the last week trying to figure this out on my own and have exhausted every resource I could find. Anyway, I echoed what's coming out of my database to make sure my query worked which seems to be OK. It also creates the index files just fine but when I've taken a look at it with the Luke Toolbox I get nothing but a list of the fields created filled with gooseggs. Just to make sure I'm using that correctly I found some code using Zend_Feed and ran that through Lukes and got all kinds of results. Also able to get results from that same code on my result test page but getting 0 when using the code below. Seems I can't get the database info indexed although the count tells me that 5 documents have been indexed (which is the number of rows I have in my database table) and I'm not getting any errors. The library script is just an autoloader script and where I set up my db connection which I've confirmed works as well. Although it's likely I'm missing the obvious or demonstrating what a novice I truly am, any help would be much appreciated.Thanks.
<?php>
require_once('scripts/library.php');
require_once ('Zend/Search/Lucene.php');
$index = Zend_Search_Lucene::create('./docindex');
$sql = ('SELECT * FROM news');
foreach ($db->query($sql) as $row){
echo $row ['author'];
echo $row['headline'];
echo $row ['source'];
}
foreach ($row as $document){
$document = new Zend_Search_Lucene_Document ();
$document->addField(Zend_Search_Lucene_Field::Text ('author', $docAuthor));
$document->addField(Zend_Search_Lucene_Field::Text ('headline', $docHeadline));
$document->addField(Zend_Search_Lucene_Field::Text ('source', $docSource));
$document->addField(Zend_Search_Lucene_Field::Unstored ('contents', $docStory));
$index->addDocument($document);
}
$index->commit();
echo $index->count()." documents have been indexed.\n";
?>
It looks like you had an extra foreach() that wasn't really doing anything and I couldn't see where your data variables were assigned, try this it should be pretty close:
<?php
require_once('scripts/library.php');
require_once ('Zend/Search/Lucene.php');
$index = Zend_Search_Lucene::create('./docindex');
$sql = ('SELECT * FROM news');
foreach ($db->query($sql) as $row) {
echo $row ['author'];
echo $row['headline'];
echo $row ['source'];
$document = new Zend_Search_Lucene_Document ();
//you use an unindexed field for the id because you want the
//id to be included in the search results but not searchable
$document->addField(Zend_Search_Lucene_Field::unIndexed('id', $row['id']));
$document->addField(Zend_Search_Lucene_Field::Text('author', $row ['author']));
$document->addField(Zend_Search_Lucene_Field::Text('headline', $row['headline']));
$document->addField(Zend_Search_Lucene_Field::Text('source', $row ['source']));
$document->addField(Zend_Search_Lucene_Field::Unstored('contents', $row['docStory']));
$index->addDocument($document);
}
$index->commit();
echo $index->count() . " documents have been indexed.\n";
?>

MySQL query within foreach loop

I want to show all text messages from db where id=$e ($err is an array).
Inserted the query into the foreach loop, it works well but it does extra work (does query for every value of array).
Is there any other way to do it (i mean extract query from foreach loop)?
My code looks like this.
foreach ($err as $e)
{
$result = $db -> query("SELECT * from err_msgs WHERE id='$e'");
$row = $result -> fetch_array(MYSQLI_BOTH);
echo "<li><span>".$row[1]."</span></li>";
}
It is much more efficient to do this with implode() because it will only result in one database query.
if (!$result = $db->query("SELECT * FROM `err_msgs` WHERE `id`='".implode("' OR `id`='",$err)."'")) {
echo "Error during database query<br />\n";
// echo $db->error(); // Only uncomment this line in development environments. Don't show the error message to your users!
}
while ($row = $result->fetch_array(MYSQLI_BOTH)) {
echo "<li><span>".$row[1]."</span></li>\n";
}
Check the SQL IN clause.
Firstly, a bit of a lecture: embedding strings directly into your queries is going to cause you trouble at some point (SQL injection related trouble to be precise), try to avoid this if possible. Personally, I use the PDO PHP library which allows you to bind parameters instead of building up a string.
With regard to your question, I'm not sure I have understood. You say that it does extra work, do you mean that it returns the correct results but in an inefficient way? If so then this too can be addressed with PDO. Here's the idea.
Step 1: Prepare your statement, putting a placeholder where you currently have '$e'
Step 2: Loop through $err, in the body of the loop you will set the place holder to be the current value of $e
By doing this you not only address the SQL injection issue, you can potentially avoid the overhead of having to parse and optimise the query each time it is executed (although bear in mind that this may not be a significant overhead in your specific case).
Some actual code would look as follows:
// Assume that $dbdriver, $dbhost and $dbname have been initialised
// somewhere. For a mysql database, the value for $dbdriver should be
// "mysql".
$dsn = "$dbdriver:host=$dbhost;dbname=$dbname";
$dbh = new PDO($dsn, $dbuser, $dbpassword);
$qry = "SELECT * from err_msgs WHERE id = :e"
$sth = $dbh->prepare($qry);
foreach ($err as $e) {
$sth->bindParam(":e", $e);
$sth->execute();
$row = $sth->fetch();
// Prints out the *second* field of the record
// Note that $row is also an associative array so if we
// have a field called id, we could use $row["id"] to
// get its value
echo "<li><span>".$row[1]."</span></li>";
}
One final point, if you want to simply execute the query once, instead of executing it inside the loop, this is possible but again, may not yield any performance improvement. This could be achieved using the IN syntax. For example, if I'm interested in records with id in the set {5, 7, 21, 4, 76, 9}, I would do:
SELECT * from err_msgs WHERE id IN (5, 7, 21, 4, 76, 9)
I don't think there's a clean way to bind a list using PDO so you would use the loop to build up the string and then execute the query after the loop. Note that a query formulated in this way is unlikely to give you any noticable performance improvment but it really does depend on your specific circumstances and you'll just have to try it out.
You can do this much simpler by doing
$err_csv = implode("','",$err);
$sql = "SELECT FROM err_msgs WHERE id IN ('$err_csv')";
$result = $db -> query($sql);
while ($row = $result -> fetch_array(MYSQLI_BOTH))
{
echo "<li><span>".$row[1]."</span></li>";
}
That way you don't have to keep sending queries to the database.
Links:
http://php.net/manual/en/function.implode.php

Categories