sql INSERT with a php form failing - php

I have an update form which I am trying to enable updating fields but struggling to update the fields when submitting - perhaps I am missing something very obvious here.
Here is my form:
<form action="actions/updateDoc.php" method="POST">
<input type="text" value="<?php echo $doc['doc_title'] ?>" name="doc_title" />
<br />
<input type="submit" value="Update" name="submit" />
</form>
Here is the script to action that form:
<?php
if(isset($_POST["submit"])){
$hostname='localhost';
$username='******';
$password='******';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=******",$username,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
$doc_title = $_POST['doc_title'];
$sql = "UPDATE doc_list (doc_title) SET ('".$_POST["doc_title"]."')";
if ($dbh->query($sql)) {
header ('Location: ../docEdit.php');
}
else{
}
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
?>
The script runs but getting a blank screen and no update occurs. I have now taken some code out to show just updating 1 row, I get the following error:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(doc_title) SET ('Document content sdfsd')' at line 1

First, add the doc_id to your form (as a hidden input) -
<form action="actions/updateDoc.php" method="POST">
<input type="text" value="<?php echo $doc['doc_title'] ?>" name="doc_title" />
<input type="hidden" value="<?php echo $doc['doc_id'] ?>" name="doc_id" />
<br />
<input type="submit" value="Update" name="submit" />
</form>
Then change your php code to get the doc_id (and use prepared statement/placeholders) -
<?php
if(isset($_POST["submit"])){
$hostname='localhost';
$username='******';
$password='******';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=******",$username,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
$sql = "UPDATE doc_list SET doc_title = :doc_title WHERE doc_id = :doc_id";
$query = $dbh->prepare($sql);
$query->execute(array(":doc_title"=>$_POST["doc_title"], ":doc_id"=> $_POST["doc_id"]));
if ($query) {
header ('Location: ../docEdit.php');
}
else{
}
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
?>

Related

Issue updating a record with SQL / PHP

I am very new to PHP. Apologies if this is an elementary question.
I am trying to update a record using PHP / SQL. I have googled this error, but am unable to determine the problem out of the context of my code:
An error occured: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
Here is my function:
function updateTeam($val) {
global $server, $db, $dbUser, $dbKey, $message;
try {
$conn = new PDO("mysql:host=" . $server . ";dbname=" . $db, $dbUser, $dbKey);
$conn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = $conn -> prepare("UPDATE Team SET teamName=:teamName, teamLogo=:teamLogo, WHERE teamID=" . $val);
$sql -> bindValue(":teamID", $_POST["teamID"]);
$sql -> bindValue(":teamName", $_POST["teamName"]);
$sql -> bindValue(":teamLogo", $_POST["teamLogo"]);
$result = $sql -> execute();
if ($result) {
$message = "Customer record was updated";
} else {
$message = "The Customer record was not updated";
}
}
catch(PDOException $e) {
echo "<div class='notification container'><p>An error occured: " . $e -> getMessage() . "</p></div>";
}
$conn = null;
}
if (isset($_POST["updateTeam"])) {
updateTeam($_POST["teamID"]);
}
and here is my markup:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<label>Team ID</label>
<input type="text" name="teamID" placeholder="9" value="<?php echo $teamID; ?>">
<label>Team name</label>
<input type="text" name="teamName" placeholder="Watson's Bay Warriors" value="<?php echo $teamName; ?>">
<label>Team logo (optional)</label>
<input type="text" name="teamLogo" placeholder="Blob" value="<?php echo $teamLogo; ?>">
<input type="submit" name="insertTeam" value="Add">
<input type="submit" name="getTeam" value="Get">
<input type="submit" name="updateTeam" value="Update">
<input type="submit" name="deleteTeam" value="Delete">
</form>
I have similar functions in place that allow me to add, get and delete and have no issues.
"UPDATE Team SET teamName=:teamName, teamLogo=:teamLogo WHERE teamID=:teamID")
Remove the comma before the WHERE clause
In your code:
$sql = $conn -> prepare("UPDATE Team SET teamName=:teamName, teamLogo=:teamLogo, WHERE teamID=" . $val);
$sql -> bindValue(":teamID", $_POST["teamID"]);
$sql -> bindValue(":teamName", $_POST["teamName"]);
$sql -> bindValue(":teamLogo", $_POST["teamLogo"]);
Why is teamID =" .$val but you bind the param teamID to a post value? Could that be the error?

How to make a warning message if possible duplicate entry is added?

I have here the code for insertion using PDO and the insertion is working fine my problem is that how can i can determine if i inputted in the textbox the record that is already in the database,in my database ihave a column of ID, Firstname and Lastname, ID is auto increment,Firstname is set to unique and lastly is password set to varchar..what i want to happen is that when try to insert a record that is already in the database i want a warning message or maybe a alert message that tells me that "the record is already duplicate"..can somebody please help me with it?
here is the code
class.php
public function create($username,$password,$province)
{
try
{
$stmt = $this->db->prepare("INSERT INTO login(Firstname,Lastname) VALUES(:Firstname, :Lastname)");
$stmt->bindparam(":Firstname",$Firstname);
$stmt->bindparam(":Lastname",$Lastname);
$stmt->execute();
return true;
}
catch(PDOException $e)
{
echo $e->getMessage();
return false;
}
}
and here is index.php
<?php
include_once 'dbconfig.php';
if(isset($_POST['btn-save']))
{
$username = $_POST['Firstname'];
$password = $_POST['Lastname'];
if($crud->create($Firstname,$Lastname))
{
echo "<script type='text/javascript'>alert('Saved!');</script>";
}
else
{
echo "<script type='text/javascript'>alert('Insertion Failed!'); </script>";
}
}
?>
<form method="POST" class="signin" action="" name="Add" target="iframe">
<fieldset class="textbox">
<label class="username">
<span>Username</span>
<input id="Firstname" name="Firstname" value="" type="text" placeholder="Username" required/>
</label>
<label class="password">
<span>Password</span>
<input id="Lastname" name="Lastname" value="" type="password" Placeholder="Password" required/>
</label>
<br />
<button id="submit" type="submit" name="btn-save">Save</button>
<button id="submit" type="reset" name="reset">Reset</button>
<br />
<br />
<hr>
</fieldset>
</form>
If you have the correct UNIQUE keys set in your database, PDO will already throw such a warning/error. You can easily try it yourself by inserting twice the same name
You should try to change your code to this, as this will throw the actual error. The correct function to call would be PDOStatement::errorInfo
Example code would be like this:
public function create($username,$password,$province)
{
try
{
$stmt = $this->db->prepare("INSERT INTO login(Firstname,Lastname) VALUES(:Firstname, :Lastname)");
$stmt->bindparam(":Firstname",$Firstname);
$stmt->bindparam(":Lastname",$Lastname);
if (!$stmt->execute())
{
throw new Exception('Could not execute SQL statement: ' . var_export($stmt->errorInfo(), TRUE));
}
return true;
}
catch(Exception $e)
{
// Here you can filter on error messages and display a proper one.
return $e->getMessage();
}
}
In your index.php, change your PHP code to this:
if(isset($_POST['btn-save']))
{
$username = $_POST['Firstname'];
$password = $_POST['Lastname'];
$result = $crud->create($Firstname,$Lastname);
if($result === TRUE)
{
echo "<script type='text/javascript'>alert('Saved!');</script>";
}
else
{
echo "<script type='text/javascript'>alert(" . $result . "); </script>";
}
}
An other, better, method would be to do a separate SELECT before you do the actual insert to see if the values you are trying to insert already exist.

Echo same MySql query in different part of the page

This might be a silly question but I am trying to call the same query to two different pages but once I call the second time, the link to the page would not work anymore. The way I have it setup at the moment is that all the pages in the app are on one file (index.php). I am linking to each page by using id (href="#page2"). If I call the same query, depending on the order of pages, only the "top" page, or in this case, Page 1 will work. I tried changing the variable names so that it would treat it as a different call but to no avail.
I am developing this app using Phonegap Build and it would be really helpful if ANYBODY can help.
Page 1
<div data-role="page" id="page1">
<form action="post-comment.php" method="POST">
<h3>COMMENT</h3>
<input type="text" name="name" placeholder="Name"><br />
<textarea name="comment" cols="50" rows="2" placeholder="Enter Comment"></textarea><br />
<input type="submit" value="comment" onClick="javascript.ajax_post()"></input><br />
</form>
<?php
$find_comments = mysql_query("SELECT * FROM COMMENTS");
while($row = mysql_fetch_assoc($find_comments))
{
$comment_name = $row['name'];
$comment = $row['comment'];
echo "$comment_name - $comment<br />" ;
}
?>
</div>
Page 2
<div data-role="page" id="page2">
<?php
$find_comments1 = mysql_query("SELECT * FROM COMMENTS");
while($row = mysql_fetch_assoc($find_comments1))
{
$comment_name1 = $row['name'];
$comment1 = $row['comment'];
echo "$comment_name1 - $comment1<br />" ;
}
?>
</div>
I suggest using PDO - DOC instead of mysql, I would do it this way :
Connect to your database :
$hostdb = "your_host";
$namedb = "db_name";
$userdb = "user_name";
$passdb = "pass";
$options = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING);
try {
$db = new PDO("mysql:host=$hostdb; dbname=$namedb; charset=utf8", $userdb, $passdb, $options);
return $db;
} catch (PDOException $e) {
$err = "DB Connection Error, because: ". $e->getMessage();
print $err;
}
Now you can use $db to connect to your database in your script and fetch comments :
<div data-role="page" id="page1">
<form action="post-comment.php" method="POST">
<h3>COMMENT</h3>
<input type="text" name="name" placeholder="Name"><br />
<textarea name="comment" cols="50" rows="2" placeholder="Enter Comment"></textarea><br />
<input type="submit" value="comment" onClick="javascript.ajax_post()"></input><br />
</form>
<?php
$find_comments ="SELECT * FROM COMMENTS";
$stmt = $db->prepare($find_comments);
if(!$stmt->execute()){
print "error";
} else {
$comments = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($comments as $comment) {
echo $comment['name']."</br>";
echo $comment['comment'] ;
}
$stmt->closeCursor(); // Close connection
}
?>
</div>
then in your Page2 just do the same as Page1. You can define the SQL statement as a global variable and re-use it in your second query. just make sure to use closeCursor(); to close your db connection.

PHP Forms to update a SQLite3 database

I need some help I am trying to create a PHP form using sqlite3 and I keep on getting a "syntax error, unexpected T_CATCH in post.php on line 10". All I want to do from the php form is update an existing sqlite3 database in the table1 where the column type = p and the column id = 340 with the values from the form.
HTML Code:
<html>
<head>
<title>Update Form</title>
</head>
<body style="font-size:12;font-family:verdana">
<form action="post.php" method="post">
<p>
Slot1: <input type="text" name="slot1"><br>
Slot2: <input type="text" name="slot2"><br>
</p>
<p>
<input type="submit" name="update" value="update">
</p>
</form>
</body>
</html>
PHP Code: Post.php
<?php
$slot1 = sqlite_escape_string($_POST['slot1']);
$slot2 = sqlite_escape_string($_POST['slot2']);
try
{
$db = new PDO("sqlite:DefaultLibrary.db");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
catch(Exception $e)
{
echo $e->getMessage();
}
}
if (!empty($slot1)) {
try
{
$stmt = $db->prepare("UPDATE tabel1 SET Slot1Pos = :slot1, Slot2Pos = :slot2 WHERE Type = P and ID = 340");
$stmt->bindParam(':slot1', $slot1, PDO::PARAM_STR);
$stmt->bindParam(':slot2', $slot2, PDO::PARAM_STR);
$stmt->execute()
}
catch(Exception $e)
{
echo $e->getMessage();
}
echo "Form submitted successfully";
}
Looks like you're missing a brace:
try {
$db = new PDO("sqlite:DefaultLibrary.db");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(Exception $e) {
echo $e->getMessage();
}

PHP - checkbox value / db insert and if(isset())

I'm new to PHP, and I have stumble on the problem which I don't know how to solve. I'm 99% it is due my poor knowledge of PHP ( I'm PHP user since last Monday:) )
Just in front I will declarate that:
db conncetion is working
table does exist
values are saved correctly to the db
I have following form:
<form id="loginForm" name="loginForm" method="post" action="../exe/news-exec.php">
<input name="live" type="checkbox" class="textfield" id="live" />
<input name="content" type="text" class="textfield" id="content" />
<input type="submit" name="Submit" value="Register" />
</form>
And following file is executing this:
<?php
//Start session
session_start();
//Include database connection details
require_once('../inc/config.php');
//Connect to mysql server
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
//Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
//Sanitize the POST values
$live = clean($_POST['live']);
$content = clean($_POST['content']);
if(isset($live)) { $live = 1;}
if(!isset($live)) { $live = 0;}
//Create INSERT query
$qry = "INSERT INTO news(live, content) VALUES('$live','$content') ";
$result = #mysql_query($qry);
//Check whether the query was successful or not
if($result) {
echo $live."<br /><br />";
echo 'Index File';
exit();
}else {
die("Query failed");
}
?>
What the form should do:
if the checkbox is checked - save the value of '1' into field 'live' in the table 'news'
if the checkbox is NOT checked - save the value of '0'
If the checkbox has been checked everything is working fine, but if the checkbox is not checked (should echo $live = 0 ), but is displaying value = 1 and following notice: Notice: Undefined index: live in C:\wamp\www\exe\news-exec.php on line 30
Line 30: $live = clean($_POST['live']);
I'm 99% sure the problem are those declaration:
if(isset($live)) { $live = 1;}
if(!isset($live)) { $live = 0;}
What I'm doing wrong? Any suggestion much appreciated.
HTML:
<input type="hidden" name="live" class="textfield" id="live0" value="0" />
<input type="checkbox" name="live" class="textfield" id="live1" value="1" />
PHP:
$live = clean($_POST['live']);
What happens here is that when the checkbox is left unchecked, the hidden field’s value gets submitted, as-is. When the check box is checked, the hidden field’s POST value gets overwritten by the activated checkbox’s.
Hope this helps.
Try this:
if (isset($_POST['live'])) $live=1; else $live=0;
Line 30: $live = clean($_POST['live']);
causes isset($live) to be true, no matter if $_POST['live'] is set or not, so you have to check $_POST['live'] directly.
According to the HTML specs, checkboxes are not sent to the server unless they are checked. You can see the exact contents of $_POST with the var_dump() function.
There are many ways to deal with this. Since you are not assigning a value attribute, I guess the value is irrelevant so you can do this:
// $live is now a boolean
$live = isset($_POST['live']);
First of all you don't need to clean a variable that's existance is used as a flag. You get the error message because in the case the checkbox is not checked $_POST['live'] doesn't even exist.
$live = (isset($_POST['live']))?1:0;
Should indeed do the trick. Just for some practice with the ternary operator.
When you don't check the checkbox, $_POST["live"] is not set, that's why you get the error.
You should try something like:
$live = isset($_POST["live"]) ? 1 : 0;
To check Checkbox checked or not do the following :
<input name="live" type="checkbox" class="textfield" id="live" value="Yes" />
if(isset($_POST['live']) && $_POST['live'] == 'Yes')
{
$live = 1;
}
else
{
$live = 0;
}
and check the query
<input name="live" type="checkbox" value="Yes" class="textfield" id="live" />
if(isset($live) && $live == 'Yes'){
$live = 1;
}else{
$live = 0;
}
As well as the examples given here, you might want to check the data type you've set on the DB column for "live". You're passing it as a string, but if you've set it as an INT you don't need the quotes around the value in the INSERT
$qry = "INSERT INTO news(live, content) VALUES($live,'$content') ";
Same with PDO
<?php
//Start session
session_start();
//Include database connection details
require_once('../inc/config.php');
/*** pdo connect ***/
$dbh = new PDO("mysql:host=$hostname;dbname=YOURDB", $username, $password);
/*** prepare the SQL statement ***/
$stmt = $dbh->prepare("INSERT INTO news(live, content) VALUES(:checkbox,:textbox)");
if(isset($_POST)){
$live = $_POST['live'];
$content = $_POST['content'];
try {
/*** bind the paramaters ***/
$stmt->bindParam(':checkbox', $live, PDO::PARAM_INT);
$stmt->bindParam(':textbox', $content);
/*** execute the prepared statement ***/
$stmt->execute();
echo "Query successful ".$live."<br /><br />";
echo 'Index File';
}catch(PDOException $e){
die("Query failed");
}
}else{
?>
<form id="loginForm" name="loginForm" method="post" action="../exe/news-exec.php">
<input name="live" type="checkbox" value="1" class="textfield" id="live" />
<input name="content" type="text" value="" class="textfield" id="content" />
<input type="submit" name="Submit" value="Register" />
</form>
<?php
}
/*db finnish*/
$dbh = null;
?>

Categories