How do I update mysql table using pdo and multiple arrays? - php

I've got a list of form fields in an html table. This page is designed to allow someone to modify multiple records at once...using an update query. Because I have multiple customer records present, I need to update based on the record Id. I thought that I was supposed to create a composite array then update the database by pointing to the various key, value pairs, but nothing seems to work...all help is appreciated..hoping its a small typo I'm not catching:
....SQL to pull data (works)...
echo "<form action='#' method='POST' >";
echo "<center><table>";
echo "<tr><th> Email Address </th> <th>Created On</th><th> Ip Address</th><th> Front of Card</th><th> Back of Card</th><th> Last 4 of Card</th><th> Decision</th><th> Notes (for Reject)</th>";
foreach ($customer as $row){
echo '<tr><input type="hidden" name="record[]" value='.$row[' id '].'/>
<td>'.$row["email"].' </td>
<td>'.$row["created_on"].'</td>
<td>'.$row["ip_address"].'</td>
<td>
<img class="fixed" src="imgReader.php?img='.$row[" card_front "].'"/>
</td>
<td>
<img class="fixed" src="imgReader.php?img='.$row[" card_back "].'"/>
</td>
<td><input type="number" name="last4[]" value="" /></td>
<td><select name="decision[]">
<option value="PENDING">Pending</option>
<option value="APPROVED">Approved</option>
<option value="DENIED">Denied</option>
<option value="DUPLICATE">Duplicate</option></select></td>
<td><input type="textarea" rows="5" name="notes[]" value="" /></td>
</tr>';
if ($_POST){
$last4 = $_POST["last4"];
$status = $_POST["decision"];
$notes = $_POST["notes"];
$ids = $_POST["record"];
$tableSet = array('last4' => $last4,
'decision' => $status,
'notes' => $notes,
'ids' => str_replace('/','', $ids)
);
var_dump($tableSet);
foreach( $tableSet as $i) {
$updateUserData = $db->prepare("UPDATE cards SET `last_4_cc` = :l4cc, `status` = :status, `notes` = :notes WHERE `id` = :record");
$updateUserData->execute([
':l4cc' => $i[$tableSet["last4"]],
':status' => $i[$tableSet["decision"]],
':notes' => $i[$tableSet["notes"]],
':record' => $i[$tableSet["ids"]]
]);
}
}
?>

Related

Show results from certain record

I have searched for this and keep getting errors no matter what I try.
The main error I get is:
mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, string given
I have created a page showing all records. The user then selects one record to edit and the id is passed on to this page which would show all the fields in a form/table. a few of the fields are readonly so can not be modified.
What I am trying to achieve is to show the results in a table so that they can be edited and then sent to the database and updated. I was thinking of sending it to another file to update and then send them back to view the results page.
<form action = 'modify2.php' method = 'post'>
<table border="1">
<tr style="border-bottom:1px solid #000000;">
<strong>User ID</strong>
<strong>Username</strong>
<strong>Password</strong>
<strong>Email</strong>
<strong>Name</strong>
<strong>Submitted By</strong>
<strong>Memeber Since</strong>
</tr>
<?PHP
//error check to see what results are obtained
echo '<br />sql code = '.$sql.'<br/>'; // this works bot the $result
shows nothing
//die();
//fetch object array and put into a row
//while($row = mysqli_fetch_assoc($result))
while($row = mysqli_fetch_assoc($sql))
{
?>
<tr><td><label>User ID :</label></td>
<td><input type = 'text' name = 'id' id = 'id' value='<?PHP echo $row["id"];?>' readonly/></input><br /></td></tr>
<tr><td><strong>Username</strong></td>
<td><input type = 'text' name = 'username' id = 'username' value='<?PHP echo $row["username"];?>'/></input><br /></td></tr>
<tr><td><label>password :</label></td>
<td><input type = 'text' name = 'password' id = 'password' value='<?PHP echo $row["password"];?>'/></input><br /></td></tr>
<tr><td><label>email :</label></td>
<td><input type = 'text' name = 'email' id = 'email' value='<?PHP echo $row["email"];?>'/></input><br /></td></tr>
<tr><td><label>Real Name :</label></td>
<td><input type = 'text' name = 'Name' id = 'Name' value='<?PHP echo $row["Name"];?>'/></input><br /></td></tr>
<tr><td><label>submitted by :</label></td>
<td><input type = 'text' name = 'submittedby' id = 'submittedby' value='<?PHP echo $row["submittedby"];?>' readonly/></input><br /></td></tr>
<tr><td><label>trn_date :</label></td>
<td><input type = 'text' name = 'trn_date' id = 'trn_date' value='<?PHP echo $row["trn_date"];?>' readonly/></input></td></tr>
<?PHP
}
//close table here
?>
<tr><td colspan='2'><div align='center'><input type = 'submit' value ='Modify Record' name = 'submit'/></td></tr>
</form></div>
</table>
You need to put $result=mysqli_query($con,$sql); first to you can use
// Associative array
$row=mysqli_fetch_assoc($result);

display data from database of an HTML form

I am trying to display results from my database using PHP through an HTML form. Once the user clicks the submit button, based on what they enter in each field, results should be shown accordingly.
E.g. if I click on "Rooms" in my drop down menu, and when I specify a certain price in the text field for price and for the rest of the fields, anything related to what I searched should be displayed.
I was able to do it for the drop down menu, but I don't know how I can enter multiple values and when I click submit it generates the data accordingly.
Here's what I've done so far:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action="dropdown2.php" method="POST">
<select name="testing" type="text">
<option value="Choose">Choose type of stay</option>
<option value="Flat">Flat</option>
<option value="Room">Room</option>
<option value="Apartment">Apartment</option>
<option value="Villa">Villa</option>
</select>
<p></p>
<table>
<tr>
<td width="14%" class="label">Minimum Price MYR</td>
<td width="42%"><input type="text" name="textfield4" id="textfield4" class="text" /></td>
<td class="label">Maximum Price MYR</td>
<td><input type="text" name="textfield2" id="textfield2" class="text" /></td>
</tr>
<tr>
<td class="label">Bed Rooms</td>
<td>
<label>
<input type="text" name="search" id="textfield5" class="text smalltextarea" />
</label>
</td>
<td class="label">Bathrooms</td>
<td><input type="text" name="textfield3" id="textfield3" class="text" /></td>
</tr>
</table>
<p></p>
<input type="submit" value="Submit" name="submit">
</form>
<?php
mysql_connect("localhost", "root", "") or die("Error connecting to database: ".mysql_error());
mysql_select_db("test") or die(mysql_error());
if(isset($_POST['testing'])){
$query = $_POST['testing'];
$min_length = 3;
if(strlen($query) >= $min_length){
$query = htmlspecialchars($query);
$query = mysql_real_escape_string($query);
$raw_results = mysql_query("SELECT * FROM rooms
WHERE (`name` LIKE '%".$query."%') OR (`price` LIKE '%".$query."%') OR (`description` LIKE '%".$query."%')") or die(mysql_error());
if(mysql_num_rows($raw_results) > 0){
while($results = mysql_fetch_array($raw_results)){
echo "<p><h3>".$results['name']."</h3>"."RM " .$results['price']."</p>"."<p>".$results['description']."</p>";
}
}
else{
echo "No results";
}
}
else{
echo "Minimum length is ".$min_length;
}
}
?>
</body>
</html>
I'm new to PHP and MySQL... any help is appreciated!
first id say change the names to something a bit more reconcilable
also you are missing a name or description field not sure which one (since the names don't resemble the database fields)
replace mysql for pdo or mysqli i used pdo in this example
since if you upgrade to php 7 mysql functions are removed (like suggested in the comments above)
instead of the mysql real escape etc you can use a prepared statement
also what you were missing in the query were the other post fields like suggested in the comments for example how many bathrooms, the minprice, the maxprice etc (these fields are posted by the user but not used in the query)
you were using the same postfield for all of those values in your query
now based on your fields i am assuming for example if someone fills in minprice = 12 and descr = flat that the result both has to have a minimum price of 12 and a description like flat so you need to change the OR's you used in your query for AND's based on which field are filled in
here is a bit of an example on how to go about it:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action="" method="POST">
<select name="description" type="text">
<option value="Choose">Choose type of stay</option>
<option value="Flat">Flat</option>
<option value="Room">Room</option>
<option value="Apartment">Apartment</option>
<option value="Villa">Villa</option>
</select>
<p></p>
<table>
<tr>
<td width="14%" class="label">Minimum Price MYR</td>
<td width="42%"><input type="text" name="minprice" id="textfield4" class="text" /></td>
<td class="label">Maximum Price MYR</td>
<td><input type="text" name="maxprice" id="textfield2" class="text" /></td>
</tr>
<tr>
<td class="label">Bed Rooms</td>
<td>
<label>
<input type="text" name="bedrooms" id="textfield5" class="text smalltextarea" />
</label>
</td>
<td class="label">Bathrooms</td>
<td><input type="text" name="bathrooms" id="textfield3" class="text" /></td>
</tr>
</table>
<p></p>
<input type="submit" value="Submit" name="submit">
</form>
<?php
$minDescriptionLength = 3;
if(isset($_POST['description'])) {
$descr = $_POST['description'];
if(strlen($descr) >= $minDescriptionLength) {
$connectionConfigArr = array('host' => 'localhost', 'dbname' => 'test', 'user' => 'root', 'password' => '');
// here we are making the database connection,
// first param = connection string, second param = user, third param = password
$dbh = new PDO(
'mysql:host=' . $connectionConfigArr['host'] . ';dbname=' . $connectionConfigArr['dbname'],
$connectionConfigArr['user'],
$connectionConfigArr['password']
);
$bindParamArr = array();
//since we check this one in the start i assumed it's required so we can use it in the base for the query
$query = 'SELECT * FROM rooms WHERE `description` LIKE :descr ';
//here for each extra field that is filled in we basicaly are going to add it to the query string
//and we push the value to the bindParamArray which will after we added the query add the values safely to the query
if(isset($_POST['minprice']) && $_POST['minprice']) {
$query .= 'AND `price` > :minprice ';
array_push($bindParamArr, array('field' => ':minprice', 'value' => $_POST['minprice'], 'type' => PDO::PARAM_INT));
}
if(isset($_POST['maxprice']) && $_POST['maxprice']) {
$query .= 'AND `price` < :maxprice ';
array_push($bindParamArr, array('field' => ':maxprice', 'value' => $_POST['maxprice'], 'type' => PDO::PARAM_INT));
}
if(isset($_POST['bathrooms']) && $_POST['bathrooms']) {
$query .= 'AND `bathrooms` = :bathrooms ';
array_push($bindParamArr, array('field' => ':bathrooms', 'value' => $_POST['bathrooms'], 'type' => PDO::PARAM_INT));
}
if(isset($_POST['bedrooms']) && $_POST['bedrooms']) {
$query .= 'AND `bedrooms` = :bedrooms ';
array_push($bindParamArr, array('field' => ':bedrooms', 'value' => $_POST['bedrooms'], 'type' => PDO::PARAM_INT));
}
//we still need to push the description to the array
array_push($bindParamArr, array('field' => ':descr', 'value' => '%' . $descr . '%', 'type' => PDO::PARAM_STR));
//here we prepare the query
$stmt = $dbh->prepare($query);
//here we bind the params safely
foreach($bindParamArr as $bParam) {
$stmt->bindParam($bParam['field'], $bParam['value'], $bParam['type']);
}
$stmt->execute();
//use this to get the amount of rows the query returned
$rowCount = $stmt->rowCount();
if($rowCount > 0) {
//we loop through the stmt fetch function which will iterate through the resultset
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "<p><h3>".$row['name']."</h3>"."RM " .$row['price']."</p>"."<p>".$row['description']."</p>";
}
}
else {
echo "No results";
}
}
else {
echo "Minimum length is ".$minDescriptionLength;
}
}
?>
</body>
</html>

how to display the date of birth from a database to a form and update it in php & PDO?

I have three pages where i want to update an existing row of a specific user by their unique id.But when i click to the update link it shows all the field with their values except the date of birth. I am trying to find out the problem. but failed as i am quite new to php. any one please help if you can.
Here is my HTML form
<form action="update.php" method="post">
<table>
<?php
include_once ("../vendor/autoload.php");
use Admission\Admission\Admission;
$object_for_showDetails = new Admission();
$object_for_showDetails->setData($_GET);
$data = $object_for_showDetails->details();
$values = $data;
?>
<th align="center" colspan="2"> <h3>Applicant's Information</h3></th>
<tr>
<td>Name of Applicant:<spam>*</spam></td>
<td><input class="nice" type="text" name="name" value="<?php echo $values['student_name']?>"></td>
<td><input type="hidden" name="id" value="<?php echo $values['uid']?>"></td>
</tr>
<tr>
<td>Email:<spam>*</spam></td>
<td><input class="nice" type="email" name="email" value="<?php echo $values['email']?>"></td>
</tr>
<tr>
<td> Gender:<spam>*</spam></td>
<td> <input type="radio" class="radio" value="male" name="gender" <?php echo ($values['gender']=='male')?'checked':'';?> />Male
<input type="radio" class="radio" value="female" name="gender" <?php echo ($values['gender']=='female')?'checked':'';?> /> Female </td>
</tr>
<tr>
<td> Birth Date:<spam>*</spam></td>
<td> <input class="nice" type="date" name="<?php echo $values['birth_date']?>" > </td>
</tr>
<tr>
<td> Religion:<spam>*</spam></td>
<td> <input class="nice" type="text" name="religion" value="<?php echo $values['religion']?>"></td>
</tr>
<tr>
<td> Phone:<spam>*</spam></td>
<td> <input class="nice" type="text" name="phone" value="<?php echo $values['phone']?>"></td>
</tr>
<th align="center" colspan="2"> <h3>Parent's information</h3></th>
<tr>
<td> Father Name::<spam>*</spam></td>
<td> <input class="nice" type="text" name="father_name" value="<?php echo $values['father_name']?>"></td>
</tr>
<tr>
<td> Mother Name::<spam>*</spam></td>
<td> <input class="nice" type="text" name="mother_name" value="<?php echo $values['mother_name']?>"></td>
</tr>
<tr>
<td> Guardian/Parent's Phone:<spam>*</spam></td>
<td> <input class="nice" type="text" name="guardian_phone" value="<?php echo $values['guardian_phone']?>"></td>
</tr>
<td>
Details|
Update Info|
Delete
</td>
<tr>
<td colspan="2" align="center"><input type="submit" value="update" class="btn"></td>
</tr>
</table>
</form>
Here is my update.php file
<?php
include_once ("../vendor/autoload.php");
use Admission\Admission\Admission;
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$object_of_update = new Admission();
$object_of_update->setData($_POST);
$object_of_update->update();
}
else{
header("location:create.php");
}
?>
and last the update methode under the main class file Admission.php
where setData() is for set the values and details() is for showing the data which fetch data from the database of a specific user and the update() method for updating the values from the database.
public function store()
{
try {
$pdo = new PDO ('mysql:host=localhost;dbname=university', 'root', '');
$query_for_insert = "INSERT INTO `student_form`(`id`, `uid`, `student_name`, `email`, `birth_date`, `gender`, `religion`, `phone`, `father_name`, `mother_name`, `guardian_phone`)
VALUES (:id,:uid,:student_name,:email,:birth_date,:gender,:religion,:phone,:father_name,:mother_name,:guardian_phone)";
$statement = $pdo->prepare($query_for_insert);
$statement->execute(array(
':id' => null,
':uid' => uniqid(),
':student_name' => $this->name,
':email' => $this->email,
':birth_date' => $this->birth_date,
':gender' => $this->gender,
':religion' => $this->religion,
':phone' => $this->phone,
':father_name' => $this->father_name,
':mother_name' => $this->mother_name,
':guardian_phone' => $this->guardian_phone,
));
if ($statement) {
session_start();
$_SESSION['message'] = "You have successfully Applied to the University Of Dhaka.Please Bring your Admit card during Admission test";
header("location:register.php");
}
} catch (PDOException $e) {
echo "Connection Error" . $e->getMessage();
}
}
public function update(){
echo "update method";
try {
$pdo = new PDO ('mysql:host=localhost;dbname=university', 'root', '');
$queryForUpdata = "UPDATE `student_form` SET `student_name`=:student_name,`email`= :email,`birth_date` =:birth_date,`gender`=:gender,`religion`=:religion,`phone`=:phone,`father_name`=:father_name,`mother_name`=:mother_name,`guardian_phone`=:guardian_phone WHERE uid="."'".$this->id."'";
$statement = $pdo->prepare($queryForUpdata);
$statement->execute(array(
':student_name' => $this->name,
':email' => $this->email,
':birth_date' => $this->birth_date,
':gender' => $this->gender,
':religion' => $this->religion,
':phone' => $this->phone,
':father_name' => $this->father_name,
':mother_name' => $this->mother_name,
':guardian_phone' => $this->guardian_phone
));
if ($statement) {
session_start();
$_SESSION['message'] = "You have successfully Updated Your Information";
header('location:register.php');
}
}
catch (PDOException $e) {
echo "Connection Error" . $e->getMessage();
}
}
Please if anyone can fix this out i will be grateful to you.
It looks like you are not setting "value" tag on "Birth date" input so when your record updates and page refreshes you are missing its value.
Also, your input name is birth_data while in php you are trying to access birth_date
<input class="nice" type="date" name="birth_date" value="<?php echo is_object($values["birth_date"]) ? $values["birth_date"]->format("Y-m-d") : $values["birth_date"]?>">

Copy database contents from one table to another table in codeigniter

I need to copy table contents from table: user_openletter to table: country on clicking archive button. How to write a query to copy from,to,title,openletter,open_id from user_openletter to another table country. This a codeigniter app.
my controller code is :
public function store_user_data_archieve()
{
$match = $this->input->post('submit');
echo $match;
if($match == "Archieve")
{
$data = array(
'open_id' => $this->input->post('open_id'),
'featured' => '1',
'from' => $this->input->post('from'),
'to' => $this->input->post('to'),
'title' => $this->input->post('title'),
'archieve' => '1',
'latest' => '0',
'sponsor' => 'images/sponsor.png'
);
$this->load->database();
//load the model
$this->load->model('select');
//load the method of model
$data['r']=$this->select->store_user_data_archieve($data);
echo "success";
}
else if(!$match == "new")
{
$data = array(
'open_id' => $this->input->post('open_id'),
'featured' => '1',
'from' => $this->input->post('from'),
'to' => $this->input->post('to'),
'title' => $this->input->post('title'),
'openletter' => $this->input->post('openletter'),
'archieve' => '0',
'latest' => '1',
'sponsor' => 'images/sponsor.png'
);
$this->load->database();
//load the model
$this->load->model('select');
//load the method of model
$data['r']=$this->select->store_user_data_archieve($data);
echo "success";
}
else if(!$match == "Discard")
{
echo "failure";
}
}
My view code is:
<?php
foreach ($r->result() as $row)
{
?>
<table border="1" cellpadding="4" cellspacing="0">
<tr>
<td>from</td>
<td>to</td>
<td>title</td>
<td>openletter</td>
<td>Date & Time</td>
<td>open_id</td>
</tr>
<tr>
<form action="/index.php/welcome/store_user_data_archieve" method="post">
<td><input type="text" name="from" value="<?php echo $row->from;?>" /></td>
<td><input type="text" name="to" value="<?php echo $row->to;?>" /></td>
<td><input type="text" name="title" value="<?php echo $row->title;?>" /></td>
<td><input type="text" name="openletter" value="<?php echo $row->openletter;?>" /></td>
<td><input type="text" name="datetime" value="<?php echo $row->datetime;?>" /></td>
<td><input type="text" name="open_id" value="<?php echo $row->open_id;?>" /></td>
<td><div><input type="submit" name="submit" value="Archieve" /></div></td>
<td><div><input type="submit" name="new" value="new" /></div></td>
</form>
</tr>
</table>
<?php } ?>
My model code is:
public function store_user_data_archieve($data)
{
//data is retrieved from this query
$this->db->insert('country', $data);
$this->db->set('openletter');
$this->db->select('openletter');
$this->db->where('open_id', $data[open_id]);
$this->db->from('user_openletter');
// Produces: INSERT INTO mytable (title, name, date) VALUES ('{$title}', '{$name}', '{$date}')
}
As per our discussion you need to copy from,to,title,openletter,open_id from table user_openletter to country table
$this->db->select('from,to,title,openletter,open_id');// select your filed
$q = $this->db->get('user_openletter')->result(); // get result from table
foreach ($q as $r) { // loop over results
$this->db->insert('country', $r); // insert each row to country table
}
$this->db->select('from, to, title,openletter, open_id');
$result_set = $this->db->get('user_openletter')->result();
if(count($result_set) > 0) {
$this->db->insert_batch('country', $result_set);
}

php save data into two rows at a time in database?

I have a form like this
<form class="product-data" action="">
<table>
<tr class="data-row">
<td>
<input type="number" name="finance[a][source_unit]" >
</td>
<td >
<input type="number" name="finance[a][target_unit]">
</td>
<td>
<input type="number" name="finance[a][client_price]">
</td>
<td>
<input type="number" name="finance[a][client_salary]" >
</td>
</tr>
<tr class="data-row">
<td>
<input type="number" name="finance[b][source_unit]" >
</td>
<td >
<input type="number" name="finance[b][target_unit]">
</td>
<td>
<input type="number" name="finance[b][client_price]">
</td>
<td>
<input type="number" name="finance[b][client_salary]" >
</td>
</tr>
</table>
</form>
here you can see I have two rows. One for a and another for b. Now I want to save them in the database with two rows. One for the a and another for b at a same time. When I am doing print_r(finance). with this code
$finances = $_POST['finance'];
print_r($finances);
Its showing me an array like this
Array
(
[a] => Array
(
[source_unit] => 3213
[target_unit] => 657654322343
[client_price] => 5435.00
[client_salary] => 897.00
)
[a] => Array
(
[source_units] => 67656565
[target_units] => 43243
[client_price] => 23432.00
[client_salary] => 6546.00
)
)
Now can someone tell me how to save them in each row. I have my database table is like this and the data should be saved like this
Id, product_type, source_unit, target_unit, client_price, lient_salary
1 A 3213 657654322343 5435 897
2 B 67656565 43243 23432 6546
I have two solutions for you. Once that is tailored for this scenario only:
$f = $_POST['finance'];
// insert first row
$query = "INSERT INTO `table` VALUES (NULL, 'A', {$f['a']['source_unit']}, {$f['a']['target_units']}, {$f['a']['client_price']}, {$f['a']['client_salary']})";
mysql_query($query);
// insert second row
$query = "INSERT INTO `table` VALUES (NULL, 'B', {$f['b']['source_unit']}, {$f['b']['target_units']}, {$f['b']['client_price']}, {$f['b']['client_salary']})";
mysql_query($query);
or if you have it more universal (for multiple rows):
$f = $_POST['finance'];
foreach($f as $key => $item) {
// assign key of the letter as value to insert
$letter = strtoupper($key);
// insert a row
$query = "INSERT INTO `table` VALUES (NULL, '{$letter}', {$item['source_unit']}, {$item['target_units']}, {$item['client_price']}, {$item['client_salary']})";
mysql_query($query);
}
loop thru your array and either insert or update accordingly.
foreach($finances as $key => $data)
{
//based on the $key if value exists in database update else insert
echo $key.'<br />';
echo $data['source_unit'].'<br />';
echo $data['target_unit'].'<br />';
echo '<hr />';
}

Categories