This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 3 years ago.
I can't insert the text from textarea when the text has apostrophe please sir's how to fix it.
this my whole code. I try mysqli_real_escape_string but it gives a error.
<?php
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "srdatabase";
$conn = new mysqli($servername, $username, $password, $dbname);
$speakerid = $_SESSION['speakerid'];
$speaker_info = "SELECT * FROM speakers WHERE id=$speakerid";
$si_result = mysqli_query($conn, $speaker_info);
$array = mysqli_fetch_array($si_result);
$dbfullname = $array['speaker_fullname'];
$dbimage = $array['speaker_image'];
$dbspecialization = $array['speaker_specialization'];
$dbdescription = $array['speaker_description'];
$dbpaymentcost = $array['speaker_paymentcost'];
?>
<!DOCTYPE html>
<html>
<head>
<title>Update Speaker</title>
</head>
<body>
<form action="updateSpeaker.php" method="post" enctype="multipart/form-data">
<textarea name="description" class="inputbox" cols="60" rows="5" autofocus required="required" maxlength="2000" style="resize:none;" placeholder="Description"><?php echo htmlspecialchars($dbdescription);?></textarea>
<br>
<input name="update" id="buttonsubmit" type="submit" value="Update">
</form>
<?php
if(isset($_POST['update']))
{
$newdescription = $_POST["description"];
$finaldescription = $mysqli_real_escape_string($conn, $newdescription);
$update_data = "UPDATE speakers SET speaker_fullname = '".$_POST["fullname"]."', speaker_description = '$finaldescription', speaker_specialization = '".$_POST["specialization"]."', speaker_paymentcost = '".$_POST["paymentcost"]."' WHERE id=$speakerid";
mysqli_query($conn, $update_data);
}
?>
</body>
</html>
Prepared statement:
$update_data = "UPDATE speakers SET speaker_fullname=?, speaker_description=?, speaker_specialization=?, speaker_paymentcost=? WHERE id=?";
$stmt = mysqli_prepare($conn, $update_data);
mysqli_stmt_bind_param($stmt, 'ssssd', $_POST["fullname"], $finaldescription, $_POST["specialization"], $_POST["paymentcost"], $speakerid);
Your current code is also mixing OOP and procedural based functions, so it will not work even once you have fixed the original issue with quoting user input.
I have converted your code into PDO (untested), which should point you in the right direction. Hope it helps.
<?php
session_start();
// config holder
$config = [
'db' => [
'host' => 'localhost',
'user' => 'root (DONT USE ROOT)',
'pass' => '',
'name' => 'srdatabase',
]
];
// connect to database
try {
$db = new PDO(
"mysql:host=" . $config['db']['host'] .";dbname=". $config['db']['name'],
$config['db']['user'],
$config['db']['pass'],
array(
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
)
);
} catch (PDOException $e) {
exit('Could not connect to database.');
}
// check id, though should be getting this from a $_GET
if (empty($_SESSION['speakerid']) || !is_numeric($_SESSION['speakerid'])) {
exit('Invalid speaker id');
}
// handle post
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errors = [];
// check or set inbound variables
$id = isset($_POST['id']) ? (int) $_POST['id'] : 0;
$description = isset($_POST['description']) ? $_POST['description'] : null;
// you could set errors here if there empty, but lets continue
/*
if (empty($description)) {
$errors['description'] = 'Description is a required field.';
}
*/
if (
empty($errors) && // check for no errors
!empty($id) && // not required if you checked above, check id is not empty
!empty($description) // not required if you checked above, check description is not empty
) {
// prepare query for update, only want to update description
try {
$stmt = $db->prepare('
UPDATE speakers
SET speaker_description = :description
WHERE id = :id
');
// bind inbound variables to the query, then execute
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->bindParam(':description', $description, PDO::PARAM_STR);
$stmt->execute();
} catch (PDOException $e) {
$errors['query'] = 'Error updating database: '.$e->getMessage();
}
}
}
// select current row based upon the id
$stmt = $db->prepare('SELECT * FROM speakers WHERE id = :id LIMIT 1');
$stmt->bindParam(':id', $_SESSION['speakerid'], PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetch();
/* would contain
$result['speaker_fullname'];
$result['speaker_image'];
$result['speaker_specialization'];
$result['speaker_description'];
$result['speaker_paymentcost'];
*/
?>
<!DOCTYPE html>
<html>
<head>
<title>Update Speaker</title>
</head>
<body>
<?php if (!empty($errors['query'])): ?>
<?= $errors['query'] ?>
<?php endif ?>
<form action="" method="post" enctype="multipart/form-data">
<input type="hidden" name="id" value="<?= $_SESSION['speakerid'] ?>">
<textarea name="description" class="inputbox" cols="60" rows="5" autofocus required="required" maxlength="2000" style="resize:none;" placeholder="Description"><?= htmlentities($result['speaker_description']) ?></textarea>
<?php if (!empty($errors['description'])): ?>
<span style="color:red"><?= $errors['description'] ?></span>
<?php endif ?>
<br>
<input name="update" id="buttonsubmit" type="submit" value="Update">
</form>
</body>
</html>
Related
I'm working on a basic database app which uses a sql database to store and retrieve information from as part of the crud operations the creation and reading of data works perfectly fine. However I'm facing issues with updating and deleting the data stored and it never happened before.Is there something I'm doing wrong?
I'm assuming the something that I've done wrong in update may be similar to my issue in delete.
Here's the code for the update part : [Note this is just for a basic demo and so security features aren't important]
<?php
require "config.php";
require "common.php";
if (isset($_POST['submit'])) {
try {
$connection = new PDO($dsn, $username, $password, $options);
$user =[
"char_id" => $_POST['char_id'],
"char_name" => $_POST['char_name'],
"currency" => $_POST['currency'],
"server_id" => $_POST['server_id'],
"account_id" => $_POST['account_id']
];
$sql = "UPDATE characters
SET
char_name = :char_name,
currency = :currency,
server_id = :server_id,
account_id = :account_id
WHERE char_id = :char_id";
$statement = $connection->prepare($sql);
$statement->execute($user);
} catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
}
if (isset($_GET['char_id'])) {
try {
$connection = new PDO($dsn, $username, $password, $options);
$char_id = $_GET['char_id'];
$sql = "SELECT * FROM characters WHERE char_id = :char_id";
$statement = $connection->prepare($sql);
$statement->bindValue(':char_id', $char_id);
$statement->execute();
$user = $statement->fetch(PDO::FETCH_ASSOC);
} catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
} else {
echo "Something went wrong!"; //this happens
exit;
}
?>
<?php require "templates/header.php"; ?>
<?php if (isset($_POST['submit']) && $statement) : ?>
<blockquote><?php echo escape($_POST['char_name']); ?> successfully
updated.</blockquote>
<?php endif; ?>
<h2>Edit a character</h2>
<form method="post">
<?php foreach ($user as $key => $value) : ?>
<label for="<?php echo $key; ?>"><?php echo ucfirst($key); ?>
</label>
<input type="text" name="<?php echo $key; ?>" id="<?php echo $key; ?>" value="<?php echo escape($value); ?>" <?php echo ($key === 'id' ? 'readonly' : null); ?>>
<?php endforeach; ?>
<input type="submit" name="submit" value="Submit">
</form>
Back to home
<?php require "templates/footer.php"; ?>
The problem seems to be that your loop of inputs expects an array variable called $user. The $user comes from a DB query, using inputs from your form, but the actual input values comes from the $user variable which isn't set until the DB query is run!
First I would try keeping the $_GET in your code. Your SELECT query expects $_GET['char_id'] to be set in order to execute. Do that by adding ?char_id=SOME NUMBER HERE to your url and go. The number should be a char_id present in your Database.
Now the DB query gets the $_GET['char_id'] that it needs (since the $_GET method fetches parameters from the URL), and you should get some working inputs from your loop, and be able to update entries in your Database.
How to insert every value of array variable in database, whenever i try to insert value using array variable it gives me a error "Array to string conversion".Actually i want to store the attendance of students into "attendance database table", i am retrieving id and name of students from students database, this information of students is being stored in array but when i use array variable"$result" to insert the name of student into attendence_tbl database it gives me error of array to string conversion.
<html>
<head>
</head>
<body>
<div class="container">
<div class="row">
<div class="templatemo-line-header" style="margin-top: 0px;" >
<div class="text-center">
<hr class="team_hr team_hr_left hr_gray"/><span class="span_blog txt_darkgrey txt_orange">Attendance Form</span>
<hr class="team_hr team_hr_right hr_gray" />
</div>
</div>
</div>
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
include("config.php");?>
<div class="form-container">
<form method="post" action="" role="form">
<!-- <div class="container"> -->
<div class="col-lg-3">
<div class="form-group">
<?php
$qs=mysql_query("select * from student_table");
?>
<table border=1>
<?php
$c=0;
while($stid=mysql_fetch_row($qs))
{
?>
<tr>
<td ><?php echo $stid[0]?></td>
<td><?php echo $stid[1]?></td>
<td>
<select name="present[]" >
<option value=""> ---Select Attendence--- </option>
<option value="P"> Present </option>
<option value="A"> Absent </option>
</select></td>
</tr>
<?php
$stud= $stid[0];
$subj= $stid[1];
$location_vars = array(/*"stud" ,*/ "subj");
$result[] = compact("nothing_here", $location_vars);
$date = date('Y-m-d H:i:s');
$c++;
}
// echo "</select>"."<br>";
echo $c;
$e=0;
if(isset($_POST['present'])){
foreach($_POST['present'] as $present){
print_r($result);
$query=mysql_query("Insert into tbl_attendence (StudentRollNumber,SubjectId,Attendence,Date)VALUES('$stud','$stid','$present','$date')");
$e++;
}}
?>
</table>
</div>
</div> <!--col-lg-4-->
<button type="submit" name="save" value="Save" class="btn btn-success btn-sm">Save</button>
</form>
</div> <!--form-container-->
</div><!--container-->
</body>
</html>
Seems you want to put an array variable data directly into table which is supposed to throw error,
Here is the solution.
For adding all value of an array directly into table you have to use first convert array into json and then need to insert it into database. like this..
$resultJson = json_encode($result);
$query = mysql_query("Insert into tbl_attendence (StudentRollNumber,SubjectId,Attendence,Date)VALUES(".$stud.", ".$resultJson.", ".$present.", ".$date.")");
AND if you want to add all array value into database for each value per row separately then you have to make sure run the loop and then insert each value into database for each record.
If I understand you right you want to upload something like this:
Array([1] => '1', [2] => '2')
into a table, which would not work. So you'd have to use JSON to stringify the array. Example:
<?php
$value = 'Some string';
$value2 = 'Some other string';
$values = Array('String 1', 'String 2', 'String 3');
$json_values = json_encode($values);
$mysqli = new mysqli('HOSTNAME', 'USERNAME', 'PASSWORD', 'DATABASE'); // Connecting to SQL Server
// Checking if connection was successfull
if( $mysqli->connect_errno ){
echo 'There was an error connection to the SQL Server<br>';
echo '(' . $mysqli->connect_errno . ') ' . $mysqli->connect_error;
exit; // FAIL
}
// Preparing a statement
$stmt = $mysqli->prepare('INSERT into TABLENAME(value, value2, values) VALUES(?, ?, ?)');
// Checking if php prepared the statement successfully
if(!$stmt){
echo 'There was an error preparing the statement!';
exit;
}
if( !$stmt->bind_param('sss', $value, $value2, $json_values) ){
echo 'There was an error binding params to the statement!';
exit;
}
$stmt->execute();
?>
to post arrays into DB I use this approach:
//database connection class
class Database{
// specify your own database credentials
private $host = "YOUR HOST";
private $db_name = "DATABASE NAME";
private $username = "USERNAME";
private $password = "PASSWORD";
public $conn;
// get the database connection
public function getConnection(){ $this->conn = null;
try{
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
}catch(PDOException $exception){
echo "Connection error: " . $exception->getMessage();
}
return $this->conn;
}
}
//model class
class Model{
// database connection
private $conn;
// constructor with $db as database connection
public function __construct($db){
$this->conn = $db;
}
// add info to db
function create($fieldset){
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// query to insert record
$query = "INSERT INTO
tbl_attendence
SET
$fieldset";
// prepare query
$stmt = $this->conn->prepare($query);
// execute query
if($stmt->execute()){
return true;
}else{
return false;
}
}
}
//part that will handle the post
// get database connection
$database = new Database();
$db = $database->getConnection();
//instatiate model
$model = new Model($db);
//function that will filter posted values
function filter($value){
$value = trim($value);
$value = strip_tags($value);
$value = stripslashes($value);
$value = htmlentities($value);
return $value;
}
if(!empty($_POST)){
//Get Variables
foreach($_POST as $key => $value){
//this part will tackle values which are arrays
if(is_array($value)){
$val=implode(",",filter($value));
$groupVal[] = $val;
$groupKeys[] = $key;
}
else{
$groupVal[] = $this->filter($value);
$groupKeys[] = $key;
}
}
//count items in array to establish a limit
$limit = count($_POST);
//arranges the data into "key = value" format
for($i=0;$i<$limit;$i++){
$prepFieldset[$i] = "$groupKeys[$i] = $groupVal[$i]";
}
//prepares the fieldset to be used in SQL query
$fieldset = implode(",",$prepFieldset);
//process them in the model
$status = $model->create($fieldset);
//show response
if($status == true){
$response = 'Data saved';
}
else{
$response = 'Error when saving data';
}
}
I have a large HTML form containing 340 fields that I need entered into a Microsoft SQL Server 2008 R2. I'm trying to find a way to enter the data without meticulously writing out each variable in the PHP code (in $sql & $params). Maybe it's possible if the columns and variables had the same name.Here's a smaller version of the HTML form and the entire PHP coode. The SQL table currently only has the columns "Date" & "PartNumber".
HTML code:
<!DOCTYPE html>
<html>
<head>
<title>Form</title>
</head>
<body>
<form id="test" action="http://10.0.0.252/test.php" method="post" accept-charset="ISO-8859-1">
<input type="text" tabindex="1" id="form283_1" value="" data-objref="61 0 R" title="Date:" name="Date" />
<input type="text" tabindex="4" id="form339_1" value="" data-objref="62 0 R" title="PartNo." name="PartNo" />
<input type="submit" value="Submit" id="form366_1">
</form>
</body>
</html>
PHP code:
<?php
$post = file_get_contents('php://input');
$serverName = "FILESERV1\SQLEXPRESS";
$connectionInfo = array(
"UID" => "user",
"PWD" => "Password",
"Database" => "ipadforms"
);
$conn = sqlsrv_connect($serverName, $connectionInfo);
if ($conn === false) die("<pre>".print_r(sqlsrv_errors(), true));
echo "Successfully connected!";
if(empty($_POST) === false && empty($errors)=== true)
{
$sql = "INSERT INTO dbo.MF001 (Date,PartNumber) VALUES (?,?)";
$params = array($post);
$stmt = sqlsrv_query( $conn, $sql , $params);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
sqlsrv_close($conn);
}
Have an array of form field names -> table field names, then iterate it?
$fields = array('formfield1' => 'dbfield1', 'formfield2' => 'dbfield2', etc...);
foreach($fields as $formfield => $dbfield) {
$sql = "INSERT INTO dbo.FM001 ($dbfield) VALUES (?)";
$stmt = $dbh->prepare($sql);
$stmt->execute(array($_POST[$formfield));
}
Note that the $dbfield has to be interpolated into the query string directly, since placeholders can only represent VALUES, not sql keywords or identifiers.
The textarea is not reading any input that is typed into the box. Initially, I was using PHP to check if the textarea was empty, and was recieveing an error there. So I removed that check, to see if it was php that was causing the issue, and added the required="required" attribute to the textarea tag, and even that is coming back with Please fill out this field. I am not quite sure where I am going wrong with my code, I had it working previously, then all of a sudden it stopped working, and I am completely confused as to why. I also looked at various other posts about the textarea not submitting, and ensured that I was checking the post with the name, not the ID; and making sure the textarea was submitting to the same form as the submit button. I have also tried it without specifying the form on the textarea tag.
HTML Code:
<form action="" method="post" id="CreateTopicForm">
<input type="hidden" name="create-topic" />
<span class="secondary radius label"><strong>Title</strong></span>
<input type="text" name="title" id="title" />
<span class="secondary radius label"><strong>Message</strong></span>
<textarea name="content" id="content" required="required" form="CreateTopicForm"></textarea>
<?php if($_SESSION['user']['account_type'] >= 3): ?>
<span class="secondary radius label"><strong>Sticky Topic</strong></span>
<input type="checkbox" name="sticky" /><br />
<?php endif ?>
<input type="submit" value="Post Topic" class="topic-post" />
</form>
PHP Code:
/* Retrieve necessary variables */
$fid = $_GET['fid'];
/* Get Forum Information */
$query = "SELECT * FROM bkg_forums where forum_id = :id";
$query_params = array(
':id' => $fid
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
} catch(PDOException $e) {
$error[] = $pdoerror;
}
$forum = $stmt->fetchAll();
/* Begin the database upload */
if(!empty($_POST)){ /* Plan to change to if($_REQUEST['submit']) */
/* Check if data was actually submitted */
$db->beginTransaction();
/* DO SOME ERROR CHECKING. MAKE SURE FIELDS ARE NOT EMPTY. */
if(empty($_POST['title'])){
$error[] = "Sorry! You must enter a title!";
}
/* Previously had a check if $_POST['content'] */
/* GENERATE SOME VARIABLES NEEDED TO INSERT INTO TABLES. ACCOUNT_TYPE IS TEMPORARY*/
if($_SESSION['user']['account_type'] == 0) {
$account_type = "Normal";
$color = "white";
} elseif($_SESSION['user']['account_type'] == 1) {
$account_type = "Donator";
$color = "#F4FA58";
} elseif($_SESSION['user']['account_type'] == 2) {
$account_type = "Moderator";
$color = "#2EFE2E";
} elseif($_SESSION['user']['account_type'] == 3) {
$account_type = "Community Manager";
$color = "#0000FF";
} elseif($_SESSION['user']['account_type'] == 4) {
$account_type = "Administrator";
$color = "#DF0101";
}
if(isset($_POST['sticky'])){
$sticky = 1;
} else {
$sticky = 0;
}
if(!isset($error)){
/* INSERT INTO TOPICS TABLE */
$query = "INSERT INTO bkg_topics (
forum_id,
icon_id,
topic_approved,
topic_title,
topic_text,
topic_poster_id,
topic_poster,
topic_poster_color,
topic_post_time,
topic_status,
topic_type
) VALUES (
:forumid,
:iconid,
:topicapproved,
:topictitle,
:topictext,
:topicposter_id,
:topicposter,
:topicposter_color,
:topicpost_time,
:topicstatus,
:topictype
)";
$query_params = array(
':forumid' => $fid,
':iconid' => 1,
':topicapproved' => 1,
':topictitle' => $_POST['title'],
':topictext' => $_POST['content'],
':topicposter_id' => $_SESSION['user']['id'],
':topicposter' => $_SESSION['user']['displayname'],
':topicposter_color' => $color,
':topicpost_time' => time(),
':topicstatus' => 0,
':topictype' => $sticky
);
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
$lastid = $db->lastInsertId();
/* Retrieve the last id of a topic, used to generate some links. */
/* UPDATE FORUM TABLE */
$query = "UPDATE bkg_forums SET
`forum_last_post_id` = :lastpostid,
`forum_last_post_topic_id` = :lastposttopicid,
`forum_last_post_title` = :lastposttitle,
`forum_last_poster_id` = :lastposterid,
`forum_last_post_time` = :lastposttime,
`forum_last_poster_name` = :lastpostername,
`forum_last_poster_color` = :lastpostercolor
WHERE `forum_id` = :forumid
";
$query_params = array(
':lastpostid' => null,
':lastposttopicid' => $lastid,
':lastposttitle' => $_POST['title'],
':lastposterid' => $_SESSION['user']['id'],
':lastposttime' => time(),
':lastpostername' => $_SESSION['user']['displayname'],
':lastpostercolor' => $color,
':forumid' => $fid
);
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
if($fid == 13){
$query = "INSERT INTO updates (
title,
content,
`date`,
`user`,
`topic_id`
) VALUES (
:title,
:content,
:date_posted,
:user_posted,
:topic_id
)";
$query_params = array(
':title' => $_POST['title'],
':content' => $_POST['content'],
':date_posted' => time(),
':user_posted' => $_SESSION['user']['displayname'],
':topic_id' => $lastid
);
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
try {
$db->commit();
$post_ok = 1;
} catch(PDOException $e) {
$erroradmin[] = $e->getMessage();
$db->rollback();
}
if(isset($post_ok)): ?>
<script>
location.href = "http://www.boundlessknights.com?viewtopic&fid=<?php echo $fid; ?>&tid=<?php echo $lastid; ?>";
</script>
<?php else: ?>
<?php $error[] = "Your topic did not post."; ?>
<?php endif; ?>
<?php
}
}
?>
Questions I looked at:
Form Post Not Reading Any Value
Cannot Get the Value of a Textarea via Post Method
Textarea Not Posting with Form
Textarea Returns Empty Value in PHP Post
TinyMCE does not keep the underlying textarea in sync at all times. Normally, when you post the form, TinyMCE will update the textarea before the form is posted but the process seems to be stopped by the required attribute. You can use the following API call to force TinyMCE to update the textarea:
tinymce.triggerSave();
This will force TinyMCE to update the textarea when its called. You can either:
Do this in the onsubmit event of the form
Do this in the TinyMCE init:
tinymce.init({
selector: "textarea",
setup: function (editor) {
editor.on('change', function () {
tinymce.triggerSave();
});
}
});
Your page is using TinyMCE editor. It is giving the following error in the console: An invalid form control with name='content' is not focusable.
Fixing that will fix your problem.
Hmmm, did you try to remove this "form" attribute from your Textarea ?
<textarea name="content" id="content" required></textarea>
Tell us what it do when u try.
Change this
<textarea name="content" id="content" required="required" form="CreateTopicForm"></textarea>
to this
<textarea name="content" id="content" required="required" ></textarea>
You might not be able to post anything because you've NOT specified the action attribute of your form.
<form action="" method="post" id="CreateTopicForm">
Set it to the name of the php file (with the proper path to the file),
and it should work.
Note: To make sure the the $_POST array contains your form submitted values, do a var_dump($_POST).
Hi I am trying to read an instance of my object person, take its individual details using a form, and then put it into a database. I think I have my code setting up the person, and connecting to the database ok, I just cant get it right when processing the information for the form, and reading it into the database. any help with be greatly appreciated!
my form
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<form action="process.php" method="post">
First Name: <input type="text" name="firstName" />
Last Name: <input type="text" name="lastName" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>
where I have my attempt at processing it
<?php
$i = 0;
$firstName = 'firstName';
$lastName = 'lastName';
$age = 'age';
$person = new person ($i,$firstName, $lastName, $age);
$PersonDAO = new PersonDAO();
$dao->insert($person);
?>
my DAO
class PersonDAO extends Person{
protected $link;
public function __construct() {
$host = "localhost";
$database = "test";
$username = "root";
$password = "";
$dsn = "mysql:host=$host;dbname=$database";
$this->link = new PDO($dsn, $username, $password);
$this->link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
public function __destruct() {
$this->link = null;
}
public function insert($person){
if (!isset($person) && $person != null){
throw new Exception("Person Required");
}
$sql = "INSERT INTO person(firstName, lastName, age)"
. "VALUES (:firstName, :lastName, :age)";
$params = array(
'firstName' => $person->getFirstName(),
'lastName' => $person->getLastName(),
'age' => $person->getAge(),
);
$stmt = $this->link->prepare($sql);
$status = $this->execute($params);
if ($status != true){
$errorInfo = $stmt->errorInfo();
throw new Exception("Could Not Add Person: " . $errorInfo[2]);
}
$id = $this->link->lastInsertId('person');
$person->setId($id);
}
}
?>
my form comes up fine, but when i click submit it says
"Fatal error: Class 'person' not found in /Applications/XAMPP/xamppfiles/htdocs/personProj/process.php on line 6"
any ideas? thanks
You might want to try:
$person = new Person ($i,$firstName, $lastName, $age);
If the class is defined with a capital, you should call it with a capital letter as well. It's always a good idea to be consistent with the case of method/class calls. In many other languages like Java, this is very strict (although PHP can be loose about this rule in some cases).