Data looping and inserting in to Database? - php

I have an array of two rows i need to satisfy two condition and based on that condition i should insert the value into the database.
Am getting the values using this query and am comparing $record['QTY'] & $record['FILLED'],the condition should be satisfied by each row in the database and when the condition satisfies it should be inserted or not inserted
In this case how can check for each row and satisfy the condition
How do i check the loop?
<?php
// Include confi.php
include_once('config.php');
if($_SERVER['REQUEST_METHOD'] == "POST"){
// Get data
$employee_id = isset($_POST['EMPLOYEE_ID']) ? mysql_real_escape_string($_POST['EMPLOYEE_ID']) : "";
$mobile = isset($_POST['DRMOBILE']) ? mysql_real_escape_string($_POST['DRMOBILE']) : "";
$qty = isset($_POST['QTY']) ? mysql_real_escape_string($_POST['QTY']) : "";
$createdon = isset($_POST['CREATEDON']) ? mysql_real_escape_string($_POST['CREATEDON']) : "";
$status = isset($_POST['STATUS']) ? mysql_real_escape_string($_POST['STATUS']) : "";
$select="SELECT IFNULL(A.QTY,0)QTY,IFNULL(SUM(B.FILLED),0)FILLED,A.PHY_ID
FROM PHYSAMPLE A
LEFT JOIN FILLEDQTYS B ON A.DRMOBILE=B.DRMOBILE AND A.EMPLOYEE_ID=B.EMPLOYEE_ID AND A.PHY_ID=B.PHY_ID
WHERE A.DRMOBILE='$mobile' GROUP BY B.PHY_ID";
$query=mysql_query($select);
while($record=mysql_fetch_assoc($query)){
// print_r($record);
if($record['QTY'] < 0.7*($record['FILLED']) )
{
$json = array("status" => 2,"msg" => "Error In adding Data");
}else{
echo $sample="INSERT INTO `PHYSAMPLE` (EMPLOYEE_ID,DRMOBILE,QTY,CREATEDON)
VALUES('$employee_id','$mobile','$qty','$createdon')";
$qry=mysql_query($sample);
}
}
}else{
$json = array("status" => 0, "msg" => "Request method not accepted");
}
#mysql_close($conn);
/* Output header */
header('Content-type: application/json');
echo json_encode($json);
?>
Sample array
Array
(
[QTY] => 30
[FILLED] => 27
[PHY_ID] => 1
)
Array
(
[QTY] => 20
[FILLED] => 24
[PHY_ID] => 2
)

Related

Inserting array of data in database

I have two arrays of values:
First array contain user id's:
Array ([0]=>1 [1]=>2 [2]=>3 [3]=>4 [4]=>5 [5]=>6)
Second array contain attendance status:
Array([0]=>Present [1]=>Absent [2]=>Absent [3]=>Present [4]=>Absent [5]=>Present)
I want to insert these values in the database in separate rows like this:
U_id Status
1 Present
2 Absent
3 Absent
4 Present
5 Absent
6 Present
Currently, I am using this code to insert values in database.
My Controller Code:
public function usr_att(){
if(isset($_POST['submit'])){
$uid = $_POST['uid'];
$status= $_POST['stat'];
$id = implode("," , $uid );
$status = implode("," , $status );
$data = array (
'u_id' => $id,
'status' => $status
);
$this->db->insert('attendence' , $data);
redirect("usr/usr_list", "refresh");
}
}
But this code inserts data like this:
U_id Status
1 Present,Absent,Absent,Present,Absent,Present
How can I insert these values in separate rows using CodeIgniter?
Simply you can do like this
public function usr_att()
{
if(isset($_POST['submit']))
{
$uid = $_POST['uid'];
$status = $_POST['stat'];
foreach ($uid as $key => $item)
{
$data = array (
'u_id' => $item,
'status' => $status[$key]
);
$this->db->insert('attendence' , $data);
}
redirect("usr/usr_list", "refresh");
}
}
For your intended purpose, once you have the values for $uid and $stat in an array, then you could do this:
<?php
// You have your u_id values in an array
$uid = array('1','2','3','4','5','6');
// You have your status values in an array
$stat = array('Present', 'Absent', 'Absent', 'Present', 'Absent', 'Present');
// As long as the number of u_id values and status values are the same
if( count($uid) == count($stat) )
{
// Use the count of uid values and loop through
for( $x = 0; $x <= count($uid) -1; $x++ )
{
// Entering each on in the database
$this->db->insert('attendence', array(
'u_id' => $uid[$x],
'status' => $stat[$x]
));
}
}

throwing Uninitialized string offset error in php array codeigniter

$month = $this->input->post('get_month');
//echo $month; exit();
// get the employee salary [result_array()];
$insert_salary = $this->payscale_model->get_salary();
// print_r($insert_salary[0]['salary_amount']); exit();// correct value displayed
//print_r($insert_salary); exit(); displayed the array correctly
for ($i=0; $i < count($insert_salary) ; $i++) {
$payscale[$i] = array(
'employee_id' => $insert_salary[0]['employee_id'][$i],
'payscale_amount' => $insert_salary[0]['salary_amount'][$i],
'payscale_date' => $month,
'payscale_total' => $insert_salary[0]['salary_amount'][$i],
);
}
echo "value is:";
print_r($payscale); exit();
$insert_payscale = $this->payscale_model->set_payscale($payscale);
i'm getting the employee salary details from salary table and insert to payscale table with current month details. I successfully retrieved the salary details and now i want insert to payscale table using for loop and insert_batch using codeigniter. but php throwing the error Uninitialized string offset.
$month = $this->input->post('get_month');
//echo $month; exit();
// get the employee salary [result_array()];
$insert_salary = $this->payscale_model->get_salary();
// print_r($insert_salary[0]['salary_amount']); exit();// correcte value displayed
//print_r($insert_salary); exit(); displayed the array correctly
if(count($insert_salary)>0)
foreach ($insert_salary as $ins) {
$payscale[] = array(
'employee_id' => $ins[0]['employee_id'],
'payscale_amount' => $ins[0]['salary_amount'],
'payscale_total' => $ins[0]['salary_amount'],
);
}
or
if(count($insert_salary)>0)
foreach ($insert_salary as $ins) {
$payscale[] = array(
'employee_id' => $ins['employee_id'],
'payscale_amount' => $ins['salary_amount'],
'payscale_total' => $ins['salary_amount'],
);
}

drop down value not being submitted to post array

Currently working with a php project in which I connect to a database in phpmyadmin. I'm currently implementing my one to many relationship and on one of my forms there is a drop down list with the list of categorys(foreign key) that a product in my database can have, however when I check the post array, and the array that contains all the values for the insert query everything is there except the foreign key.
Drop down list and array of values:
<select name="Category_ID">
<?php
foreach ($category as $cat) {
echo '<option value="' . $cat['ID'] . '">' . $cat['ID'] . '</option>';
}
?>
</select>
Array (
[authorName] => Hiroshi Sakurazaka
[bookName] => All You Need Is Kill
[costPrice] => 59
[sellPrice] => 99
[productCatID] => )
Could not insert book
Heres the file that converts the data in the formdata array into an object:
<?php
require_once 'product.php'; //Connecting to the product class
require_once 'Classes/productTable.php'; //Connecting to the TableGateway
require_once 'Classes/Connection.php'; //Connecting to the Connection class
require_once 'validateProduct.php';//Connecting to the product validation
require_once 'utils/functions.php';
//start_session();
//
//if (!is_logged_in()) {
// header("Location: login_form.php");
//}
echo '<pre>';
print_r($_POST);
echo '</pre>';
$formdata = array();
$errors = array();
validate($formdata, $errors);
if (empty($errors)) {
$AuthorName = $formdata['AuthorName'];
$BookName = $formdata['BookName'];
$costPrice = $formdata['CostPrice'];
$sellPrice = $formdata['sellPrice'];
$productCatID = $formdata['productCatID'];
echo '<pre>';
print_r($formdata);
echo 'Form Data array';
echo '</pre>';
$connection = Connection::getInstance();
$gateway = new productTable($connection);
$id = $gateway->insert($AuthorName, $BookName, $costPrice, $sellPrice, $productCatID);
header('Location: viewProducts.php');
}
else {
require 'createProductForm.php';
}
Heres the function in the table gateway that inserts the object into the database:
> public function insert($authorName, $bookName, $costPrice, $sellPrice,
> $productCatID) {
> $sql = "INSERT INTO "
> . "`product`(`AuthorName`, `BookName`, `CostPrice`, `sellPrice`, `productCatID`)"
> . " VALUES (:authorName,:bookName,:costPrice,:sellPrice,:productCatID)";
> $statement = $this->connection->prepare($sql);
> $params = array(
> "authorName" => $authorName,
> "bookName" => $bookName,
> "costPrice" => $costPrice,
> "sellPrice" => $sellPrice,
> "productCatID" => $productCatID
> );
> print_r($params);
> $status = $statement->execute($params);
>
> if (!$status) {
> die("Could not insert book");
> }
>
> $id = $this->connection->lastInsertId();
>
> return $id; }
can somebody please tell me what I'm missing?
Your select has the name of Category_ID not productCatID. If you expecting GET/POST data coming in under productCatID you need to name your select productCatID.
Solved my problem finally, so I'll post how I did it. For debuging my code and to see what values were being passed into the $POST array and the $formdata array, I used print_r to post each array if there was a problem and heres what I got:
$POST Array
(
[AuthorName] => g
[BookName] => g
[CostPrice] => 33
[sellPrice] => 3
[productCatID] => 4
[createProduct] => Create Product
)
form data array
(
[AuthorName] => g
[BookName] => g
[CostPrice] => 33
[sellPrice] => 3
[ProductCatID] =>
)
As you can see the $POST array was getting the value from the drop down list just fine, it was the form data array that was the issue. Embarrassingly the issue was just a simple typo error that was quickly resolved in my validation script.
With foreach you have to explicitly request access to the key, so if you don't, you'll only get the array values.
Just do this to debug (outside of the <select>):
foreach($category as $key=>$cat){
var_dump($cat['ID'], $cat, $key);
}
And I think you'll see where the actual data you need is.
(also, you seem to be running without strict errors and notices on, which is crucial for debugging and might show you some notices when array keys you try to access don't exist)

Simplify php validation of array from form-input

I'm creating a page where you can save your predictions for soccermatches.
Every week there are 9 matches and a user can post his prediction for a match via a form.
The result of this form will result in the following array:
Array
(
[week] => 12
[game_id_1] => 28
[game_1_home] => 2
[game_1_away] => 2
[game_id_2] => 29
[game_2_home] => 2
[game_2_away] => 1
[game_id_3] => 31
[game_3_home] => 4
[game_3_away] => 0
[game_id_4] => 30
[game_4_home] => 2
[game_4_away] => 0
[game_id_5] => 32
[game_5_home] => 0
[game_5_away] => 2
[game_id_6] => 33
[game_6_home] => 1
[game_6_away] => 0
[game_id_7] => 35
[game_7_home] => 1
[game_7_away] => 1
[game_id_8] => 34
[game_8_home] => 2
[game_8_away] => 4
[game_id_9] => 36
[game_9_home] => 3
[game_9_away] => 0
)
I already wrote a validation part for the first match but instead of copying this 8 times I think this can go much easier.
Anyone an idea how to do this and please give me advice if I can improve this piece of code.
$blnOK = true;
$strResult = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (isset($_POST['game_id_1']) && !empty($_POST['game_1_home']) && !empty($_POST['game_1_away']))
//check if the posts are not empty, then put in variables
{
$strGame_id_1 = $_POST['game_id_1'];
$strGame_1_home = $_POST['game_1_home'];
$strGame_1_away = $_POST['game_1_away'];
//Check if strings are numeric
if ((ctype_digit($strGame_1_home)) && (ctype_digit($strGame_1_away)))
{
//Check if prediction already exists in database for user
$strQueryPrediction = "SELECT count(id) amount FROM prediction where player_id = 1 and game_id = $strGame_id_1";
$resultQueryPrediction = mysql_query ($strQueryPrediction);
$intPredictionKnown = mysql_result($resultQueryPrediction, 0);
if ($intPredictionKnown == 0)
{
//NOT KNOWN so INSERT
$blnOK = executeQuery("INSERT INTO prediction (player_id, game_id, predict_home, predict_away) VALUES (1, $strGame_id_1, $strGame_1_home, $strGame_1_away)", $strErrorText, $db);
echo "Your prediction is saved";
}
else
{
//KNOWN so UPDATE
$blnOK = executeQuery("UPDATE prediction SET predict_home = $strGame_1_home, predict_away = $strGame_1_away WHERE player_id = 1 AND game_id = $strGame_id_1", $strErrorText, $db);
echo "Your prediction is updated";
}
}
else
{
$strResult = "Too bad, your prediction could not saved.";
$blnOK = false;
}
}
else
{
echo "Input is empty";
}
}
You could, and arguably should, use a loop to save you copying the code a number of times. You say there are 9 games, so you can do the following :
$blnOK = true;
$strResult = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
for ($i = 1; $i <= 9; $i++)
{
if (isset($_POST['game_id_' . $i]) && !empty($_POST['game_' . $i . '_home']) && !empty($_POST['game_' . $i . '_away']))
//check if the posts are not empty, then put in variables
{
$strGame_id = $_POST['game_id_' . $i];
$strGame_home = $_POST['game_' . $i . '_home'];
$strGame_away = $_POST['game_' . $i . '_away'];
//Check if strings are numeric
if ((ctype_digit($strGame_' . $i . '_home)) && (ctype_digit($strGame_' . $i . '_away)))
{
//Check if prediction already exists in database for user
$strQueryPrediction = "SELECT count(id) amount FROM prediction where player_id = 1 and game_id = $strGame_id";
$resultQueryPrediction = mysql_query ($strQueryPrediction);
$intPredictionKnown = mysql_result($resultQueryPrediction, 0);
if ($intPredictionKnown == 0)
{
//NOT KNOWN so INSERT
$blnOK = executeQuery("INSERT INTO prediction (player_id, game_id, predict_home, predict_away) VALUES (1, $strGame_id, $strGame_home, $strGame_away)", $strErrorText, $db);
echo "Your prediction is saved";
}
else
{
//KNOWN so UPDATE
$blnOK = executeQuery("UPDATE prediction SET predict_home = $strGame_home, predict_away = $strGame_away WHERE player_id = 1 AND game_id = $strGame_id", $strErrorText, $db);
echo "Your prediction is updated";
}
}
else
{
$strResult = "Too bad, your prediction could not saved.";
$blnOK = false;
}
}
else
{
echo "Input is empty";
}
}
}
Whenever you have to do something multiple times, think of using a loop if possible, or creating a function which you can call multiple times.

Unset Not Clearing Array Key/Value

I have form submission that redirects based on the results of a survey. On the landing page, I call a function to process query string, query the database and return results as an array for in-page processing.
function surveyResults() {
if($goodtogo) {
$survey = $wpdb->get_results(...,ARRAY_A);
$name_has_space = strpos(trim($q_name_field[0]),' ');
if($name_has_space === false) {
$q_first_name = $q_name_field[0];
$name_has_num = preg_match('/[0-9]/',$q_first_name);
$q_first_name = ((0 === $name_has_num) ? " ".ucfirst($q_first_name).", " : '');
} else {
$q_first_name = substr(trim($q_name_field[0]),0,$name_has_space);
$name_has_num = preg_match('/[0-9]/',$q_first_name);
$q_first_name = ((0 === $name_has_num) ? " ".ucfirst($q_first_name).", " : '');
}
$survey['name']['q_fname'] = $q_first_name;
$results = $survey;
} else {
$results = false;
}
return $results;
}
Output:
Array (
[0]=> Array (
'key' => 'value'
)
...
[n]=> Array (
'key' => 'value'
)
['name'] => Array (
[q_fname] => MyName
)
)
Which is perfect – except – each time I test the page, the $survey[0-n] results change as queried, but the $survey['name']['q_fname'] still holds the previous value MyName.
I have tried adding unset($survey['name']['q_fname']); immediately after setting $results = $survey; but that doesn't seem to make a difference. Do I need to unset($results) or use a reference &$fname...
What am I missing here?
Thanks
I'm macgregor, and I'm an idiot. Missed a critical piece of condition in the query.

Categories