This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 7 years ago.
I've a multidimensional array to insert into mysql table. Trying to add datetime time along with other elements in that array.
but everytime i get this error. :
Notice: Undefined offset: 10 in C:\xampp\htdocs\Auto-attendance\main\proccess_attendance.php on line 47
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'att_status' cannot be null' in C:\xampp\htdocs\Auto-attendance\main\proccess_attendance.php:60 Stack trace: #0 C:\xampp\htdocs\Auto-attendance\main\proccess_attendance.php(60): PDOStatement->execute(Array) #1 {main} thrown in C:\xampp\htdocs\Auto-attendance\main\proccess_attendance.php on line 60
I don't get where is the prob.
<?php
require_once("db_const.php");
if (!$_SERVER['REQUEST_METHOD']=='POST'
|| !$_POST['submit']=='save'
|| empty($_POST['subject_name'])
|| empty($_POST['subject_code'])
|| empty($_POST['department_name'])
|| empty($_POST['department_short_name'])
|| empty($_POST['teacher_name'])
|| empty($_POST['date'])
|| empty($_POST['time'])
|| empty($_POST['student'])
|| empty($_POST['stroll'])
|| empty($_POST['status'])
) {
header('Location: ../student_attendance.php?page=take-attendance');
} else {
## connect mysql server
/** $mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
# check connection
if ($mysqli->connect_errno) {
echo "<p>MySQL error no {$mysqli->connect_errno} :
{$mysqli->connect_error}</p>";
exit();
}**/
## query database
# prepare data for insertion 538 072 662 2716
$subject_name = $_POST['subject_name'];
$subject_code = $_POST['subject_code'];
$department_name = $_POST['department_name'];
$department_short_name = $_POST['department_short_name'];
$teacher_name = $_POST['teacher_name'];
$date = $_POST['date'];
$time = $_POST['time'];
$student = $_POST['student'];
$student_roll = $_POST['stroll'];
$status = $_POST['status'];
$date=date_create_from_format("j-M-Y", $date);
$date= date_format($date,"Y-m-d");
$timestamp = date('Y-m-d H:i:s');
foreach($student as $k=>$v){
$st[] = array($subject_name, $subject_code, $department_name,
$department_short_name, $teacher_name, $date, $time, $timestamp, $v,
$student_roll[$k], $status[$k]); }
$db = new PDO('mysql:host=localhost;dbname=auto_attendance', 'root',
'');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$insert = $db->prepare(
'INSERT INTO student_attendance (subject_name , subject_code,
department_name, department_short_name,
teacher_name, date, time, timestamp, student_name, student_roll,
att_status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
foreach($st as $values) {
$result = $insert->execute($values);
}
if($result == true) {
echo "<script>alert('Record successfuly
Saved.');window.location.href='../student_attendance.php?page=take-
attendance';</script>";
}
else {
echo "<script>alert('Record couldnt be
Saved.');window.location.href='../student_attendance.php?page=take-
attendance';</script>";
}
}
?>
Well your code is a bit of a mess, so I cleaned as much as I could:
1. I changed your if statement so that it is a bit more readable also I remove the else part, since you redirect if something isn't set.
2. Also put an exit(); after each header() call. To make sure the script execution is stopped.
3. Also I wrapped your database stuff into a try and catch block to catch PDOExceptions
4. I also changed the assignment of the execute() call, since you want to check if every execution was successful and not only the last one
<?php
require_once("db_const.php");
function checkPostIndex(array $indexes = [""]) {
if(empty($indexes)) return FALSE;
return array_reduce($indexes, function($result, $v){
return $result && !empty($_POST[$v]);
}, TRUE);
}
$indexes = ["subject_name", "subject_code", "department_name", "department_short_name", "teacher_name", "date", "time", "student", "stroll", "status"];
if($_SERVER["REQUEST_METHOD"] !== "POST" || $_POST['submit'] !== "save" || checkPostIndex($indexes)) {
header("Location: ../student_attendance.php?page=take-attendance");
exit();
}
$subject_name = $_POST['subject_name'];
$subject_code = $_POST['subject_code'];
$department_name = $_POST['department_name'];
$department_short_name = $_POST['department_short_name'];
$teacher_name = $_POST['teacher_name'];
$date = $_POST['date'];
$time = $_POST['time'];
$student = $_POST['student'];
$student_roll = $_POST['stroll'];
$status = $_POST['status'];
$date = DateTime::createFromFormat("j-M-Y", $date)->format("Y-m-d");
$timestamp = date("Y-m-d H:i:s");
foreach($student as $k => $v) {
$tmpOne = (!empty($student_roll[$k])?$student_roll[$k]:"");
$tmpTwo = (!empty($status[$k])?$status[$k]:"");
$st[] = [$subject_name, $subject_code, $department_name, $department_short_name, $teacher_name, $date, $time, $timestamp, $v, $tmpOne, $tmpTwo];
}
try {
$db = new PDO("mysql:host=localhost;dbname=auto_attendance", "root", "");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$insert = $db->prepare('INSERT INTO student_attendance
(subject_name , subject_code, department_name, department_short_name, teacher_name, date, time, timestamp, student_name, student_roll, att_status)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
foreach($st as $values) {
$result[] = $insert->execute($values);
}
} catch(PDOException $e) {
echo $e->getMessage();
}
?>
<script>alert('Record <?php echo (!in_array("FALSE", $result, true)?"successfuly":"couldnt be") ?> Saved.');window.location.href='../student_attendance.php?page=take-attendance';</script>
Side Notes:
Add error reporting at the top of your file(s) to get useful error messages:
<?php
ini_set("display_errors", 1);
error_reporting(E_ALL);
?>
(Turn it on only while testing, never in production!)
The problem is with the value being passed in to $_POST['status']; If you track down what is being passed in to this variable you will find it is the problem!
Related
I have found similar questions on here, but nothing quite right for my situation. I need to make multiple entries to a database from a combination of values from a set of arrays and repeated strings. To give an example:
$sql = "INSERT INTO sonch_MAIN.Concert (venue_id, date, ensemble_id, info, title, repertoire, time)
VALUES ('$venue', '$date', '1', '$info', '$title', '$repertoire_formatted', $time)";
$venue, $time, AND $date are arrays.
'1' should be added to EACH entry to the database without change.
$info, $title, AND $repertoire_formatted are strings that should be repeated, i.e., inserted without any variation, for each entry to the database.
So the following example shows what the contents of each variable might be:
$venue = array('venue1', 'venue7', 'venue50');
$date = array('2019-01-01', '2019-02-02', '2019-03-03');
$time = array('20:00:00', '19:00:00', '18:00:00');
$info = 'General info about this event';
$repertoire_formatted = 'Music that people will play at this event';
My SQL database is set up to take the different types of data for each input variable.
HERE is the code I have (not working):
session_start();
$_SESSION["servername"] = "localhost";
$_SESSION["username"] = "sonch_nB";
$_SESSION["password"] = 'hello';
$_SESSION["dbname"] = "sonch_MAIN";
date_default_timezone_set('Europe/Zurich');
$venue = ($_POST['venue']);
$date = ($_POST['date']);
$ensemble_id = '1'; //THIS WILL BE SET VIA LOGIN
$info = ($_POST['info']);
$title = ($_POST['title']);
//FORMAT INCOMING VARS CODE SKIPPED//
// Create connection
$conn = new mysqli($_SESSION['servername'], $_SESSION['username'], $_SESSION['password'], $_SESSION['dbname']);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//NEED TO LOOP INPUT TO MYSQL NUMBER OF VALUES IN ARRAY
$stmt = $conn->prepare("INSERT INTO sonch_MAIN.Concert (venue_id, date, ensemble_id, info, title, repertoire, time) VALUES (?, ?, '1', ?, ?, ?, ?)");
$stmt->bind_param("ssssss", $v, $d, $info, $title, $repertoire_formatted, $t);
for ($i = 0; $i < count($venue); $i++) {
$v = $venue[$i];
$d = $date[$i];
$t = $time[$i];
$stmt->execute();
}
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$stmt->close();
You should use a prepared statement. In MySQLi (assuming your connection is $conn):
$stmt = $conn->prepare("INSERT INTO sonch_MAIN.Concert (venue_id, date, ensemble_id, info, title, repertoire, time)
VALUES (?, ?, '1', ?, ?, ?, ?)");
$stmt->bind_param("ssssss", $v, $d, $info, $title, $repertoire_formatted, $t);
for ($i = 0; $i < count($venue); $i++) {
$v = $venue[$i];
$d = $date[$i];
$t = $time[$i];
if ($stmt->execute() === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $conn->error;
}
}
$stmt->close();
I am trying to enter data from html into MSSQL database using php. I am unable to insert record in 2 different tables and unable to insert multiple records to a table, I have the code below
<?php
$name = $_POST["name"];
$email = $_POST["email"];
$company = $_POST["company"];
$contact = (int)$_POST["contact"];
$worktitle = $_POST["worktitle"];
$industry = $_POST["industry"];
$V101 = $_POST["part2q1"];
$V102 = $_POST["part2q2"];
$V103 = $_POST["part2q3"];
$V104 = $_POST["part2q4"];
$V105 = $_POST["part2q5"];
$V106 = $_POST["part2q6"];
$V107 = $_POST["part3q1"];
$V108 = $_POST["part3q2"];
$V109 = $_POST["part3q3"];
$V110 = $_POST["part3q4"];
$V111 = $_POST["part3q5"];
$V112 = $_POST["part3q6"];
$V113 = $_POST["part4q1"];
$V114 = $_POST["part4q2"];
$V115 = $_POST["part4q3"];
$V116 = $_POST["part4q4"];
$V117 = $_POST["part4q5"];
$V118 = $_POST["part4q6"];
$V119 = $_POST["part5q1"];
$V120 = $_POST["part5q2"];
$V121 = $_POST["part5q3"];
$V122 = $_POST["part5q4"];
$V123 = $_POST["part5q5"];
$V124 = $_POST["part5q6"];
$V125 = $_POST["part6q1"];
$V126 = $_POST["part6q2"];
$V127 = $_POST["part6q3"];
$V128 = $_POST["part6q4"];
$V129 = $_POST["part6q5"];
$V130 = $_POST["part6q6"];
$V131 = $_POST["part7q1"];
$V132 = $_POST["part7q2"];
$V133 = $_POST["part7q3"];
$V134 = $_POST["part7q4"];
$V135 = $_POST["part7q5"];
$V136 = $_POST["part7q6"];
$V137 = $_POST["part7q7"];
$V138 = $_POST["part7q8"];
$V139 = $_POST["part8q1"];
$V140 = $_POST["part8q2"];
$V141 = $_POST["part8q3"];
$V142 = $_POST["part8q4"];
$V143 = $_POST["part8q5"];
$V144 = $_POST["part8q6"];
$currenttime = date("Ymd h:m:sa");
$server = "***";
$connOptions = array("Database"=>"**", "UID"=>"**", "PWD"=>"**!");
$conn = sqlsrv_connect($server, $connOptions);
if($conn){
$query="INSERT INTO dbo.profile (
name,
email,
company,
telephone,
worktitle,
industry,
createdate
)
VALUES (?, ?, ?, ?, ?, ?,getdate())";
$params = array(
$name,
$email,
$company,
$contact,
$worktitle,
$industry,
$currenttime
);
if(sqlsrv_query($conn, $query, $params)){
echo "<h4>Thank you</h4><p>You have completed the survey and your answers have been received.</p>";
} else {
echo "<p>We're sorry but there has been and error receiving your answers.</p>";
}
} else {
echo "<p>We're sorry but there has been and error receiving your answers. </p>";
}
Im trying to insert records to another table like this continuing from the previous line:
if($conn){
$query1="INSERT INTO dbo.SurveyResponse (
profileid,
Value,
CreatedOn
)
VALUES ('2', ?, ?, ?, ?, ?,getdate())";
$params=array($V101,$currenttime);
$query1="INSERT INTO dbo.SurveyResponse (
profileid,
Value,
CreatedOn
)
VALUES ('2', ?, ?, ?, ?, ?,getdate())";
$params=array($V102,$currenttime);
$query1="INSERT INTO dbo.SurveyResponse (
profileid,
Value,
CreatedOn
)
VALUES ('2', ?, ?, ?, ?, ?,getdate())";
$params=array($V103,$currenttime);
. . . . .
if(sqlsrv_query($conn, $query1, $params))
{
echo "<h4>Thank you</h4><p>You have completed the survey and your answers have been received.</p>";
} else {
echo "<p>We're sorry but there has been and error receiving your answers.</p>";
}
} else {
echo "<p>We're sorry but there has been and error receiving your answers. </p>";
}
?>
I have been trying this, insert works for first table but not the second table, can anyone help please
The following worked for me to enter multiple records to second table. Thanks to Miken32
if($conn){
$query1="INSERT INTO dbo.SurveyResponse (
profileid,
Qid,
Value,
CreatedOn
)
VALUES (?, ?, ?,getdate())";
$params1=array(2,101,$V101,$currenttime);
if(sqlsrv_query($conn, $query1, $params1))
{
echo "";
}
else { echo"<p>We're sorry but there has been and error receiving your answers.</p>" ; }
}
if($conn){
$query2="INSERT INTO dbo.SurveyResponse (
profileid,
Qid,
Value,
CreatedOn
)
VALUES (?, ?, ?,getdate())";
$params2=array(2,102,$V102,$currenttime);
if(sqlsrv_query($conn, $query2, $params2))
{
echo "";
}
else { echo"<p>We're sorry but there has been and error receiving your answers.</p>" ; }
}
So I'm working on this project here and I"m trying to do a prepared statement so I can handle any odd objects like slashes and what not as the raw data comes through. However, when I go to execute the statement it provides the same error over and over again:
SQLSTATE: 07002
code: 0
message: [Microsoft][SQL Server Native Client 11.0]COUNT field incorrect or syntax error
it says that my field count is incorrect, but I checked all the variables and made sure everything that was supposed to be there, is. So I'm just a little confused I guess. Also to note this is my first time working with the sqlsrv prepared statements, so any help would be awesome!
Here is my code below:
<?php
$serverName = "localhost";
$connectionInfo = array( "Database"=>"devel", "UID"=>"root", "PWD"=>"");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
$error_message = "";
$xml = trim(file_get_contents('/file.xml'));
$xml = new SimpleXMLElement($xml);
$truck_number;
$date_time;
$speed;
$heading;
$gps_quality;
$latitude;
$longitude;
$location;
$fix_type;
$ignition;
$gps_odometer;
$gps_rolling_odometer;
$performx_odometer;
$performx_fuel;
$performx_speed;
$performx_idle;
$packet_id;
sqlsrv_begin_transaction($conn);
$error_count = 0;
$q = "INSERT INTO eagle_devel.dbo.people_net (truck_number, date_time, speed, heading, gps_quality, latitude, longitude, location, fix_type, ignition, gps_odometer, gps_rolling_odometer,
performx_odometer, performx_fuel, performx_speed, performx_idle, packet_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$stmt = sqlsrv_prepare($conn, $q, array(&$truck_number, &$date_time, &$speed, &$heading, &$gps_quality, &$latitude, &$longitude, &$location, &$fix_type, &$ignition, &$gps_odometer, &$gps_rolling_odometer, &$performx_odometer, &$performx_fuel, &$performx_speed, &$performx_idle, &$packet_id));
foreach($xml->loc_history as $loc_history){
$truck_number = $loc_history->truck_number;
$date_time = $loc_history->datetime;
$speed = $loc_history->speed;
$heading = $loc_history->heading;
$gps_quality = $loc_history->gps_quality;
$latitude = $loc_history->latitude;
$longitude = $loc_history->longitude;
$location = $loc_history->location;
$fix_type = $loc_history->fix_type;
$ignition = $loc_history->ignition;
$gps_odometer = $loc_history->gps_odometer;
$gps_rolling_odometer = $loc_history->gps_rolling_odometer;
$performx_odometer = $loc_history->performx_odometer;
$performx_fuel = $loc_history->performx_fuel;
$performx_speed = $loc_history->performx_speed;
$performx_idle = $loc_history->performx_idle;
$packet_id = $xml->packet_id;
if(sqlsrv_execute($stmt) === false){
$error_count++;
if(($errors = sqlsrv_errors()) != null){
foreach($errors as $error){
$error_message .= "SQLSTATE: ".$error['SQLSTATE']."<br>";
$error_message .= "code: ".$error['code']."<br>";
$error_message .= "message: ".$error['message']."<br><br>";
}
}
}
}
if($error_count)
sqlsrv_rollback($conn);
else
sqlsrv_commit($conn);
print $error_message;
?>
UPDATE : I was told to try and initialize the variables before hand so I did and I get this.
SQLSTATE: IMSSP
code: -16
message: An invalid PHP type for parameter 1 was specified.
I have no idea what this means so I'm researching.
This is the query code:
if (isset($_POST['moduleAction']) && ($_POST['moduleAction'] == 'edit')) {
$date = date('Y-m-d H:i:s', time());
$stmt = $db->prepare('UPDATE todolist SET what = ?, priority = ?, added_on = ? WHERE id = ?');
$stmt->execute(array($what, $priority + 1, $date, $id));
}
My db connection:
<?php
try {
$db = new PDO('mysql:host=' . DB_HOST .';dbname=' . DB_NAME . ';charset=utf8mb4', DB_USER, DB_PASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
} catch (Exception $e) {
showDbError('connect', $e->getMessage());
}
The query is not executed on the db, on another page in the same document i am executing queries to the same db without problem. I've tried executing it without a prepared statement, double quotes, restarting te connection,... nothing works.
Anyone who can push me in the right direction?
EDIT
Setting variables:
$priorities = array('low','normal','high'); // The possible priorities of a todo
$formErrors = array(); // The encountered form errors
$id = isset($_GET['id']) ? (int) $_GET['id'] : 0; // The passed in id of the todo
$what = isset($_POST['what']) ? $_POST['what'] : ''; // The todo that was sent in via the form
$priority = isset($_POST['priority']) ? $_POST['priority'] : 'low'; // The priority that was sent in via the form
You should always check for errors, there is so many reason an query fail to work as expected.
Here is the right way to check:
if(isset($_POST['moduleAction']) && ($_POST['moduleAction'] == 'edit')) {
$date = date('Y-m-d H:i:s', time());
$query ='UPDATE todolist SET what = ?, priority = ?, added_on = ? WHERE id = ?';
if($stmt = $db->prepare($query)){
if($stmt->execute(array($what, $priority + 1, $date, $id))){
echo 'execute() successful';
if($stmt->rowCount() > 0){
echo 'Affected a row';
}else{
echo 'No row affected';
}
}else{
echo 'execute() error:';
die($dbh->errorInfo());
}
}else{
echo 'prepare() error:';
die($dbh->errorInfo());
}
}
Edit
One more thing, $priority + 1 seem a little weird.
After your update I see this line:
$priority = isset($_POST['priority']) ? $_POST['priority'] : 'low';
so you try to increment a string by 1?
Anyway what happened to traditional debugging ?
$sql_debug = "UPDATE todolist
SET what = '$what', priority = '$priority', added_on = '$date'
WHERE id = $id";
echo "**************************************<br>";
echo $sql_debug."<br>";
echo "**************************************<br>";
error_log('sql = '.$sql_debug);
Take a look at the query
And run to see what happens
I think update query is correct,please check the date time format,try this code
if (isset($_POST['moduleAction']) && ($_POST['moduleAction'] == 'edit')) {
$date=date_create("2014-10-09");
date_time_set($date,13,24,46);
$datetime =date_format($date,"Y-m-d H:i:s");
$stmt = $db->prepare('UPDATE todolist SET what = ?, priority = ?, added_on = ? WHERE id = ?');
$stmt->execute(array($what, $priority + 1, $datetime, $id));
}
If your query is not execute and you get no error I would say that something is wrong with this
if(isset($_POST['moduleAction']) && ($_POST['moduleAction'] == 'edit')) {
Make sure your moduleAction is set in your post array and is really egal to 'edit'.
Hope this helps
I am new in PDO. I heard that it is more friendly to the programmer to use multiple databases in a project and it is much more secure, so I want to learn PDO. I want to insert data into MySQL using PDO but I can't, and no error message comes. I used the following code:
<?php
class ManageUsers02 {
private $db_con;
public $db_host = "localhost"; // I run this code on my localhost
public $db_name = "todo"; // database name
public $db_user = "root"; // username
public $db_pass = ""; // password
function __construct() {
try {
// connect to database using PDO
$this->db_con = new PDO("mysql:host=$this->db_host;db_name=$this->db_name", $this->db_user, $this->db_pass);
} catch (PDOException $exc) { // PDO exception handling
echo $exc->getMessage();
}
}
public function reg_user($username, $password, $ip_address, $reg_date, $reg_time ) {
try {
// preparing sql query
$query = $this->db_con->prepare("INSERT INTO user_reg (username, password, ip_address, reg_date, reg_time) VALUES ( ?, ?, ?, ?, ? )");
}
catch( PDOException $exc ) { // PDO exception handling
echo $exc->getMessage();
}
try {
// execute sql query
$query->execute(array($username, $password, $ip_address, $reg_date, $reg_time));
}
catch( PDOException $exc ) {
echo $exc->getMessage();
}
$counts = $query->rowCount(); // return value of affected row
// here it should be return 1
echo "<br /> count :: <b> " . $counts . "</b> <br />"; // shows result 0
// no value inserted
}
}
$user_reg = new ManageUsers02();
$user_reg->reg_user('pdo_name', 'pdo_password', '127.0.0.1', '2013-2-6', '4:20 am');
?>
This fails because of insert a string to a mysql Time field.
$sql = "INSERT INTO user_reg ( ... , reg_time) VALUES (..., '4:20 am');
If you want to use '4:20 am' you should use.
TIME( STR_TO_DATE( ? , '%h:%i %p' ))
like
$sql = "INSERT INTO user_reg ( ... , reg_time) VALUES
( ?, ?, ?, ?, TIME( STR_TO_DATE( ? , '%h:%i %p' )))";
and give the class a ok and a counts .
<?php
class ManageUsers02 {
...
public $counts = 0;
public $ok = false;
function __construct() {
try {
$this->db_con = new PDO("mysql:dbname=$this->db_name;host=$this->db_host", $this->db_user, $this->db_pass);
} catch (PDOException $exc) { // PDO exception handling
echo $exc->getMessage();
return;
}
if (!$this->db_con) {
return;
}
$this->ok = true;
}
public function reg_user($username, $password, $ip_address, $reg_date, $reg_time ) {
$this->counts = 0;
$this->ok = false;
$sql = "INSERT INTO user_reg (username, password, ip_address,
reg_date, reg_time) VALUES
( ?, ?, ?, ?, TIME( STR_TO_DATE( ? , '%h:%i %p' )))";
try {
$query = $this->db_con->prepare($sql);
}
catch( PDOException $exc ) { // PDO exception handling
echo $exc->getMessage();
return;
}
if (!$query) {
return;
}
try {
$this->ok = $query->execute(array($username, $password, $ip_address, $reg_date, $reg_time));
}
catch( PDOException $exc ) {
echo $exc->getMessage();
$this->ok = false;
return;
}
if ($this->ok) {
$this->counts = $query->rowCount(); // return value of affected row
}
}
}
$user_reg = new ManageUsers02();
if ($user_reg->ok) {
$user_reg->reg_user('pdo_name4', 'pdo_password4',
'127.0.0.1', '2013-2-6', '04:20 am' );
if ($user_reg->ok) {
echo "<br /> count :: <b> " . $user_reg->counts . "</b> <br />";
} else { echo "Error : Insert failed";}
} else { echo "Error : Connection failed: ";}
?>
+1 to the answer from #moskito-x for spotting the incorrect time format. But there are a couple of other functional problems with your code.
$this->db_con = new PDO("mysql:host=$this->db_host;db_name=$this->db_name", ...
You need to use dbname in the DSN, not db_name. See http://www.php.net/manual/en/ref.pdo-mysql.connection.php
$this->db_con = new PDO("mysql:host=$this->db_host;dbname=$this->db_name", ...
Also you need to enable the error mode like this:
$this->db_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
If you don't, PDO doesn't throw exceptions on prepare() or execute(), but those functions just return false if there's an error.
I don't know what's particular problem with your insert, but your implementation is just terrible. By design.
First of all you have to get rid of PDO connection code in the class. You have to create a PDO instance separately, and then only pass it in constructor.
Secondly, you have to get rid of all these try..catch which makes your code bloated with not a slightest benefit.
Also, No class method should ever output a single byte, but return only.
So, it have to be something like
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$pdo = new PDO($dsn, $user, $pass, $opt);
class ManageUsers02
{
private $db_con;
function __construct($db_con)
{
$this->db_con = $db_con;
}
public function reg_user($username, $password, $ip_address, $reg_date, $reg_time )
{
$sql "INSERT INTO user_reg (username, password, ip_address, reg_date, reg_time)
VALUES ( ?, ?, ?, ?, ? )";
$query = $this->db_con->prepare($sql);
$query->execute(array($username, $password, $ip_address, $reg_date, $reg_time));
return $counts = $query->rowCount(); // return value of affected ro
}
}
$user_reg = new ManageUsers02($pdo);
$count = $user_reg->reg_user('pdo_name', 'pdo_password', '127.0.0.1', '2013-2-6', '4:20 am');
var_dump($count);
This setup at least will tell you if something goes wrong.