outside of foreach loop query doesn't work properly - php

Here I'm trying to insert the datas again into database new table (with quantity & customer details). $grocery_id and $grocery_item values are fetch from database. $customername, $customermobile, $groqty values are user will enter the details in that appropriate textfield.
When I execute this code ($groceryid, $groceryitem) -> These two column always stored the last row values. Because I've put the query outside of foreach loop. Here is my problem. If I put the query inside the foreach it works fine. But, quantity values doesn't work properly. So, How can I execute the query properly (outside of foreach loop)?
<?php
if(isset($_POST['submit']))
{
$grocery_id = $rowid;
$grocery_item = $rowsitem;
$customername = $_POST['customername'];
$customermobile = $_POST['customermobile'];
$groqty = $_POST['groceryquantity'];
for($i = 0; $i < sizeof($groqty); $i++)
{
$groqtys = $groqty[$i];
foreach($grocery_id as $key => $index_id )
{
}
$sql = "INSERT INTO ".customer_order." SET grocery_id = '$index_id' , grocery_item = '$grocery_item[$key]', customername = '$customername', customermobile = '$customermobile', quantity = '$groqtys' ";
mysql_query($sql,$CN);
$response = asort_form_ok("Your order successfully submitted. We will deliver you soon.");
}
}
?>

You could simply use one foreach loop considering the index values of $grocery_id and $groqty are the same.
Try:
<?php
if (isset($_POST['submit']))
{
$grocery_id = $rowid;
$grocery_item = $rowsitem;
// sanitizing your values
$customername = mysql_real_escape_string($_POST['customername']);
$customermobile = mysql_real_escape_string($_POST['customermobile']);
$groqty = array_map('mysql_real_escape_string', $_POST['groceryquantity']);
foreach($grocery_id as $key => $index_id)
{
$sql = "INSERT INTO " . customer_order . " SET grocery_id = '$index_id' , grocery_item = '$grocery_item[$key]', customername = '$customername', customermobile = '$customermobile', quantity = '$groqty[$key]' ";
mysql_query($sql, $CN);
$response = asort_form_ok("Your order successfully submitted. We will deliver you soon.");
}
}
?>
Also note:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

Related

PHP Array to string to mysql - empty record

I am on point where I have to usk on forum.
So, I have an array that is my return from join table sql query.
i am displaying it correctly without the problem.
but some of those values I want to put in different table of mysql database.
$array = joint_table();
$array_value = array['key'];
I can echo array_value and it's displaying correctly, also checked variable type and it returns STRING.
however when I am inserting it into the table, it's empty cell.
I am inserting other stuff like date() and such and that is inserted correctly.
So my sql query works fine, besides I am using same query in other places without problem.
Only values I have from that array are not inserting, but still can echo them.
<?php
$page_title = 'Complete Task';
require_once('includes/load.php');
// Checkin What level user has permission to view this page
page_require_level(2);
$task = join_task_table((int)$_GET['id']);
?>
<?php
if(isset($_POST['complete_task'])){
$area = $task['area'] ;
$jig = $task['jig'];
$desc = $task['description'];
$freq = $task['freq'];
$date = make_date();
$user = current_user();
$user_done = remove_junk(ucfirst($user['name']));
$comment = remove_junk($db->escape($_POST['comment']));
if(empty($errors)){
$sql = "INSERT INTO tpm_history (area_name,jig_name,description,frequency,date_done,done_by_user,comment)";
$sql .= " VALUES ('{$area}','{$jig}','{$desc}','{$freq}','{$date}','{$user_done}','{$comment}')";
$result = $db->query($sql);
if($result && $db->affected_rows() === 1){
$session->msg('s',"Job Completed");
redirect('home.php', false);
} else {
$session->msg('d',' Sorry failed to complete the task!');
redirect('task_complete.php?id='.$task['id'], false);
}
} else{
$session->msg("d", $errors);
redirect('task_complete.php?id='.$task['id'],false);
}
}
?>
I am lost. Help.

Mysqli query doesn't work with id from another table

I have this php script.
$cwZ = count($wiegen_zutat);
$cwM = count($wiegen_menge);
$cwS = count($wiegen_schritt);
if($cwM == $cwS and $cwM == $cwZ and $cwZ == $cwS){
for($x = 0; $x < $cwZ; $x++){
$aktZuat = $wiegenZutat[$x];
$qr = "SELECT ID_Zutat FROM Zutaten WHERE Name='$aktZutat' LIMIT 1";
$id_get = mysqli_query($verbindung,$qr );
$id = mysqli_fetch_array($id_get);
$zuatenID = $id['ID_Zutat'];
echo $id['ID_Zutat'];
echo $zutatenID;
$sql3 = "INSERT INTO Wiegen (ID_Zutat, Menge) VALUES ('$zutatenID', '$wiegenMenge[$x]')";
$wiegenEintragen = mysqli_query($verbindung, $sql3);
}
}
$wiegen_zutat, _menge, _schritt are all three arrays which contain the information from my form.
I go through the first array, and check the variable against a table which contains the ingredients for my website. I want to get the id of a ingredient which was added some steps before and add it into another table.
The problem is that neither the echos or the query are working.
What am I missing?
Please don't get confused by the name of the variables, I'm german :)
Best regards

Error when fetching data from table using values from two different table - MySQL

I have two MySQL tables - "mfb_servicelog" and "mfb_agent_status_summary".
I want to select data from "total_ce" column in "mfb_agent_status_summary" where sl_id = $sl_id and then export it as an excel sheet using PHPExcel.
I can get the $sl_id value from mfb_servicelog table where h_id = $value[$i].
And the values of $value is coming from another php file using _POST as an array.
Please point me to the right direection.
Here is my code: (Its returning long list of error)
$value = $_POST['hospitalname'];
$from = $_POST['from'];
$to = $_POST['to'];
if($_POST["Submit"]=="Submit") {
for ($i=0; $i<sizeof($value); $i++) {
$queryslid="SELECT sl_id FROM mfb_servicelog WHERE h_id LIKE ('".$value[$i]."')";
if ($resultslid = (mysql_query($queryslid) or die(mysql_error())) {
while($rowslid = mysql_fetch_row($resultid)) {
$slidset[$i] = $rowslid;
}
$querycasesentered = "SELECT total_ce FROM agent_summary WHERE sl_id LIKE ('".$slidset[$i]."')";
if ($resultcaseentered = (mysql_query($querycasesentered) or die(mysql_error())) {
while($rowce = mysql_fetch_row($resultcasesentered)) {
$casee[$i] = $rowce;
if($i == 0) {
$col = 'H';
}
else {
$col = $k;
}
foreach ($rowce as $cell) {
$obejctPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$cell);
$col++;
}
$rowNumber++;
}
}
}
Just a heads up, you are accepting POST data without cleaning it before running your SQL statement, this is very very dangerous and opens your database to injection attacts. But to the problem at hand. Use a join SQL statement something like:
$sql = "SELECT total_ce FROM agent_summary AS agent LEFT JOIN mfb_servicelog AS service ON agent.sl_id = service.sl_id WHERE service.h_id LIKE ('".$value[$i]."')"
You are using mysql_query in a wrong way.
mysql_query has 2 parameters which is the connection and the query
You can look at this definition:
http://www.w3schools.com/php/func_mysqli_query.asp
In short, I suggest that you should use PDO when you are not sure what you are doing with mysql. In order to understand what is PDO, you should read this tutorial http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers carefully which help you to prevent your code from the SQL Injection.

Yii insert series of data

So, I got a series of data that I need to insert into a table. Right now I am using a for loop to iterate through each entry and save the model one by one. But that doesn't seem like a good way to do it, moreover using transaction would be an issue. What's a better way to do it to improve performance and also so I can use transaction.Here's the code I am currently using.
foreach ($sheetData as $data)
{
$newRecord = new Main;
$newRecord->id = $data['A'];
$newRecord->name = $data['B'];
$newRecord->unit = $data['C'];
$newRecord->save();
}
If you can skip validation, you can generate a simple sql insert and execute it once. like:
$count = 0;
$sql = '';
foreach ($sheetData as $data)
{
if(!$count)
$sql .= 'INSERT INTO tbl_main (id ,name ,unit) Values ('.$data['A'].','$data['B']','$data['C']') ';
else
$sql .= ' , ('.$data['A'].','$data['B']','$data['C']')';
$count++;
}
Yii::app()->db->createCommand($sql)->execute();

How to do a INSERT with two different loops?

Update
I have updated my code according to phant0m's suggestion. It still doesn't quite work yet, though: question_id is always 0 in the database, even though it's not in the array:
var_dump($_POST['question_id'])
array(2) { [0]=> string(2) "22" [1]=> string(2) "23" }
The query:
string(122) "INSERT INTO student_score(course_uid, student_uid, question_uid, answer) VALUES
(1, 4, 0, 'answer1'),
(1, 4, 0, 'answer4')
This is the new code:
$sql_data = array();
$sql_prefix = "INSERT INTO student_score(course_uid, student_uid, question_uid, answer) VALUES";
foreach($_POST['answer'] as $id => $answer){
// don't use $_REQUEST!
$course_id = (int) $_POST['course_id'][$i];
$student_id = (int) $_POST['student_id'][$i];
$question_id = (int) $_POST['question_id'][$i];
$answer = mysql_real_escape_string($answer);
$sql_data[] = "($course_id, $student_id, $question_id, '$answer')";
}
$sql = $sql_prefix.implode(", \n", $sql_data);
var_dump($sql);
if(!mysql_db_query($dbName, $sql, $connect)){
$_SESSION['msg'] = "Could not save information, Please try again";
header("Location:student_assignment.php");
//replaced die with else clause
}
else{
$_SESSION['msg'] = "Question successfully created";
header("Location:student_assignment.php");
}
Initial question:
I have a problem adding the values of an array into a mysql database. The thing is
I have two loops and if I add the INSERT in one of the then the other one gives the wrong value. But if I echo inside each loop it gives the right values.
At the moment it adds two double rows of each value where I only want one row of each value.
Here is my code:
<?php
require_once("settings.inc.php");
// require_once("student_session.inc.php");
session_start();
for ($d = 0; $d <= count($_POST[answer]); $d++) {
$answer = $_POST[answer][$d];//I want to insert this value
//echo $answer;
$ids = $_REQUEST['question_id'];
foreach ($ids as $value) {
//echo $value; //and this value into the INSERT
$sql = "INSERT INTO student_score(answer) VALUES ('$answer')";
$results = mysql_db_query($dbName, $sql, $connect);
}
}
if (!$results) {
$_SESSION['msg'] = "Could not save information, Please try again";
header("Location:student_assignment.php");
die;
}
$_SESSION['msg'] = "Question successfully created";
header("Location:student_assignment.php");
die;
?>
You're using the wrong variable:
"INSERT INTO student_score(answer) VALUES ('$answer')";
You comment that the variable you'd like inserted is called $value, so you meant to write:
"INSERT INTO student_score(answer) VALUES ".
"('".mysql_real_escape_string($value)."')";
(mysql_real_escape_string is to prevent SQL injection attacks)
make use of MySQL transactions:
PHP + MySQL transactions examples
Also can you post the output of the following?:
print_r($_POST); and print_r($_POST[answer]);
Using $_REQUEST is bad Idea. either use POST or GET explicitly!
Your code does not make much sense.
This might more closely resemble what you want it to do:
// you will not want <=, that will create an index error upon the last
// iteration, also, you need to quote the key!
// This is fixed:
//for ($d = 0; $d < count($_POST['answer']); $d++) {
// this is a better way
// this assumes, that the indices of the POST array nicely correspond with each
// other.
$sql_data = array();
$sql_prefix = "INSERT INTO student_score(question_id, student_id, course_id, answer) VALUES";
foreach($_POST['answer'] as $id => $anwer){
// don't use $_REQUEST!
$question_id = (int) $_POST['question_id'][$i];
$student_id = (int) $_POST['student_id'][$i];
$course_id = (int) $_POST['course_id'][$i];
$answer = your_escape_function($answer)
$sql_data[] = "($question_id, $student_id, $course_id, '$answer')";
}
$sql = $sql_prefix.implode(", \n", $sql_data);
if(!mysql_db_query($dbName, $sql, $connect)){
$_SESSION['msg'] = "Could not save information, Please try again";
header("Location:student_assignment.php");
//replaced die with else clause
}
else{
$_SESSION['msg'] = "Question successfully created";
header("Location:student_assignment.php");
}
Attention
This code is mostly based on guesswork and assumptions what you want it to do.
You need to have a function that properly escapes your code based on whether magic_quotes are enabled. Simply calling mysql_real_escape_string()as suggested in the other answer is incorrect.
Please note that mysql_* functions are outdated. Consider using parameterized queries using PDOs or myqsli.
PS: do not use $_REQUEST.

Categories