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
}
Related
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
I'm scratching my head over this and not sure why this isn't working
I am trying to post info from a form to save the entry in the database, for troubleshooting I am doing a field at a time
Here is my code and the link is /example.php?device=test
I have even tried $_GET['device'] = "test101"; and still no luck.
The database name and login is correct as I have another form that works, knowing this I have copied and pasted the code to this file and changed the details for the table to try help solve my problem.
I'm guessing its something simple that I have over looked.
<?php
// include database connection
include 'inc/connect.php';
try{
// insert query
$query = "INSERT INTO repairs SET device=:device";
// prepare query for execution
$stmt = $con->prepare($query);
// bind the parameters
$stmt->bindParam(':device', $_GET['device']);
// Execute the query
if($stmt->execute()){
echo "<div>Record was saved.</div>";
}else{
echo mysql_error();
die('Unable to save record.');
}
}
// show error
catch(PDOException $exception){
die('ERROR: ' . $exception->getMessage());
}
?>
change INSERT INTO to update
if you want to update:-
$query = "update repairs SET device=:device";
or if you want to insert
$query = "INSERT INTO repairs (device) VALUES (:device)";
Ok, so I've been trying to do this for days, and I've been reading all sorts of tutorials, but I seem to be missing something, because I still can't get it. I'm working on learning about web forms and inserting the form input into the respective database. I'm able to take the info from the form and echo it on the result page, so I know that all works. but I can't seem to get the form input to go into my database. I know the connection works, so there must be something wrong with my syntax.
PHP
//DB Configs
$username = null;
$password = null;
try {
$db = new PDO("mysql:host=localhost;dbname=Testing3", $username, $password);
//Set the PDO error mode to exception (what does this mean?)
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Prepare SQL and bind parameters
$sql = $db->prepare("INSERT INTO `NFK_SPECIES` (`Name`)
VALUES (:name)");
//Insert a Row
$species = $_POST['Species'];
$sql->execute(array(':name'=>$species));
}
catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
$result = $db->query('SELECT * from `NFK_Species` ORDER BY `Id` DESC');
//Query
/*
$input = $db->query("INSERT INTO `NFK_Species` (`Id`, `Name`) VALUES (Null, `$species`)");
$result = $db->query('SELECT * from `NFK_Species` ORDER BY `Id` DESC');*/
//Kill Connection
$db = Null;
}
HTML/PHP (web page)
<h1>Inserting a New Species into Database:</h1>
<h3>Results</h3>
<?php
if ($sql->execute()){
echo "Data input was successful";
while ($rows = $result->fetch()){
echo $rows['Name']; echo ", ";
}
} else {
echo "Data input failed."; echo mysql_error();
}
?>
This is only my current attempt at doing this. I prefer the attempt I had before, with the bindParam and simple execute(), so if I could get that to work instead, I'd appreciate it. The following example also has the Id column for this table. This is an auto-increment column, which I read doesn't need to be included, so I excluded it from my recent attempt. Is that correct?
Past PHP
//Prepare SQL and bind parameters
$sql = $db->prepare("INSERT INTO `NFK_SPECIES` (`Id`, `Name`)
VALUES (Null, :name)");
$sql->bindParam(':name', $species);
//Insert a Row
$species = $_POST['Species'];
$sql->execute();
I've been reading a bunch of tutorials (or trying to), including attempting to decipher the php.net tutorials, but they all seem to be written for people who already have a good handle on this and experience with what's going on, and I'm very new to all of this.
Alright, I was able to figure out my problem, and then successfully insert a row using my code.
Debugging:
So the code posted above was breaking my code, meaning my page wouldn't load. I figured that meant that there was a syntax error somewhere, but I couldn't find it, and no one else had located it yet. Also, that meant that my Error Alerts weren't working to let me know what the problem was. If you look at my original PHP sample, you'll see down at the very bottom there is a single "}" just hanging out and serving no purpose, but more importantly, it's breaking the code (stupid, hyper-sensitive php code). So I got rid of that, and then my Error messages started working. It said I couldn't connect to my database. So I look over my database login syntax, which looked fine, and then you'll notice in my 1st php sample that somehow I'd managed to set my $username and $password to NULL. Clearly that isn't correct. So I fixed that, and next time I refreshed my page, I'd successfully entered a row in my database! (yay)
Note:
In my original php sample, I'd included the Id Column, which is auto-incremented, for the row insertion, with a value of NULL. This worked, and it inserted the row. Then I experimented with leaving it out altogether, and it still worked. So the updated working code below doesn't include the Species Id.
Working code:
<body>
<h1>Inserting a New Species into Database:</h1>
<h3>Results</h3>
<?php
//DB Configs
$username = root;
$password = root;
try {
//Connect to Database
$db = new PDO("mysql:host=localhost;dbname=Testing3", $username, $password);
//Enable PDO Error Alerts
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Prepare SQL statement and bind parameters
$sql = $db->prepare("INSERT INTO `NFK_SPECIES` (`Name`) VALUES (:name)");
$sql->bindParam(':name', $species);
//Insert a Row
$species = $_POST['Species'];
$sql->execute();
// Echo Successful attempt
echo "<p class='works'><b>" . $species . "</b> successfully added to database.</p></br></br>";
}
catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
// Gather updated table data
$result = $db->query('SELECT * from `NFK_Species` ORDER BY `Id` DESC');
//Kill Connection
$db = Null;
while ($rows=$result->fetch()){
echo $rows['Id']; echo " - "; echo $rows['Name']; echo "</br>";
}
?>
<body>
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);"
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.