PDO PHP Form unable to save record - php

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)";

Related

PHP sql insert code is returning false even when sql command if correct and database is too

Once again I come back to all of you with another question.
I have tried everything in my mind as well as most of the recommendations I have found on the web and here in Stackoverflow but nothing seems to fix this issue for me.
For some reason the sql command in my code is returning false even though it should not.
Here is my php file called (dbRKS-DBTest.php)
<?php
//Gets server connection credentials stored in serConCred.php
//require_once('/../prctrc/servConCred2.php');
require_once('C:\wamp64.2\www\servConCred2.php');
//SQL code for connection w/ error control
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if(!$con){
die('Could not connect: ' . mysqli_connect_error());
}
//Selection of the databse w/ error control
$db_selected = mysqli_select_db($con, DB_NAME);
if(!$db_selected){
die('Can not use ' . DB_NAME . ': ' . mysqli_error($con));
}
//VARIABLES & CONSTANTS
//Principal Investigator Information
$PI_Selected = '6';
//Regulatory Knowledge and Support Core Requests variables
$RKS_REQ_1_Develop = '1';
//This sets a starting point in the rollback process in case of errors along the code
$success = true; //Flag to determine success of transaction
//start transaction
$command = "SET AUTOCOMMIT = 0";
$result = mysqli_query($con, $command);
$command = "BEGIN";
$result = mysqli_query($con, $command);
//Delete this portion of code afyer testing is finished
//Core Requests saved to database
$sql = "INSERT INTO rpgp_form_table_3 (idPI, RKS_REQ_1_Develop)
VALUES ('$PI_Selected', '$RKS_REQ_1_Develop')";
//*************TEsts code for "SCOPE_IDENTITY()" -> insert_id() for mysql
$sqlInsertId = mysqli_insert_id($con); //This value is supposed to be 0 since no queries have been executed.
echo "<br>MYSQLi_INSERT_ID() value before query should be 0 and it is:= " . $sqlInsertId;
//Checks for errors in the db connection.
$result = mysqli_query($con, $sql); //Executes query.
if($result == false){ //Checks to see for errors in previews query ($sql)
//die ('<br>Error in query to Main Form: Research Proposal Grant Preparation: ' . mysqli_error($con));
echo "<br>Result for the sql run returned FALSE. Check for error in sql code execution.";
echo "<br>Error given by php is: " . mysqli_error($con);
$success = false; //Chances success to false is it encounted an error in order to rollback transaction to database
}
else{
//*************TEsts code for "SCOPE_IDENTITY()" -> insert_id() for mysql
$sqlInsertId = mysqli_insert_id($con); //Saves the last id entered. This would be for the main table
echo "<br>MYSQLi_INSERT_ID() value after Main form query= " . $sqlInsertId; //Displays id last stored. This is the main forms id
$MAIN_ID = mysqli_insert_id($con); //Sets last entered id in the MAIN Form db to variable
}
//Checks for errors or craches inside the code
// If found, execute rollback
if($success){
$command = "COMMIT";
$result = mysqli_query($con, $command);
echo "<br>Tables have been saved witn 0 errors.";
}
else{
$command = "ROLLBACK";
$result = mysqli_query($con, $command);
echo "<br>Error! Databases could not be saved. <br>
We apologize for any inconvenience this may cause. <br>
Please contact a system administrator at PRCTRC.";
}
$command = "SET AUTOCOMMIT = 1"; //return to autocommit
$result = mysqli_query($con, $command);
//Displays message
//echo '<br>Connection Successfully. ';
//echo '<br>Database have been saved';
//Close the sql connection to dababase
mysqli_close($con);
?>
Here is my php frontend html code named (RPGPHomeQueryTest.php)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<form id="testQuery" name="testQuery" method="post" action="../dbRKS-DBTest.php" enctype = "multipart/form-data">
<input type="submit" value="Submit query"/>
</form>
</html>
And here is how my database looks (rpgp_form_table_3):
So, when I open my html code, All I will see is a button since its all the code there is there. Once you press the button, the form should submit and execute the php code called (dbRKS-DBTest.php). This should take the predetermine values I already declared and saved them to the database called (rpgp_form_table_3). This database is set to InnoDB format.
Now, the output I should be getting is a message saying "Tables have been saved witn 0 errors." but the problem is that the message I am getting is this one bolow:
I honestly don't know why. I am posting this message to find guidance to this issue. I am still learning by myself and its been very did-heartedly to not find a solution this fixing this.
As always, I thank you for your patient and guidance! Let me know what other details I can provide.
Here is the SQL code you run:
$sql = "INSERT INTO rpgp_form_table_3 (idPI, RKS_REQ_1_Develop)
VALUES ('$PI_Selected', '$RKS_REQ_1_Develop')";
You are inserting data into rpgp_form_table_3. From the screenshot, we can see that table has several (7) fields yet you are only inserting 2 fields. The question then is: do you need to specify a value for all fields?
The error you are getting states
Error given by php is: Field 'idCollaRecord_1' doesn't have a default value Error! Databases could not be saved.
It's clear that you have to insert the row by specifying a value for each column, not just the two columns you are interested in.
Try
$sql = "INSERT INTO rpgp_form_table_3 (idPl, RKS_REQ_1_Develop, idCollaRecord_1, idCollaRecord_2, idCollaRecord_3, idCollaRecord_4)
VALUES ('$PI_Selected', '$RKS_REQ_1_Develop',0,0,0,0)";
Try this insert code. If the PI_Selected is NUMERIC use the First one. If it is string use the second one
$sql = "INSERT INTO rpgp_form_table_3 (idPI, RKS_REQ_1_Develop) VALUES (" .
$PI_Selected . ",'" . $RKS_REQ_1_Develop . "')";
$sql = "INSERT INTO rpgp_form_table_3 (idPI, RKS_REQ_1_Develop) VALUES ('" .
$PI_Selected . "','" . $RKS_REQ_1_Develop . "')";

Attempting to insert new row into database using PDO

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>

Running an INSERT query inside an If statement

I am wondering if its possible to run an insert query if the answer is correct, I have tried multiple types of queries from creating a new stmt and array and inserting them into the database if the answer if correct, However with my basic understanding of how it all works, I may be missing something? I am not getting any errors returned, just getting the echo statement returned.
Note : I know I am trying to insert QuestionID multiple times its just to put data into the database. It will be updated with the correct fields.
Can anyone enlighten me on whats the issue :
<?php
// establishing the MySQLi connection
require_once('connection-test.php');
$mysqli = new mysqli($host,$username,$password,$database);
if($mysqli -> connect_error)die($mysqli->connect_error);
$questionID = $_POST['id'];
$userAnswer = $_POST['answer'];
$query = "SELECT answers FROM answers WHERE questionID=?";
$statement = $mysqli->prepare($query);
$statement ->bind_param('i', $questionID);
$statement->execute();
$statement->bind_result($answer);
while($statement->fetch()){
if($answer != $userAnswer){
echo "Wrong";
//return to previous Page
}else{
echo "Correct";
mysqli_query($mysqli,"INSERT INTO submissions (submissionsID,teamID,questionID,answer)
VALUES ($questionID,$questionID,$questionID,$userAnswer)");
}
}
$statement->close();
?>
Turns out I had to free_result()before I could run another mysqli statement

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
}

Delete record and count rows to check for result

So Im trying to delete a record from a table using php and sql and check whether it has been deleted using a rowcount() function in an if statement.
Im having problems on both fronts...
<?php
echo $_GET['id'];
if (isset($_GET['id'])) {
$trainingID = $_GET['id'];
}
else {
die('There was a problem with the ID given.');
}
// include the connection file
require_once('./includes/connection.inc.php');
$conn = dbConnect();
// prepare SQL statement
$sql = 'DELETE FROM `trainingCourses` WHERE `trainingID` = "$trainingID"';
$stmt = $conn->prepare($sql);
try {
$stmt->execute();
echo "deleted";
echo $stmt->rowcount();
//check number of rows affected by previous insert
if ($stmt->rowCount() == 1) {
$success = "$trainingID has been removed from the database.";
}
}
catch(PDOException $e){
echo $e;
echo 'Sorry, there was a problem with the database.';
}
?>
I currently get 3 things outputted from my echo's throughout my code, firstly i get T0001, which is the primary key of the record i want to delete from another page. Secondly i get "deleted" which is from an echo within my 'try' statement but the record doesn't actually delete from the database. This is backed up from the rowcount() function which outputs 0.
I can't seem to get this working and im sure it should be simple and is something i am just overlooking!
Will the try method default to the catch if the "if" statement in it fails? As im also unsure what should be output from a rowcount() when a row has been deleted?
Any help you could offer would be really helpful! Thanks!
echo'ing this line
$sql = 'DELETE FROM `trainingCourses` WHERE `trainingID` = "$trainingID"';
will treat $trainingID as string and not variable.
$sql = "DELETE FROM `trainingCourses` WHERE `trainingID` = '$trainingID'";
will do the work BUT its not safe (sql injections). You should use PDO to bind varaibles like this
$sth = $dbh->prepare("DELETE FROM `trainingCourses` WHERE `trainingID` = :id");
$sth->bindParam(":id",$trainingID);
$sth->execute();

Categories