Insert whole HTML code into content table - php

I am trying to update the intro field of the content DB (Joomla) with a whole HTML code which is about 1200 lines long.
try {
$MyDBConn = new PDO("mysql:host=localhost;port=3306;dbname=$MyDBName", $MyDBUser, $MyDBPass);
// PDO can throw exceptions rather than Fatal errors, so let's change the error mode to exception
$MyDBConn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//$MySQL = "UPDATE jso_content SET introtext = '$MyTeamHTML_FR' WHERE titel like '%$MyTeamTitel' and alias like '%$MyTeamAlias'";
$MySQL = "UPDATE jso_content SET introtext = :INTRO WHERE alias = :ALIAS";
$MyStmt = $MyDBConn->prepare($MySQL);
$MyStmt->execute(array(':INTRO' => $MyTeamHTML_FR, ':ALIAS' => $MyTeamAlias));
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage()."\n";
}
$MyDBConn = null;
The update does not perform tough and I don't know why.
When I do this manually through PHPMyAdmin, I can insert the text code.
I used the same statements in a post before and this got solved as there was an error while using exec() instead of execute().
Another comment was on SQL injection attacks, which I hope I solved.
Thank you for your support
Regards
Laurent

I change your code a little and added code for logging the exception. This will help you debug in case of error and solve it.
try {
$MyDBConn = new PDO("mysql:host=localhost;port=3306;dbname=$MyDBName", $MyDBUser, $MyDBPass);
// PDO can throw exceptions rather than Fatal errors, so let's change the error mode to exception
$MyDBConn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//$MySQL = "UPDATE jso_content SET introtext = '$MyTeamHTML_FR' WHERE titel like '%$MyTeamTitel' and alias like '%$MyTeamAlias'";
$MySQL = "UPDATE jso_content SET introtext = :INTRO WHERE alias = :ALIAS";
$MyStmt = $MyDBConn->prepare($MySQL);
$MyStmt->execute(array(':INTRO' => $MyTeamHTML_FR, ':ALIAS' => $MyTeamAlias));
}
catch(PDOException $e) {
$h = fopen('<path_to_a_writable_dir>/error.log', 'a+');
fwrite($h, var_export($e, true));
echo "Connection failed: " . $e->getMessage()."\n";
}
$MyDBConn = null;
Make sure to pass writable dir for path_to_a_writable_dir

Sorry for that post. I realized later last might, that I had a typo here in
"UPDATE jso_content SET introtext = :INTRO WHERE alias = :ALIAS"
this should bw
"UPDATE jos_content SET introtext = :INTRO WHERE alias = :ALIAS"
After changing it, the scripts passed.
Anyway, thank you for your comments
Cheers
Laurent

Related

PHP - PDO Transaction sequence

In my MySQL database very rarely I get duplicate rows. I'm just looking at my code and I want to check if my transaction code is causing this problem. Here is it:
try
{
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$con->beginTransaction();
$sql1 = $con->prepare("query_to_update_tb1");
$sql2 = $con->prepare("query_to_insert_tb2");
$sql1->execute();
$sql2->execute();
...
$sql3 = $con->prepare("query_to_insert_tb1");
$sql4 = $con->prepare("query_to_insert_tb2");
$sql3->execute();
$sql4->execute();
$con->commit();
}
catch(Exception $e)
{
$con->rollback();
}
Never mind. The user was submiting multiple forms, then the duplicate fields. Nothing wrong with the code.

No mySQL error thrown while trying to UPDATE an empty row

Building a small project and trying to learn as I go along.
I get error codes fine if tables are misnamed etc but if I try to UPDATE an empty row I do not get an error. I want to but it isn't telling me I have screwed up. Is this normal?
public function updateMessage($id){ //done
try{
global $pdo;
$temp=$this->_message;
$sql = "UPDATE message SET content=:val WHERE id=$id";
$s = $pdo->prepare($sql);
$s->bindValue(':val',$temp);
$s->execute();
}
catch (PDOException $e)
{ $loc = $_SERVER['PHP_SELF'];
$output = "Unable to connect to the database server: $loc <br><h3>Please contact
Steve via text on ###### quoting:</h3><h5>" . $e->getMessage() . "<br>
Found at $loc.</h5>
<h3>Thanks. </h3>". "<br>"."<br>" ;
include $_SERVER['DOCUMENT_ROOT'] ."/beta01/includes/output.html.php";
exit();
}
}
As I said it works as expected with most errors just not on the empty update problem.
$sql = "UPDATE message SET content=:val WHERE id=$id";
If it's an "empty row" (assuming I understand you right), then it doesn't meet the condition WHERE id=$id, so it worked - it updated the contents of message for every row with that id (there were none).
It sounds like you want to know if no rows were affected by the query, in which case you could do:
$s->execute();
if ($s->rowCount() < 1) {
//throw an exception, show a warning, whatever you want to do
}

Insertig php array in mysql DB - Syntax correct, values are not inserted

I have writen this pice of code that should insert into my Database some event data, but it does not insert a thing in the DB, can you tell me why?
try {
$pdo = new PDO("mysql:host={$dbhost};dbname={$dbname}", $dbuser, $dbpass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch( PDOException $excepiton ) {
echo "Connection error :" . $excepiton->getMessage();
}
try{
$sql = "INSERT INTO events_DB (event_id, event_end_time, event_location, event_name) VALUES (:event_id, :event_end_time, :event_location, :event_name) ON DUPLICATE KEY UPDATE event_id = :event_id, event_end_time = :event_end_time, event_location = :event_location, event_name = :event_name";
$stm = $db->prepare($sql);
$stm->execute(array(":event_id" => $event[id], ":event_end_time" => $event[end_time], ":event_location" => $event[location], ":event_name" => $event[name]));
}
catch ( PDOException $exception )
{
// decomentati sa vedeti erorile
echo "PDO error :" . $exception->getMessage();
}
Thanks
The code you've posted is different than the code you're running as the posted code would result in a syntax error at parse time and never actually run.
However, what's happening is the SQL being sent to the prepare method is not valid in some way so that the result returned and stored in $stm is a boolean (false) rather than a valid statement object. Double check your SQL (you could try running it in another application such as phpMyAdmin or via the mysql command-line program) to ensure its validity. You could also add some error handling to find the cause with:
$stm = $db->prepare($sql);
if (!$stm) {
die($db->errorInfo());
}
Edit: You've modified the posted source code which now shows use of exception handling. However, you've commented out the line that echos the exception message. This information will be useful in telling you what's causing the error condition. Uncomment to see the message (which will most likely inform you that the SQL is invalid and which part of it caused the error).
Try to remove the <br> tag from the first line and a " is messing
$sql = "INSERT INTO events_DB (event_id, event_end_time, event_location, event_name);"

How to show SQL errors in SQLite?

Using SQLite in PHP (thus using PDO), I have this code:
try {
$db = new PDO("sqlite:C:\Program Files\Spiceworks\db\spiceworks_prod.db");
echo "Done.<br /><b>";
$query = "SELECT id FROM Devices LIMIT 5";
echo "Results: ";
$result = $db->query($query);
while ($row = $result->fetchArray()) {
print_r($row)."|";
}
}
catch(PDOException $e) {
echo $e->getMessage();
}
But that does not print out any data from the SQL. I know the database has data in it and the connection is valid. If I change the query to say:
$query = "SELECT BLAHid FROM FakeDevices LIMIT 5";
Nothing changes. Nothing from SQL gets printed out again, and I see no errors even though this is clearly an invalid SQL query.
In both situations, the "Done" and "Results" gets printed out okay. How can I print out SQL errors, like if the query is invalid?
You need to tell PDO to throw exceptions. You can do that by adding the following line after you connect to the database:
$db = new PDO("sqlite:C:\Program Files\Spiceworks\db\spiceworks_prod.db");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
That way you can catch all exceptions except for a possible problem with the first line, the database connection itself.

Why is my database table not updated after this query?

I am using a dedicated server through 1 and 1 and the PHP code as below will not insert the data into the database.
All connections to database are correct.
$id = $_REQUEST['id'];
$content = $_REQUEST['content'];
mysql_query("UPDATE `content` SET `content` = '$content' WHERE `id`='$id'");
When I test on my local server all works fine, there is something about the server that will not allow me to upload. I am connecting using a very general method
$connection = mysql_connect("localhost",
"root",
"password");
mysql_select_db("dbname", $connection);
1) Turn on error reporting by putting this on the top of your PHP script:
error_reporting(E_ALL);
2) Run your script. Any errors? If yes, proceed according to the error message you get.
3) Double check that your variables are actually defined (you are getting them from the request, you cannot be sure request actually contains values you are trying to use).
4) Your SQL query is very dangerous. Use mysql_real_escape_string() or prepared statements. Don't put quotes around integer values.
5) Edit your script to look more like this:
error_reporting(E_ALL);
$id = (isset($_REQUEST['id']) && !empty($_REQUEST['id'])) ? $_REQUEST['id'] : NULL;
$content = (isset($_REQUEST['content']) && !empty($_REQUEST['content'])) ? $_REQUEST['content'] : NULL;
try{
if(NULL === $id){
throw new Exception('$id is NULL');
}
if(NULL === $content){
throw new Exception('$content is NULL');
}
$id = mysql_real_escape_string($id);
$content = mysql_real_escape_string($content);
$sql = "UPDATE content SET content = '$content' WHERE id = $id";
// connect to database
// ...
mysql_query($sql);
}catch(Exception $e){
echo '<p style="color: red;">',$e->getMessage(),'</p>';
}
Ddebugging for beginners...
You haven't posted any errors, is error reporting turned off? Debugging is much easier with error reporting turned on.
error_reporting(E_ALL);
We'll also want to see what the actual query we're trying to run in the database. Perhaps the variables haven't been properly escaped (Contains illegal characters).
$query = "UPDATE table SET name='$name' where id='$id'";
echo $query;
mysql_query($query);
My guess is that you have to mysql_real_escape_string(); both variables.
Also you pass $id as a string, it's probably an integer.
You're mishandling transactions.

Categories