PHP constant SQL query - php

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.

Related

How to store <li>-item created by user server sided (mySQL)

I have a simple <ul> where you can add a list item with an input field:
$('#plannerform').submit(function(e) {
var val = $(this).find('#plannername').val();
$('ul.plannerlist:visible').append('<li>' + val + '</li>');
e.preventDefault();
});
My question is: Is it possible in a way to save this created list on a mySQL database on a webserver? I haven't got much experience in PHP or other languages for server sided storage. And if it's possible, can you tell me any links where it's explained how? I spent some time already with searching, but I didn't find anything because I simply don't know what to search after.
Here is a simple php script that I wrote to connect to my MySQL DB, and retrieve along with display each result in a given column.
Just replace:
Hostname with probably your local IP if MySQL is installed on your local machine.
Your MySQL username, probably root if you haven't created another user.
The password, which could be blank if you didn't create one.
Database with the name of your Database.
<?php
//Connect to DB
$conn = new mysqli("Hostname","Username","Password","Database");
//If the connection has errors
if ($conn->connect_error){
//Display the error
die("Connection failed because: " . $conn->connect_error);
}
//Otherwise the connection is good so lets create a sql query
$sql = "SELECT * FROM Database";
//Get the results of the query
$result = $conn->query($sql);
//If the results have rows
if($result->num_rows > 0){
//While there are more rows in the results
while($row = $result->fetch_assoc()) {
//Display in HTML paragraph form: Column1 = DataInColumn1
echo '<p> Column1 = ' . $row["Column1"] . ' </p>';
}//End While
}//End If
//Otherwise the query had no results
else{
echo '<p>No results found!</p>';
}
?>

One column table into an array

I read most of the posts related to my question but none can resolve my simple issue.
I am using PHP and MySQLi to retrieve data from my server.
In my Database I have a one-dimensional table (i.e. one column only) and I want to put its data inside an array.
Until now I was using JSON to hold the data from my server.this is my code:
<?php
include 'ChromePhp.php';
$con=mysqli_connect("197.168.240.100","jsoncloud","nuahyu,hs","json");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
ChromePhp::warn('Failed to connect to MySQL');
}
$sql="SELECT `street` FROM `users` ";
$result=mysqli_query($con,$sql);
$rows = array();
while ($row = mysqli_fetch_all($result,MYSQLI_ASSOC)) {
$rows[] = $row[0];
}
echo json_encode($rows);
// Free result set
mysqli_free_result($result);
mysqli_close($con);
?>
My final goal is to echo the array back so I can use it with Ajax in another JS file
in the other JS file I have the following code:
$.ajax({
type: 'POST',
url: 'js/SQLusersstreets.php',
dataType: 'json',
success: function(jsonData) {
console.log(jsonData);
},
error: function() {
alert('Error loading SQLusersstreets.php from GoogleMapsCode.js');
}
});
This is my output when I open the browser's debugger:
I am trying to return a simple array, what am I doing wrong?
Change mysqli for PDO
Assuming a connection is already established, you will need only one line of code:
echo json_encode($pdo->query("SELECT `street` FROM `users`")->fetchAll(PDO::FETCH_COLUMN));
but if you prefer to write a lot of code, then change fetch_all to fetch_assoc
try this, if this is what you are asking about:
for($i=0;$i<sizeof($rows);$i++){
echo $rows[$i]['id']; //for example
}
mysqli_fetch_all is a shortcut for while($row = mysqli_fetch) {}, so you can skip the while cycle.
$sql="SELECT DISTINCT `street` FROM `users` ";
$result=mysqli_query($con,$sql);
$rows = mysqli_fetch_all($result,MYSQLI_ASSOC);
echo json_encode(array_map(function($i) { return $i['street']; }, $rows));
See the documentation here for more examples http://php.net/manual/en/mysqli-result.fetch-all.php

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

How a database is loaded into an application?

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.

Executing multiple update statements in PHP

I have three update statements to be executed in PHP, i am getting the values of all these as return parameters. How to execute each statement independely and finally show the end user the result that it has been successfully updated.
<?php
public function name($parameter1,$parameter2.... $parametern) {
}
?>
Then how finally we can get the result in my row object.
Ah i think i see, well looks to me from your update statements that you want to update 3 different tables which all depend on 'tycodashboard'.
In that case i advise you use transactions to retain a bit of data integrity, otherwise say if one fails? you'll have lost some data. As a general rule, if you need to do more than 1 update simultaneously use transactions.
Heres a great article on the subject: http://dev.mysql.com/doc/refman/5.0/en/commit.html
Its quite easy to do, just make you sure your tables are using the INNODB, then all you have to do is append START TRANSACTION to the top of your sql script and then COMMIT at the end.
You might be trying to combine too much into a single function, whenever i'm updating multiple tables, it's easier to just handle each one in turn, rather than trying to stuff them all into one return. So try making a function that saves it, returning success or failure, then call it from your main function for each one of your sql scripts passing in the values.
//This is the function that gets called from your page.
public function my_called_function() {
//your sql script (using "" means you can put variables in without having to remove the quotes)
$sql = "UPDATE....SET 'col' = $_POST['myvalue']";
//Run your script and get result
$result = $this->save_my_stuff($sql);
//if not null means success!
if($result) {
echo 'success!'; // your success message
}
else {
echo 'something bad happened'; //your failure message
}
}
//this is the function that does the saving!
private function save_my_stuff($sql_script) {
//Make connection
$conn = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
//Check connection
if(!$conn) {
//connection failed
die('Could not connect: '.mysql_error());
}
//Select your database using your connection object
mysql_select_db(DB_NAME, $conn);
//try and save
try {
//run the query
$result = mysql_query($sql_script, $conn);
//return the result
return mysql_result($result);
}
catch (Exception $e) {
//deal with exception
return null;
}
//close connection
mysql_close();
}

Categories