MySQL Update big amount of html content issue - php

I've created autosave via Ajax for my content management system. Having problem. Problem is, when i'm testing on my local server, the php side updates big piece of data easily but when i'm testing it on my webhost, I see that, if the updated content is a big data, then php doesn't update the table row on the first attempt, updates only after second attempt. Any suggestion? How to deal with that problem?
PHP Side
<?php
session_start();
require '../../core/includes/common.php';
$err=array();
$name=filter($_POST['name'],$db);
$id=$db->escape_string($_POST['id']);
$title=filter($_POST['title'], $db);
$parentcheck=$db->escape_string($_POST['parentcheck']);
if(isset ($_POST['parent'])) $parent=$db->escape_string($_POST['parent']);
else $parent=$parentcheck;
$menu=$db->escape_string($_POST['menu']);
$content = html($_POST['content'], $db);
if (!isset($content)) die('error');
$result=$db->query("UPDATE pages AS p, menu AS m SET m.parent='$parent', m.name='$name', m.showinmenu='$menu', p.id='$id', p.title='$title', p.content='$content' WHERE m.id='$id' AND p.id=m.id") or die($db->error);
if ($result){
echo "{";
echo '"msg": "Success" ';
echo "}";
}
else{
echo "{";
echo
'"err": "Error"';
echo "}";
}
?>

Your code looks like you can have tons of potential errors, this example should only show what you can do to always return something back which might be in the format your AJAX request can deal with:
You're mixing two types of error handling: die'ing straight away and reporting your action result to AJAX. You should do the one way or the other, this one is reporting back always:
<?php
session_start();
require '../../core/includes/common.php';
...
if (!isset($content)) die('{"err": "No content"}'); // This will never happen BTW.
$result = $db->query("UPDATE pages AS p, menu AS m SET m.parent='$parent', m.name='$name', m.showinmenu='$menu', p.id='$id', p.title='$title', p.content='$content' WHERE m.id='$id' AND p.id=m.id");
if ($result)
{
echo '{"msg": "Success"'}';
}
else
{
echo '{"err": "Error"}';
}
?>

Can you do something like this, parse the html content for only the important content ie the div and not the entire page, Mysql text datatype supports 2GB, but its not safe to overload mysql.
Idea 1
Can you by any chance save the HTML content on an XML and refer the link along with the node in the Mysql Column so that AJAX picks up the xml and the node to display data on the fly.
Idea 2
Gzip the content and store in Mysql

Related

Output Buffering: Easy way to make string out of HTML-Code

I'm currently using Chatfuel to open the index.php-file of my website which sends the user the html code into his browser. There he can register and set up his account.
An example URL might look like this:
https://my.domain.com?key_value='123456789'
Depending on if that user is a new or a existing one, I wanna present him with a different form. In order to check so, I do a simple query to the MySQL db and see if the passed on key_value is already in the db and safe true or false to a boolean. Stating the obvious: If hes not an existing user, the 'empty' form with no values should show up. If he is registered he should see the information he filled in from last time.
My idea:
At the top of my index.php I do the check whether he's an existing customer or not (Note: This is working already). Then I want to use outputbuffering to alter the html-code depending on the boolean, before it is sent to the client.
My problem:
I developed the blueprint of the website in plain html (see code below). And OB only catches it as output if its within a string. Since I use " as well as ' in the document the string gets interrupted every few lines. Is there a simple workaround to this? Because the OB function is unable to access anything within the <html>...</html> tags.
Or do i need to use redirecting after the check (in my index.php) and create a separate form + script for both edit customer data and add new customer data?
<?php
//Connection stuff
// Prepare statment: !TODO: string needs to be escaped properly first
$query_string = "SELECT * FROM tbl_customer WHERE unique_url = '$uniqueurl'";
$query_rslt = mysqli_query($conn, $query_string);
if($query_rslt == FALSE)
{
// Failure
echo "<br> Oops! Something went wrong with the querying of the db. " . $conn->connect_error;
//Handle error
}
else
{
if ($query_rslt->num_rows > 0)
{
// Set boolean
$existing_customer = TRUE;
// Create an array called row to store all tuples that match the query string
while($row = mysqli_fetch_assoc($query_rslt)) {
//...
}
}
}
// Custom post processing function
function ob_postprocess($buffer)
{
// do a fun quick change to our HTML before it is sent to the browser
$buffer = str_replace('Testing', 'Working', $buffer);
// Send $buffer to the browser
return $buffer;
}
// start output buffering at the top of our script with this simple command
// we've added "ob_postprocess" (our custom post processing function) as a parameter of ob_start
if (!ob_start('ob_postprocess'))
{
// Failure
echo "<br> Oops! Something went wrong with output buffering. Check that no HTML-Code is sent to client before calling this start function.";
// Handle error
}
else
{
// Success
// This is where the string should get accessed before sending to the client browser
echo "Testing OB.";
}
?>
<!--DOCTYPE html-->
<html lang="en">
<head>
<meta charset="utf-8">
//...
</body>
</html>
<?php
// end output buffering and send our HTML to the browser as a whole
ob_end_flush();
?>
Output: "Working OB."
EDIT: I added source code example. This code won't compile.
Since, i can't comment, so i'll put some of my question here.
I dont really get the point, but give me a try, are you mean escaping string? you can use backslashes \ to escape string.
Like this "select from ".$dbname." where id = \"".$id."\"".
You can easily using addslashes($var) before adding the variable to the sql. like this
$id = addslashes($_POST['id']);
$sql = "select form db where id = '$id'";
If you mean checking the existent of the user to select which form to show in the page, why dont you do this?
if(userCheck()) {
?>
// here write the html code if user passed
<?php
} else {
?>
// here write the html code if user not passed
<?php
}
You can put userCheck() as global function or whereever you place it, as long as you can use it when you want to check the user before showing the form.
tl;dr: The thing I was looking for was a combination of file_get_contents() and object buffering.
file_get_contents() returns a string of a plain html-file of your choice. I could post a ton of explanation here or simply link you to phppot.com. The article offers you a directly executable demo with source (Download here). In case you wanna try it with a html file of yours, simply change the file path.
So once the whole html was converted into a string, I used the postprocessing function of OB to alter the string (= basically my html) if it's an existing user that came to alter his data. Then all the html-code (in a string still at this point) is sent to the client using ob_end_flush(). I will put up the actual code asap :)

How to read a blob in Base64 using PHP and MySQL?

I am a newb with 6 months experience, self-taught via StackEx/books/etc. Created a pretty decent website with login/register and storing some info via mySQL. I have been through every single BLOB post here and I have some decent output.
I think I, like most newbs, know enough to be dangerous, don't have the greatest foundation laid out so when it gets to serious understanding of built-in functions, arrays and passing arguments we can lose the flow and I basically think I have dug a hole by using includes to call some navbar so that I can't just use a header to output the damn image as I echo the user name after login so it has already outputted lines and it will be a monster to undo. Three levels of nav, unauthenticated, authenticated and admin.
The database connection and write to/read from is OK. I can store the BLOB and I can even read it back and store the array in a variable and then debug see the binary but I can't get it to display on an HTML page.
Here is the fun:
$stmt = $dbc2->query("SELECT * FROM equip1");
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$name = $row['equipname1'];
$desc = $row['equipdesc1'];
$img = $row['equipimg1'];
}
<div class="col-lg-12">
<h1><?php echo $name ?></h1>
<p><?php echo $desc ?></p>
<pre>
<?php print_r($img); ?>
</pre>
<?php echo "<img src='data:image/jpeg;base64," . base64_encode( $img ) . "' />"; ?>
</div>
$dbc2 connects
equip1 table is two simple varchar cols, one BLOB col.
$name and $desc echo out ok, the $img displays broken link.
I check the array via pre code and is matching, per what is stored in dB during upload.
From what I have read and gone through, seems like you can't do this at same time unless via data URI which I have done but still broken link. Not making sense to me at all. I try the header and of course output already started but I can see also outputs the binary.
Here is screenshot of the URI method:
Since both methods "seem" to get into and out of the dB but do not display I'm going round in circles. Please help me out to display the image on an html page. I would like to echo it anywhere and then I can just style the page after that. Thanks!
Try Like this
<?php echo '<img src="data:image/png;base64,'.base64_encode($img).'">';?>
Uhh NEVER MIND. Never thought reading someones answer would make for "fresheyes". I noticed I was encoding but I already encoded it when I stored it. Mea culpa. DOH! :)

Code block not getting executed

I was trying to make a little report management system recently. Everything was going well till I encountered this weird problem. Since the code contains lots of html, I'll only include the important parts.
Basically this is a login page. I am storing the information in SESSION variable.
When the username and pass doesn't match, the error message is given to this below function for further processing.
Edit: Every page in my project includes a config.php with following contents
// Start of config.php
session_start();
error_reporting(E_ERROR);
// ********************* Database Config **********************//
$dbHost = "localhost"; // MySQL host
$dbUser = ""; // MySQL username
$dbPass = ""; // MySQL password
$dbDatabase = ""; // MySQL main database name
A part of login.php is shown below.
//START OF PHP CODE//
include("config.php");
function gotError($msg)
{
$_SESSION['err'] = $msg;
header("Location: login.php");
die();
}
//CODE FOR EVALUATION OF DATA//
// END OF THE PHP CODE & BELOW THE HTML WILL START //
And on the same page, below the starting php code, there is the html code of page. Between the html, there are some bits of php code for using the data set above.
----------- SOME HTML CODE HERE----
<?php
if(isset($_SESSION['err']))
{
$html.= "<script type='text/javascript'>";
$html.= '$.alert("'.$_SESSION['err'].'");';
$html.= "</script>";
print $html;
}
?>
----------------- SOME HTML CODE HERE--------
Now here's the weird behavior comes in. The page post the login data to itself & if error occurs, the error is set in session variable { $_SESSION['err'] } and then redirected to itself again which displays a jquery message box if $_SESSION[ 'err' ] is not empty.
The above code doesn't work in the original form, however, if I do like code shown below, the code works. I mean the whole code including the conditional components which didn't worked previously. As soon as I remove that particular line, the conditional evaluation doesn't work.
<?php
print($_SESSION['err']);
if(isset($_SESSION['err']))
{
$html.= "<script type='text/javascript'>";
$html.= '$.alert("'.$_SESSION['err'].'");';
$html.= "</script>";
print $html;
}
?>
Does anyone have a clue about this? I am using PHP Version 5.3.8.
Thank You.
Are you calling session_start() to actually enable the session? Without that, you'll just be wasting your time. Unless you start the session, php will NOT save any data your write to $_SESSION, not will it load any data that was previously saved elsewhere.
I resolved this problem. Comes out that changing the position of the php script between the HTML from head to body did the trick.

How to properly backup results to the database?

I'm working on a jQuery AJAX call where I get a set of results from a search. I return html with an echo and I need to backup the results by inserting into the db. Will also have to check if they already exist before inserting.
I want the html to be returned as soon as possible. If I add insert code below the echo will the entire code have to finish running before the html is returned?
The most important thing is content returning back to the user right away.
This is all on mobile so every 100 milliseconds count.
$data = file_get_contents($url);
$result = json_decode($data, true);
foreach ( $result->results as $items ) {
$name = $items->name;
$description = $items->desc;
$id = $items->id;
$coverurl = $items->coverurl;
$returnhtml .= "<h3>".$name."</h3>";
$returnhtml .= "<h4>".$description."</h$>";
}
echo $returnhtml;
//how to backup to database
//check if already in db
//insert into db
To answer your question, yes. The entire script must complete before the HTML is outputted back to the client. You can use output buffering to capture the output, send it, and then continue on with other processing. The server will then try to output the remaining when the script finished but AJAX doesn't know how to handle the second part so it just ignores it.
Look into http://www.php.net/manual/en/ref.outcontrol.php
It'll be something like:
ob_start();
... generate html for client
ob_flush();// send output buffer to the client
... insert data into database
ob_end_clean();
After do the ob_flush as explained before, you can try MySQL INSERT DELAYED if you don't wait for the INSERT to complete.
http://dev.mysql.com/doc/refman/5.5/en/insert-delayed.html

Fetch database information on a new page without using new documents

I'm working on a page where I've listed some entries from a database. Although, because the width of the page is too small to fit more on it (I'm one of those people that wants it to look good on all resolutions), I'm basically only going to be able to fit one row of text on the main page.
So, I've thought of one simple idea - which is to link these database entries to a new page which would contain the information about an entry. The problem is that I actually don't know how to go about doing this. What I can't figure out is how I use the PHP code to link to a new page without using any new documents, but rather just gets information from the database onto a new page. This is probably really basic stuff, but I really can't figure this out. And my explanation was probably a bit complicated.
Here is an example of what I basically want to accomplish:
http://vgmdb.net/db/collection.php?do=browse&ltr=A&field=&perpage=30
They are not using new documents for every user, they are taking it from the database. Which is exactly what I want to do. Again, this is probably a really simple process, but I'm so new to SQL and PHP coding, so go easy on me, heh.
Thanks!
<?php
// if it is a user page requested
if ($_GET['page'] == 'user') {
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
// db call to display user WHERE id = $_GET['id']
$t = mysql_fetch_assoc( SELECT_QUERY );
echo '<h1>' . $t['title'] . '</h1>';
echo '<p>' . $t['text'] . '</p>';
} else {
echo "There isn't such a user".
}
}
// normal page logic goes here
else {
// list entries with links to them
while ($t = mysql_fetch_assoc( SELECT_QUERY )) {
echo '<a href="/index.php?page=user&id='. $t['id'] .'">';
echo $t['title'] . '</a><br />';
}
}
?>
And your links should look like: /index.php?page=user&id=56
Note: You can place your whole user page logic into a new file, like user.php, and include it from the index.php, if it turns out that it it a user page request.
Nisto, it sounds like you have some PHP output issues to contend with first. But the link you included had some code in addition to just a query that allows it to be sorted alphabetically, etc.
This could help you accomplish that task:
www.datatables.net
In a nutshell, you use PHP to dynamically build a table in proper table format. Then you apply datatables via Jquery which will automatically style, sort, filter, and order the table according to the instructions you give it. That's how they get so much data into the screen and page it without reloading the page.
Good luck.
Are you referring to creating pagination links? E.g.:
If so, then try Pagination - what it is and how to do it for a good walkthrough of how to paginate database table rows using PHP.

Categories