Isaac_4 39 Junior Poster in Training

The plugin itself is not that important. Make sure that your site:

1) Works well with the social media sites you use (e.g. pulls in the right thumbnail and summary text when you share a page)

2) Write good content that is relevant to your target market

There are dozens of ways you can accomplish this, and it's easily done with the built in tools.

Isaac_4 39 Junior Poster in Training

Just wanted to comment that I recommend strongly using prepare and execute instead of escaping strings, as that is a very error-prone method and may lead to SQL injections. See this code snippet for an easy to use function you can use instead.

Isaac_4 39 Junior Poster in Training

The general approach is to do two queries.

Since you didn't include the code that generated your result set, I will use a simple example.

The idea is to do a SELECT COUNT(*) query to figure out how many rows there are in the table, then do a separate SELECT * query to get the current page of data.

<?php

$where = '1=1'; // If you have any conditions in your query, include them here
$perPage = 25;
if(isset($_GET['p'])) {
    $page = (int)$_GET['p']-1; // Get the page selected
} else {
    $page = 0;
}

$countSQL = 'SELECT COUNT(*) As total_rows FROM table_name WHERE '.$where;
// Now get the current page of text
$pageSQL = 'SELECT * FROM table_name WHERE '.$where.' LIMIT '.($page*$perPage).','.$perPage;
$query = mysql_query($countSQL);
$pageCount = $query['total_rows'] / $perPage;
$query = mysql_query($pageSQL);

Now you'll have a populated query object and a pageCount variable telling you how many pages there are.

Add something like this to the end of the page, under your table to render a list of pages:

<p>
Page:
<?php

for($i = 1; $i <= $pageCount; $i++) {
    echo '<a href="?p='.$i.'">'.$i.'</a> ';
}
?>
</p>

This code isn't tested but should be very close to what you need to do.

See this page for info about MySQL LIMIT http://www.mysqltutorial.org/mysql-limit.aspx

Isaac_4 39 Junior Poster in Training

Looks like maybe a simple typo, you open a file named "modifiedrecords." (without any extension) then try to rename a file named "modifiedrecords.txt" to "newrecords.txt".

rproffitt commented: Eagle eye. +12
Isaac_4 39 Junior Poster in Training

Cache in the PHP level is not going to help in this case. The person at your hosting company was probably either talking about browser caching, or didn't really have a good answer to give you.

Allowing the users to upload the files is fine, but you need to resize them before you include them on a page. PHP has a bunch of built in functions in the GD and ImageMagick libraries that can do this. If you can't quite figure it out, I can write a function for you later tonight or torrow and show how I do it.

For the YouTube video ID you probably want to use explode() or preg_match() depending on how fancy you want to get.

SimonIoa commented: Thanks Isaac +2
Isaac_4 39 Junior Poster in Training

What is the URL to your page? The ISP's notes sound more related to a frontend (i.e. your browser can't load that many videos at once) than something you could solve in PHP, but it would be impossible for us to know without looking at the page as it loads.

Isaac_4 39 Junior Poster in Training

Some things to check...

Does your page now start with the line PHP Parsed okay? If not, there is something wrong with PHP's configuration or there is a syntax error in your file.

Did you put my db_query() function and the $pdo = new PDO(...); line into your dbcon.php file? If not, you need to either add it there or include the database.php file instead of dbcon.php. Make sure you also adjust the PDO() line to match your database settings.

Also, is the file this code in actually called form.php? This is where the form is trying to post to, so if youy renamed it, you need to change the <form> tag's action attribute to match the new filename.

Do you have a .htaccess file in the root of your site? You need to make sure your S/FTP program is set to show hidden files to see it, or if you are on the command line, us ls -al to show hidden files. If you do have such a file, try moving it (or delete it after making a backup locally, and checking the backup has the same contents as the original). It could be causing a redirect which may prevent the POST from working... which you can also check by looking in your browser's Developer Tools to see if after submitting the form you get any 301 or 302 or other interesting return codes.

To see if you can catch anything else, put an exit here at …

Isaac_4 39 Junior Poster in Training

What output do you get with my version? It should have printed out an error message object.

If you got no output at all, try putting this at the top of the file and report back what output you see:

<?php
echo "PHP Parsed okay<br/>";
ini_set('display_errors', 'on');
error_reporting(E_ALL);
Isaac_4 39 Junior Poster in Training

You need to define what you want to redirect from as well as what you want to redirect to. Assuming that you want to go from:

http://example.com/test

to:

http://example.com/media.php?page=test

Then this should do the trick:

<IfModule mod_rewrite.c>
    # Turn on the engine
    RewriteEngine On

    # If your pages are under the root of the domain, leave as /
    # If they are instead under a subdirectory such as /test/,
    # change RewriteBase to be /test/
    RewriteBase /

    # Don't redirect real files (-f) or directories (-d)
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d

    # Do the redirect - if you had to change RewriteBase, add that
    # here as well - /test/media.php instead of /media.php
    RewriteRule ^(.*)$ /media.php?page=$1 [L]
</IfModule>

But if your situation is more complex, this won't cut it:

  • Do some URLs need to be redirected to files other than media.php?
  • Are there multiple base directories to redirect from (not just / or /test/ as in my comments, but more than one base)?
  • Do you need query strings to still work? (as is, in the URL http://example.com/test?q=1 the q=1 value will be stripped out and won't be visible to media.php)
Isaac_4 39 Junior Poster in Training

I suggest using DataTables to do this. Their zero configuration example does exactly what you want to an existing HTML table. It does also add search and a few things, so you may want to remove those extra features:

<!-- previous code the same -->
<table id="admintable" border="1" cellpadding="2" cellspacing="0">
<thead><!-- added -->
<tr>
    <th>Page</th><th>Post</th>
</tr>
</thead><!-- added -->
<tbody><!-- added -->
<?php
$i=0;
while ($data = mysql_fetch_array($result)){
$result2=($i%2)?'#DFA09D':'white';
        //echo "<tr bgcolor='$result2'>";                    
        //echo '<td>'.$data['page'].'</td>';
        //echo "<td><a href='post.php?post_id=".$data['post_ID']."'><img src='../images/post.jpg'></a></td>";
        //echo '</tr>';                  
        echo "<tr bgcolor='$result2'>";                  
        echo '<td><a href="input_berita_static.php?post_id='.$data['post_id'].'">'.$data['page'].'</a></td>';
        echo '<td>';
        if($data['post_type']=="post"){                                         
        echo '<a href="post.php?post_id='.$data['post_id'].'"><img src="../images/post.png"></a></td>';                                                 
        }
        echo '</tr>';
$i++;   
}
?>
</tbody>
</table><!-- added -->

<!---------------------- DataTables Begin ---------------------->
<!-- remove this line if you already have jquery -->
<script type="text/javascript" language="javascript" src="//code.jquery.com/jquery-1.11.1.min.js"></script>

<!-- include datatables library -->
<script type="text/javascript" language="javascript" src="//cdn.datatables.net/1.10.3/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function() {
    $('#admintable').DataTable({
        "paging": false,
        "searching": false
    });
});
</script>
<!---------------------- DataTables End ---------------------->

<!-- all other code the same -->

DataTables can also use server-side data loading so that it only fetches enough data to display at one time. This is not needed unless you have many thousands or millions of records, however, so the above should get you very far.

Note that you must have <thead> and <tbody> tags or DataTables will not load properly! Normally these tags are optional and many people don't even know they exist, but DataTables requires them.

Isaac_4 39 Junior Poster in Training

Those are not really errors - they are PHP code that isn't getting parsed. Somewhere you have a line that starts with "load->model(array('Mediatutorialaccount'))" which is not inside of a <?php block.

I would recommend searching the whole directory for the word "Mediatutorialaccount" to try to find where this is.

You will get a 404 if the URL you're trying to get to doesn't, by default, match controllerName/methodName. What URL are you trying to load?

Isaac_4 39 Junior Poster in Training

Well it's actully returning some data. The three ... in bold mean that the output is being truncated because it's too deep. Try using print_r() instead of var_dump():

echo '<pre>';
print_r($obj);
echo '</pre>';

That should show you all the nested objects and arrays. You have to dig deeper into the returned data.

You probably have to do something like

foreach($obj->monitors->monitor as $monitor) {
    var_dump($monitor);
}
Isaac_4 39 Junior Poster in Training

Some sample code. Post data to your customer's PHP file like this:

// Read data from DB
$query = $db->execute("SELECT * FROM `dlr_tbl` WHERE `fetched` = '0'");
$row = $query->getrows();

// Create an array of rows to encode, using the field names we want
$array_data = array();
for($i=0;$i<count($row);$i++) {
    $post_data[] = array(
        'extid' => $row[$i]['external_id'],
        'status' => $row[$i]['delivery_status'],
        'cause' => $row[$i]['cause'],
        'mobile' => $row[$i]['mobile_no'],
        'date' => $row[$i]['delivery_date'],
    );
}

// Encode data to a JSON packet
$json_data = json_encode($array_data);

echo 'DEBUG SEND: '.$json_data.'<hr/>'; // DEBUG only

// Post the JSON packet - no GET parameters needed, everything is
// in $json_data already
$furl = "http://www.example.com/library/getresponse.php";
$ch = curl_init($furl);
curl_setopt_array($ch, array(
    CURLOPT_URL => $furl,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => $json_data
));
$curl_scraped_page = curl_exec($ch);
echo 'DEBUG RESULT: '.$curl_scraped_page; // DEBUG only
curl_close($ch);

Then in your customer's PHP file, getresponse.php, you can get the array back out like this:

// php://input returns all POST data. We want to decode it as JSON
$post_data = file_get_contents("php://input");
if($post_data) {
    if(substr($post_data, 1, 1) != '{') || substr($post_data, -1, 1) != '{')) exit('Error, POST data does not look like JSON');

    echo 'DEBUG RECV: '.$post_data.'<hr/>'; // DEBUG only
    $array_data = json_decode($post_data);
    var_dump($array_data); // DEBUG only
} else exit('Error, no data in POST!');
Isaac_4 39 Junior Poster in Training

Good point! Maybe first two lines of database.php replaced with this new function would be a good idea:

function db_connect()
{
    // Connect to the database. This requires the PDO and PDO_Mysql modules to be installed in PHP.
    // TODO: Store this connection string in a config file instead of hardcoded
    return new PDO('mysql:host=localhost;dbname=database_name', 'username', 'password');
}

// Helper function to prepare and execute a statement with parameters immediately
function db_query($conn, $sql, $params=array()) {
    $query = $conn->prepare($sql);
    if($query->execute($params)) {
        return $query->fetchAll();
    } else {
        return array();
    }
}

Then usage looks like:

$conn = db_connect();
$result = db_query($conn, 'INSERT INTO posts(author, response_to, subject, post) VALUES(?, ?, ?, ?)', array(&$member_id, &$response_to, &$subject, &$post));

Otherwise a custom PDO could be made if the use case was more complex.

I usually use a framework (CodeIgniter has been my favorite but lately I've been using Mako and starting with Symfony2) -- but sometimes a simple script is better in my opinion. Hopefully some people get some miledge out of these!

Isaac_4 39 Junior Poster in Training

Here is a simple way to insert into a database that isn't much harder than using string concatenation - which we all know is very dangerous due to SQL injection attacks.

Put the code snippet into database.php.

Now, in a script handling a form post, such as post_reply.php:

<?php

require_once("database.php");

// Get session and post data to insert - no need for mysql_real_escape_string or other escaping
// (Note: Passwords should still go through password_hash() or crypt() though!)
$member_id = $_SESSION['member_id'];
$response_to = isset($_POST['response_to']) ? $_POST['response_to'] : (isset($_GET['response_to']) ? $_GET['response_to'] : '');
$subject = isset($_POST['subject']) ? $_POST['subject'] : '';
$post = isset($_POST['post']) ? $_POST['post'] : '';


// Use the db_query function from database.php with a parameter array to safely embed values into 
// the query without string subsitution. I seem to remember parameter binding doesn't quite work
// properly without the reference operator (&) on each variable in this array but can't test at
// the moment.
$result = db_query('INSERT INTO posts(author, response_to, subject, post) VALUES(?, ?, ?, ?)',
                        array(&$member_id, &$response_to, &$subject, &$post));

Even better of course would be to use a framework such as Laravel but for simple scripts this is very safe to use.

Isaac_4 39 Junior Poster in Training

Try adding these lines to the top of your PHP script to make sure errors show up:

define('DEBUG', true); // change true to false to disable errors showing up
if(DEBUG) {
  ini_set('display_errors', 1);
} else {
  ini_set('display_errors', 0);
}
error_reporting(E_ALL & ~E_NOTICE);

This might help you track down the error if the they are being hidden from you for some reason.

Also try to var_dump your variables to see if they have the values you expect. Combined and expanded with broj1's good recommendations this might look like this:

// sanitize the data - unless you use mysqli_prepare (mentioned again
// a few lines down) - NEVER access $_POST or $_GET without passing
// the value through mysqli_real_escape_string() or crypt() first.
// even if you do use mysqli_prepare, always use crypt() for passwords!
$username = mysqli_real_escape_string($_POST['username']);
// TODO: change second string ('*D') passed to crypt() to something unique to your
// site. if you have PHP 5.5 use password_hash instead of crypt.
$password1 = crypt($_POST['password1'], '*D'); 
//$password1 = password_hash($_POST['password1'], PASSWORD_DEFAULT);  // PHP 5.5 only
$email = mysqli_real_escape_string($_POST['email'])

echo "<br/>Username =";
var_dump($username);
echo "<br/>Password ="; // remember this will be a long string hash, that's good!
var_dump($password);
echo "<br/>Email =";
var_dump($email);

// prepare the query from sanitized data
// TODO/SECURITY RISK: instead of concatenating strings from user
// supplied values, you should consider using mysqli_prepare
// (see http://php.net/manual/en/mysqli.prepare.php) in which case
// mysqli_real_escape_string would no longer be required above
$sql = "INSERT INTO member (name, password, email) VALUES ('$name', …
broj1 commented: Nicely explained +11
Isaac_4 39 Junior Poster in Training

Your pattern matches only a single character, add a + to match one or more characters:

if ( preg_match ('/^[a-z0-9]+$/', $username)) {
    echo $username. ' ' . $password . ' ' . $email;     
}
else {
    echo 'special characters are not allowed';
}

I suggest using a tool like RegexBuddy to help write and test regular expressions.

pritaeas commented: +1 for RegexBuddy +14
Isaac_4 39 Junior Poster in Training

This is likely because your user probably does not have the FILE privilege. I would be very much surprised to see a user on shared hosting that has this privilege as it's quite dangerous.

Note that phpMyAdmin has an export link at the bottom of all SQL results, just run your normal query, then download the file and upoad to wherever you need it.