Cluster Cluster - 19 days ago 6
MySQL Question

PHP & MySQL - Display results after update

Problem which I am having is as follows:

I can save and retrieve information after its saved but I don't know how to do that automatically as soon as the record is saved/updated.

To update I use:

$result = mysql_query("UPDATE loan SET loana='$loann', dater='$dater', apaid='$apaid' WHERE id=$id");


Once save I can load the main page wit the results and click on a link which looks like this and it displays all of the info:

echo "<td><a href=\"full_loan_details.php?id=$res[id]\" target=\"_blank\" alt=\"Print loan details\" title=\"Print loan details\">".$res['name']."&nbsp;".$res['surname']."</a></td>";


...but for I am not able to do this automatically when the record is saved. Any help is greatly appreciated.

Answer

You could use header:

header("Location: /full_loan_details.php?id=$res[id]");

As mentioned your script is vulnerable to injection attacks. You should use PDO's:

<?php

define( "DB_DSN", "mysql:host=localhost;dbname=foo");
define( "DB_USERNAME", "root");
define( "DB_PASSWORD", "password" ); 

// define sql
$sSQL = "UPDATE loan SET loana=:loana, dater=:dater, apaid=:apaid WHERE id=:id";

// create an instance of the connection
$conn   = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );

// prepare
$st   = $conn->prepare( $sSQL );

// securely bind any user input in the query
$st->bindValue(":loana", $loana, PDO::PARAM_STR);
$st->bindValue(":dater", $dater, PDO::PARAM_STR);
$st->bindValue(":apaid", $apaid, PDO::PARAM_STR);
$st->bindValue(":id", $id, PDO::PARAM_INT);

// execute the connection
if($st->execute()){
    header("Location: /full_loan_details.php?id=".$id);   
}else{
    // didnt execute 
}

You could do a SELECT to confirm the change and or get a value. Same method as above but will need the following to read it;

To fetch single row use an If, or if more than 1 row use a while

if($row = $st->fetch() ){
    header("Location: /full_loan_details.php?id=".$row['id']);   
}

Note: it could be unsafe to redirect a user to a location based of unsanatised data from the DB. Even if you have inserted it with the method above. Ensure you sanatise all output correctly.

Comments