I have a registration form that use PDO to insert the data into database.
This is my html file;
https://codepen.io/anon/pen/pYOKJx
This is my insert.php file
<?php
//insert.php;
if(isset($_POST["cname"]))
{
$connect = new PDO("mysql:host=localhost;dbname=dbname", "testing", "pass");
for($count = 0; $count < count($_POST["cname"]); $count++)
{
$query = "INSERT INTO guest
(cname, sex, ic, age, nationality, phone, e_phone, address, check_in, check_out,remarks)
VALUES (:cname, :sex, :ic, :age, :nationality, :phone, :e_phone, :address, :check_in, :check_out, :remarks)
";
$statement = $connect->prepare($query);
$statement->execute(
array(
':cname' => $_POST["cname"][$count],
':sex' => $_POST["sex"][$count],
':ic' => $_POST["ic"][$count],
':age' => $_POST["age"][$count],
':nationality' => $_POST["nationality"][$count],
':phone' => $_POST["phone"][$count],
':e_phone' => $_POST["e_phone"][$count],
':address' => $_POST["address"][$count],
':check_in' => $_POST["check_in"][$count],
':check_out' => $_POST["check_out"][$count],
':remarks' => $_POST["remarks"][$count]
)
);
}
$result = $statement->fetchAll();
if(isset($result))
{
echo 'ok';
}
}
?>
I couldn't find any error in error log but when I check my database, the data was not inserted.
What should I change to make it works?
Have you tried changing :
$result = $statement->fetchAll();
if (isset($result)) {
echo 'ok';
}
to
if ($statement->fetchAll()) {
echo 'ok';
}
because it seems that your isset($result) is not executing the command.
Related
Here is a part of the code I am using to update the database.
It works, but I would like to redirect the user to another page if the database update is a success.
How can I do that ?
I know the header('Location: ../../');, but where to use it ?
$statement = $dbconnect->prepare("
UPDATE members
SET name = :fname, lastname = :lname, phone = :phone
WHERE member_id = :memberid
");
$dbconnect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$statement->execute(
array(
':fname' => "$fname",
':lname' => "$lname",
':phone' => "$phone",
':memberid' => "$memberid"
)
);
} catch(PDOException $e) {
die("ERROR: Could not connect. " . $e->getMessage());
}
Even tried the following, but no redirection
$statement->execute(array(':fname' => "$fname", ':lname' => "$lname", ':phone' => "$phone",':memberid' => "$memberid"));
if ($statement) {
header('Location: http://sitename.com');
} else {
echo 'It failed!';
}
You need to check the result from the PDOStatement::execute execution and use the correct binding when you execute a prepared statement with an array of insert values (named parameters). Note, that the result from the successful PDO::prepare call is a PDOStatement object, not a boolean value.
The folloling script, based on your code, is a possible solution to your problem:
<?php
try {
$dbconnect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$statement = $dbconnect->prepare("
UPDATE members
SET name = :fname, lastname = :lname, phone = :phone
WHERE member_id = :memberid
");
if ($statement === false) {
die("ERROR: Could not prepare statement.");
}
$result = $statement->execute(
array(
':fname' => $fname,
':lname' => $lname,
':phone' => $phone,
':memberid' => $memberid
)
);
if ($result) {
header('Location: http://sitename.com');
exit;
}
} catch(PDOException $e) {
die("ERROR: Could not connect. " . $e->getMessage());
}
?>
If you want to assume that your update was successful as long as you did not encounter any PDO errors (I assume that updates without errors are successful) you can write this:
$statement = $dbconnect->prepare("UPDATE members SET name = :fname, lastname = :lname, phone = :phone WHERE member_id = :memberid");
$dbconnect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$statement->execute(array(':fname' => "$fname", ':lname' => "$lname", ':phone' => "$phone",':memberid' => "$memberid"));
// if there were no errors redirect now
header('Location: ../../');
} catch(PDOException $e){
die("ERROR: Could not connect. " . $e->getMessage());
}
On another note outside of dev you should find a different way to handle the error: this is almost the same as not having a try/catch.
I have tables like this:
-artists
-djs
-track_artist
-track_dj
I am adding two or more artists/djs while adding song via multiple select box. But I couldn't find how to edit those rows.
Adding song function:
$sql = "INSERT INTO sarki (sarki_isim, sarki_tarz, sarki_file, sarki_resim, sarki_eklenmetarihi) VALUES (:isim, :tarz, :file, :resim, NOW())";
$sqlartist = "INSERT INTO trackartist (trackartist_artist, trackartist_track) VALUES (:artistid, :trackid)";
$sqldj = "INSERT INTO trackdj (trackdj_dj, trackdj_track) VALUES (:djid, :trackid)";
try {
$stmt = $this->db->prepare($sql);
$stmt->execute(array(':isim' => $b["isim"], ':tarz' => $b["tarz"], ':file' => $b["file"], ':resim' => $b["resim"]));
$trackid = $this->db->lastInsertId();
foreach ($b["artists"] as $artist) {
$insert = $this->db->prepare($sqlartist);
$insert->execute(array(":artistid" => $artist, ":trackid" => $trackid));
}
foreach ($b["djs"] as $artist) {
$insert = $this->db->prepare($sqldj);
$insert->execute(array(":djid" => $artist, ":trackid" => $trackid));
}
$db = null;
return $stmt;
} catch (PDOException $e) {
echo $e->getMessage();
}
I have an array like:
$arrays = array(
array('id' => '1','Name' => 'Monica','online' => '1'),
array('id' => '2','Name' => 'Jessica','online' => '1')
);
I only included 2, but let's say I have 200 of these. I already have a table in SQL with associated columns id, name and online.
Can you help me input these into database? I'm developing using wordpress. From Insert array into MySQL database with PHP I have an idea of how to do it for 1 single array
If you're having an array , you need to use a foreach loop to know the length content of insertion.
This is an example of insertion:
if(is_array($array)){
$sql = "INSERT INTO some_table (id, name, online) values ";
$valuesArr = array();
foreach($array as $row){
$id= (int) $row['id'];
$email = mysql_real_escape_string( $row['name'] );
$name = mysql_real_escape_string( $row['online'] );
$valuesArr[] = "('$id', '$email', '$name')";
}
$sql .= implode(',', $valuesArr);
mysql_query($sql) or exit(mysql_error());
}
Please try this.
Using PDO example
$sql = <<<EOT
INSERT IGNORE INTO
table_name (id, name, online)
VALUES
(:id, :name, :online)
;
EOT;
define("INSERT_UPDATE_SQL", $sql,true);
try{
$con = new PDO(CONNECTION_STRING);
if(is_array($arrays)){
$stmt = $con->prepare(INSERT_UPDATE_SQL);
$stmt->bindParam(':id', $id);
$stmt->bindParam(':name', $name);
$stmt->bindParam(':online', $online);
foreach($arrays as $row){
$id = (int)$row['id'];
$name = $row['Name'];
$online = $row['online'];
$stmt->execute();
}
$stmt = null;
}
$con = null;
}catch (PDOException $e) {
echo 'error !!';
throw $e;
}
not changed if already registered.
I'm doing a CRUD with PHP in extjs grid.
The following code works fine:
include("conect.php");
$contacts= $_POST['contacts'];
$data = json_decode($contacts);
$nome = $data->name;
$email = $data->email;
$phone = $data->phone;
$state = $data->state;
$sqlQuery = "INSERT INTO contact (name, email, phone,state) values ('%s', '%s', '%s', '%s')";
$sqlRes = $conn->query($sqlQuery);
echo json_encode(array(
"success" => mysql_errno() == 0,
"contatos" => array(
"id" => mysql_insert_id(),
"name" => $name,
"email" => $email,
"phone" => $phone,
"state" => $state
)
));
However, I intend to use prepared statements.
I made the next attempt, without success:
include("conect.php");
$statement = $conn->stmt_init();
$contacts = $_POST['contacts'];
$data = json_decode($contacts);
$name = $data->name;
$email = $data->email;
$phone = $data->phone;
$state = $data->state;
$sqlQuery = "INSERT INTO contact (name, email, phone, state, id) values (?, ?, ?, ?, ?)";
$statement = $conn->prepare($sqlQuery);
$statement->bind_param("ssssi", $name_val, $email_val, $phone_val, $state, $id_val);
$statement->execute();
$statement->bind_result($col1, $col2, $col3, $col4, $col5);
while($statement->fetch()){
$output[] = array($col1, $col2, $col3, $col4, $col5);
};
$arr = array(
'success' => mysql_errno() == 0,
"contact" => array(
"id" => mysql_insert_id(),
"name" => $name,
"email" => $email,
"phone" => $phone,
"state" => $state
)
);
$statement->close();
echo json_encode($output, $arr);
$conn->close();
What am I doing wrong?
The extjs store:
Ext.define('APP.store.StoreAPP', {
extend: 'Ext.data.Store',
model: 'APP.model.ModelAPP',
pageSize: 25,
autoLoad:true,
autoLoad: {start: 0, limit: 25},
autoSync: false,
proxy: {
type: 'ajax',
api: {
create: 'php/createContact.php',
read: 'php/Contact.php',
update: 'php/updateContact.php',
destroy: 'php/deleteContact.php',
},
reader: {
type: 'json',
// root: 'contacts', //Extjs 4
rootProperty: 'contacts', //Extjs 5
successProperty: 'success'
},
writer: {
type: 'json',
writeAllFields: true,
encode: true,
// root: 'contacts', //Extjs 4
rootProperty: 'contacts' //Extjs 5
}
}
});
Thanks in advance.
EDIT
Thanks for replying.
I've read everything I could find (internet, books) about mysqli and prepared statements.
I could not find an answer so far.
I think the problem is in json_decode and json_encode.
The following code identical to your logic works well:
include("conn.php");
$sqlQuery = "SELECT phone FROM contact WHERE name = ? AND email = ? ";
$statement = $conn->prepare($sqlQuery);
$name = "John";
$email = "email#email.com";
$statement->bind_param("s",$name, $email);
$statement->execute();
$statement->bind_result($col1, $col2);
while($statement->fetch()){
$output[] = array($col1, $col2);
};
echo json_encode($output);
$statement->close();
$conexao->close();
I think the problem is in json_decode and json_encode.
'contacts' like you say it's a array and its extjs store rootProperty config (= name of database).
The data it's provide in textfields form (name, email, phone, state).
Any idea what could be wrong?
EDIT
Next code works, but not quite what I want.
It seems to be a mixture of mysql in json decode and encode with mysqli prepared statements.
mysqli_errno() does not work in json_encode; just mysql_errno().
If you have other ideas, I will be grateful.
Thanks.
include("conect.php");
$contacts= $_POST['contacts'];
$data = json_decode($contacts);
$name = $data->name;
$email = $data->email;
$phone = $data->phone;
$state = $data->state;
$sqlQuery = "INSERT INTO contact (name, email, phone, state) values (?, ?, ?, ?)";
$statement= $conn->prepare($sqlQuery);
$statement -> bind_param ("ssss", $name_val, $email_val, $phone_val, $state_val);
$statement->execute();
echo json_encode(array(
"success" => mysql_errno() == 0,
"contatos" => array(
"name" => $name,
"email" => $email,
"phone" => $phone,
"state" => $state
)
));
From what I can see, There are a number of issues that need addressing with the above code examples.
The top block of code that you have entered would not enter correct information into the database, Your not assigning the values, just '%s'. I just ran the exact same command and got this as the row:
1, %s, %s, %s, %s
Referring to this line: $contacts = $_POST['contacts']; and the plural naming, I would presume that $contacts will contain more than one value, so the variable will be an array of values, so statements such as $name = $data->name; will not work, You would need to work with the array, maybe using a loop. Without knowing the data being provided its difficult to say.
bind_result is used to display results, but an insert statement wont return any results. If you want to see how many results are being returned use $statement->affected_rows or check the boolean result of $statement->execute for success/fail.
The code below works for me:
<?php
$mysqli = new mysqli("localhost", "test_user", "test_pass", "test_db");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$statement = $mysqli->stmt_init();
$data = new stdClass();
$data->name = "Bob";
$data->email = "bob#example.com";
$data->phone = "555-5555";
$data->state = "Some State";
// I use auto increment for the ID field.
$sqlQuery = "INSERT INTO contact (`name`, `email`, `phone`, `state`) values (?, ?, ?, ?)";
$statement = $mysqli->prepare($sqlQuery);
$statement->bind_param("ssss", $data->name, $data->email, $data->phone, $data->state);
$statement->execute();
$arr = array(
'success' => mysqli_errno($mysqli) == 0,
"contact" => array(
"id" => mysqli_insert_id($mysqli),
"name" => $data->name,
"email" => $data->email,
"phone" => $data->phone,
"state" => $data->state
)
);
$statement->close();
echo json_encode($arr);
$mysqli->close();
I would suggest having a read on the Mysqli Docs.
EDIT: To insert multiple entries into the database from an array you would need to use a loop such as this code.
$contacts = json_decode($_POST['contacts']);
foreach ($contacts as $contact) {
// I use auto increment for the ID field.
$sqlQuery = "INSERT INTO contact (`name`, `email`, `phone`, `state`) values (?, ?, ?, ?)";
$statement = $mysqli->prepare($sqlQuery);
$statement->bind_param("ssss", $contact->name, $contact->email, $contact->phone, $contact->state);
$statement->execute();
}
This should be expanded to include additional error checking / reported but it should give you working code that answers your question, giving you a good starting point. Hope it helps.
EDIT 2: This other StackOverflow post shows methods of inserting multiple rows using prepared statements
Is there a way to update two tables at the same time? I have a table food and table food_r
This is the code with which I insert into food
$rest_id = null;
if ( !empty($_GET['rest_id']))
{
$rest_id = $_REQUEST['rest_id'];
}
if ( null==$rest_id )
{
echo "null==$rest_id";
}
if(isSet($_POST['submit']))
{
// keep track post values
$food_name = $_POST['food_name'];
$food_description = $_POST['food_description'];
$food_menu = $rest_id;
$usertype = $_SESSION['usertype'];
// update data
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = $pdo->prepare("INSERT INTO food ( food_name, food_description, food_menu, usertype )
VALUES (:food_name, :food_description, :food_menu, :usertype)");
$sql->execute(array(
':food_name' => $food_name,
':food_description' => $food_description,
':food_menu' => $food_id,
':usertype' => $_SESSION['usertype']
));
Database::disconnect();
echo "Product added!";
}
Now If I want to be visible the inserted product I must insert in table food_r value of food_menu and the value of usertype.
How can I do this?
Update: It's working that way. Thank's to #JonathonWisnoski for pointing me to transactions..
$pdo->beginTransaction();
$sql = $pdo->prepare("INSERT INTO food ( food_name, food_description, food_menu, usertype )
VALUES (:food_name, :food_description, :food_menu, :usertype)");
$sql->execute(array(
':food_name' => $food_name,
':food_description' => $food_description,
':food_menu' => $rest_id,
':usertype' => $_SESSION['usertype']
));
$lastInsertID = $pdo->lastInsertId();
$sql = $pdo->prepare("INSERT INTO food_r (food_id, usertype)
VALUES (:rest_id, :usertype)");
$sql->execute(array(
':rest_id' => $lastInsertID,
':usertype' => $rest_id
));
$pdo->commit();
Update: It's working that way. Thank's to #JonathonWisnoski for pointing me to transactions..
I've also put try{}catch{} block for any errors.
try
{
$pdo->beginTransaction();
$sql = $pdo->prepare("INSERT INTO food ( food_name, food_description, food_menu, usertype )
VALUES (:food_name, :food_description, :food_menu, :usertype)");
$sql->execute(array(
':food_name' => $food_name,
':food_description' => $food_description,
':food_menu' => $rest_id,
':usertype' => $_SESSION['usertype']
));
$lastInsertID = $pdo->lastInsertId();
$sql = $pdo->prepare("INSERT INTO food_r (food_id, usertype)
VALUES (:rest_id, :usertype)");
$sql->execute(array(
':rest_id' => $lastInsertID,
':usertype' => $rest_id
));
$pdo->commit();
}
// any errors from the above database queries will be catched
catch (PDOException $e)
{
// roll back transaction
$pdo->rollback();
// log any errors to file
ExceptionErrorHandler($e);
exit;
}