How a database is loaded into an application? - php

All i need is a simple explanation on how does this function work
I also attached a piece of php which I think is the one that retrieves the data from the database. Please correct me if I'm wrong
Cheers.
function loadDatabaseRecords ()
{
// Mozilla/Safari
if (window.XMLHttpRequest)
{
xmlHttpReq = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject)
{
xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
alert ("To Server (Load Records):\n\najax-open-DB.php");
xmlHttpReq.open('GET', "ajax-open-DB.php", true);
xmlHttpReq.onreadystatechange = loadDatabaseRecordsCallback;
xmlHttpReq.send(null);
}
<?php
$link = mysql_connect ("ipaddress", "localhost", "password");
mysql_select_db ("database1");
$query = "SELECT * from addressbook";
$result = mysql_query ($query);
print "<table>";
print "<tr>";
print "<th>Firstname</th><th>Lastname</th><th>Address</th><th>Telephone</th>";
print "</tr>";
for ($i = 0; $i < mysql_num_rows ($result); $i ++)
{
$row = mysql_fetch_object ($result);
print "<tr>";
print "<td>$row->firstname</td>";
print "<td>$row->lastname</td>";
print "<td>$row->address</td>";
print "<td>$row->telephone</td>";
print "</tr>";
}
print "</table>";
mysql_close ($link);
?>

mysql_connect connects to MySQL using the hostname (ipaddress), username (localhost) and password (password). select_db then chooses the database (database1).
mysql_query queries the database for all records (select *) in a certain table (addressbook), through the connection you just made. Generally, people also reference the connection, as in mysql_query ($query, $link)
fetch_object fetches the next row from that query, one at a time, and php formats the results with td/tr, etc.

With Ajax you can update only part of your view. The information from you MySQL database on the server side is "mixed" with the current page on the client side that the user is viewing. If you have complex structures and presentation details, Ajax can save you time by skipping redundant information the client knows already. You might be interested to take a look into the JQuery load API which makes Ajax easier to use.

Related

Selecting * from table returns nothing

I wrote this php script that allows me to fetch all the rows in a table in my MySQL database.
I have put the echo "1", etc. to see whether it gets to the code at the very end. The output proves it does. However, it does not output anything when echoing json_encode($resultsArray), which I can't seem to figure out why.
Code:
// Create connection
$connection = mysqli_connect("localhost", "xxx", "xxx");
// Check connection
if (!$connection) { die("Connection failed: " . mysqli_connect_error()); } else { echo "0"; }
// select database
if (!mysqli_select_db($connection, "myDB")) { die('Unable to connect to database. '. mysqli_connect_error()); } else { echo "1"; }
$sql = "select * from myTable";
$result = mysqli_query($connection, $sql) or die(mysqli_error($connection));;
echo "3";
$resultsArray = array();
while($row = mysqli_fetch_assoc($result)) {
// convert to array
$resultsArray[] = $row;
}
echo "4";
// return array w/ contents
echo json_encode($resultsArray);
echo "5";
Output:
01345
I figured, it is not about the json_encode, because I can also try to echo sth. like $result['id'] inside the while loop and it just won't do anything.
For testing, I went into the database using Terminal. I can do select * from myTable without any issues.
Any idea?
After around 20hrs of debugging, I figured out the issue.
As I stated in my question, the code used to work a few hours before posting this question and then suddenly stopped working. #MichaelBerkowski confirmed that the code is functional.
I remembered that at some point, I altered my columns to have a default value of an empty string - I declared them as follows: columnName VARCHAR(50) NOT NULL DEFAULT ''.
I now found that replicating the table and leaving out the NOT NULL DEFAULT '' part makes json_encode() work again, so apparently there's an issue with that.
Thanks to everybody for trying anyway!

Fetching the data from sqlite3 database in php

I need some help with my PHP. I have a trouble with fetching the data from the database. I have hired a PHP developer who did not do his job properly that he have messed up the code which make it don't work so I need some help to fix the issue to get it working again.
When I try this:
//open the database File
$db = new SQLite3('myChannel.db');
if(!$db)
{
echo $db->lastErrorMsg();
}
else
{
$channel_name = $_GET['channels'];
$sql ="SELECT channel, title, start_date, stop_date, description FROM programs WHERE channel='$channel_name'";
$results = $db->query($sql);
while ($row = $results->fetchArray())
{
print_r($row);
}
What happen with the code is it will not fetching the matched data from the database as it will not do anything. I think there is something wrong with the $sql variable.
What I'm expecting to do is I want to look for data in the database where I use the variable called $channel_name, then I want to fetch the matched data to output them in my PHP.
Can you please help me how I can fetch the matched data in the database?
Try this code based on the SQLite PHP docs
class MyDB extends SQLite3 {
function __construct() {
$this->open('myChannel.db');
}
}
$db = new MyDB();
if (!$db) {
echo $db->lastErrorMsg();
} else {
$channel_name = $_GET['channels'];
$sql = "SELECT channel, title, start_date, stop_date, description FROM programs WHERE channel='{$channel_name}'";
$results = $db->query($sql);
while($row = $results->fetchArray(SQLITE3_ASSOC) ) {
print_r($row);
}
}
I changed a few things. I turned your database connection into a class, and I changed your while to include SQLITE3_ASSOC.
Warning: OP's code and as a result this answer has code that is
vulnerable to SQL Injection!

How to get a text string from sql database to use in html code

I want to get stings form a mysql server to use as text on my webpage.
That way I can edit the text without editing the html file.
Problem is that the code I have to get the string is quite long, and I don't want to paste it everywhere on the page.
I would also like a tip on how to get just one datafield from the server, and not the whole column like I do here.
So this is what I got. And what I think is to write a function I can call from all the places I want the webpage to get a string or field from the sqlserver. But I don't know how. Can anyone help me?
<?php
$con=mysqli_connect("localhost","user..", "passwd..","db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT topic FROM web_content";
$result = $con->query($sql);
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc())
{
echo $row["topic"]. "<br>";
}
} else
{
echo "error";
}
$con->close();
?>
Problem is that the code I have to get the string is quite long, and i
dont want to paste it everywhere on the page.
Put the code into a function, call that function wherever you need to. Then it is just a single line you have to insert.
PHP:
<?php
function connect() {
$con=mysqli_connect("localhost","user..", "passwd..","db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} else {
return $con;
}
}
function renderContent($con) {
$sql = "SELECT topic FROM web_content";
$result = $con->query($sql);
if ($con && ($result->num_rows > 0))
{
// output data of each row
while($row = $result->fetch_assoc())
{
echo $row["topic"]. "<br>";
}
} else {
echo "error";
}
}
HTML:
<?php $con = connect(); ?>
[...]
<div>
<?php renderContent($con); ?>
</div>
[...]
I would also like a tip on how to get just one datafield from the
server, and not the whole coloumn like i do here.
Not the whole column would mean not all rows, but one or some selected ones. That means you are looking for sqls ''WHERE'' clause.
SELECT topic FROM web_content WHERE <where clause>;
Where <where clause> is some clause to narrow down the result set. For example you can narrow down to topics containing some string: ... WHERE topid LIKE '%word%'; or by the IDs are a date range of the entries in your table. You should take a look into the documentation of the query syntax for an explanation: http://dev.mysql.com/doc/refman/5.0/en/select.html
Obviously all of this is just a rough sketch of what you are looking for. Lots of things need improving. Using exceptions for error handling is one thing, just to give an example...

Error Getting Data to Return from Database in PHP

I'm new at PHP, and trying to set up a simple test to get data to return from a temp database I set up, but I keep getting a syntax error. I've looked it over and after the process of elimination, it seems to be in this line, but I'm not sure what's wrong since I'm pretty sure it looks just like the tutorial I'm using.
while($row = mysqli_fetch_row($result)) {
Here is the all the code relevant to what I'm doing:
<?php
// Perform database query
$query = "SELECT * FROM subjects";
$result = mysqli_query($connection, $query);
// Test if there was a query error
if (!$result) {
die ("Database query failed.");
}
?>
<?php
// Use returned data (if any)
while($row = mysqli_fetch_row($result)) {
// output data from each row
var_dump($row);
echo "<hr />";
?>
I'm able to successfully make the initial connection, etc, it's just when I tried to get data to show up from the database that I got the syntax error.
It's here, you missed your closing braces
<?php
//Use returned data (if any)
while($row = mysqli_fetch_row($result)) {
// output data from each row
var_dump($row);
echo "<hr />";
} //you missed your closing braces
?>

PHP constant SQL query

I need to constantly read from my database every 1 second to get the latest values. Here is my code:
<?php
// connect to the "tests" database
$conn = new mysqli('localhost', 'root','','Test');
// check connection
if (mysqli_connect_errno()) {
exit('Connect failed: '. mysqli_connect_error());
}
// SELECT sql query
$sql = "SELECT * FROM `Value`";
// perform the query and store the result
$result = $conn->query($sql);
if (!$result)
print 'Error!';
// if the $result contains at least one row
if ($result->num_rows > 0) {
// output data of each row from $result
while($row = $result->fetch_assoc()) {
$output=$row;
print_r($output);
}
}
else {
print '0 results';
}
$conn->close();
?>
My HTML code refreshes every 1 second as follows:
function reload (){
setInterval(getData,1000);
}
function getData()
{
$.get('test.php', function(data) {
var output = data;
document.getElementById("output").innerHTML = "Info: " + output;
});
}
....
<body onload="reload();">
<p id="output"></p>
</body>
Everything works fine but after around 5-10 mins the MYSQL server crashes. I'm assuming it is being overloaded. My thoughts are that I keep running the php script every time which connects each second. Am I doing this incorrectly? Anyone have any suggestions on a better implementation?
I think you are looking for something to have the database "unclosed" when the script has ended.
In mysqli you can prepend the hostname by adding p: to use a so called persistant database connection
// connect to the "tests" database
$conn = new mysqli('p:localhost', 'root','','Test');
Read more about persistant connections here:
http://php.net/manual/en/features.persistent-connections.php
You might try having it not start the next request until 1 second after the last one finishes by calling setTimeout() in the callback like so:
function getData()
{
$.get('test.php', function(data) {
var output = data;
document.getElementById("output").innerHTML = "Info: " + output;
setTimeout(getData, 1000);
});
}
....
<body onload="getData();">
This is generally a better approach than using setInterval(), cuz you may end up having two concurrent connections and request A may start before request B, but may end after B, because something happened and it took more than a second to finish the request. This could cause some weird behavior.
This may also fix your issue, because maybe it fails because it ends up having several concurrent connections open from the same IP, etc.
Yes it can be implement in a much better way.
As you are using same Database connection configuration every-time, there is no need to connect and close database on page refresh.Connecting to database server every-second is very expensive call.
Why don't you just reload/refresh the query statement?
The idea is:
Use Persistent Database Connection
Refer BlaM answer in following post to know why persistent connections is optimal.
Put the queries in a separate div say #load.
echo '<div id="load">';
// SELECT sql query
$sql = "SELECT * FROM `Value`";
// perform the query and store the result
$result = $conn->query($sql);
if (!$result)
print 'Error!';
// if the $result contains at least one row
if ($result->num_rows > 0) {
// output data of each row from $result
while($row = $result->fetch_assoc()) {
$output=$row;
print_r($output);
}
}
else {
print '0 results';
}
echo '</div>';
Use jquery function to refresh only #load div
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$("#load").load("filename.php #load");
}15000); // refresh every 1 second
</script>
I had implemented this for auto-refresh leaderboard page.It worked perfectly and server didn't crash even in 50 hrs.

Categories