Jump to content

Recommended Posts

I want to send 25 students records in to the mySQL in one go. I used a for loop to do this.

 

This is what I've tried so far and no success. Could someone help?

 

 

require_once("accessLocal.php");

for (i=0; i<25; i++) {
$student+$i = mysql_real_escape_string($_POST['student'+$i]);
$subjectID+$i = mysql_real_escape_string($_POST['subjectID'+$i]);

$query = sprintf("UPDATE studentbackup13 SET code='%s' WHERE name ='%s'", mysql_real_escape_string($subjectID+$i), mysql_real_escape_string($student+$i));
$result = mysql_query($query);
}

Link to comment
https://forums.phpfreaks.com/topic/271270-add-none-empty-data-into-the-array/
Share on other sites

first of all, you would only run mysql_real_escape_string() once on a variable, not twice as you are doing

second of all, mysql_real_escape_string() is, as the name suggests, only any use at sanitising strings, so it's useless against integers.

third of all, you should take the +$i out of the square brackets for the $_POST array call

finaly this is not an efficent way to do things, you may want to think about a different approach - you should never run queries inside of loops

Because it's a gross and needless waste of resources and possably bandwidth, also in the event of larger more complex queires can result in bans from certain hosting companies (can be percieved as a DoS style attack) not to mention that in certain cases, when multitreading is enabled with a low simultanious connection limit, you can end up filling the connection limit with what should be a single transaction, locking out any other transactions.

 

Edt : Oh, yeah, and there has only ever been a single occasion I have ever come accross where a looped query was required, and this is nowhere close to that.

Edited by Muddy_Funster

I see, i was just wondering because there has been a case or two were i have resulted in using query in a loop. Do you think you should generate a single query in a loop to execute it once complete?

 

Come to think of it i used recently to update multiple fields on the bases of an array of passed id's.

 

   /* Ticket Updates */
   public function ChangeCaseStatus($status,$ticketIds) {
       empty($this->errors); // clear errors
       for($i=0;$i<count($ticketIds);$i++) {
           if(!mysql_query('UPDATE '.$this->defaultTable.' SET status="'.$status.'" WHERE id='.$ticketIds[$i])) {
               $this->errors[$i] = $ticketIds[$i].' [status : '.$status.'] '.mysql_error();
           }
       }
       return $this->notification(count($ticketIds),'Marked '.$status);
   }

that is still running it in a loop, so if you have 50 ticket id's in that array you are hitting the DBS with 50 query requests, when you should be using only 1. As I don't have the first clue what you are doing this for, this is more of an extreme "catch all" solution for this type scenrio : (i'm assuming your working with id numbers here...)

$record = array();
for($i=0;$i<25;$i++){
$record[$i] = $_POST['student']+$i.",".$_POST['subject']+$i;
}
$appendSQL = "VALUES ";
$values = implode ('), (', $record);
$appendSQL .="({$values})";
$sql = <<<SQL
DROP TABLE IF EXISTS temp_table_update_dataset;
CREATE TEMPORARY TABLE temp_table_update_dataset (studentID int, subjectID int);
INSERT INTO temp_table_update_dataset (studentID, subjectID) {$appendSQL};
UPDATE studentbackup13
INNER JOIN temp_table_update_dataset
 ON (temp_table_update_dataset.studentID = studentbackup13.name)
SET studentbackup13.code = temp_table_update_dataset.subjectID
SQL;
$performUpdate = mysql_query($sql) or die (mysql_error());

that's just off the top of my head, so it's likely not going to work without some refinement, but it will at least give you the idea of using a single query request rather than looping.

is this a good way of doing it?

 

$ar1 = array(1,2,3,4,5);
$ar2 = array(9,8,7,6,5);

$n=0;
foreach ($ar1 as $thing) {
$bigar[$n][1] = $thing;
$n++;
}
$n=0;
foreach ($ar2 as $thing) {
$bigar[$n][2] = $thing;
$n++;
}
foreach ($bigar as $part) {
//echo $part[1].$part[2];

$query = sprintf("UPDATE studentbackup13 SET code='%s' WHERE name ='%s'", mysql_real_escape_string($part[1]), mysql_real_escape_string($part[2]));
$result = mysql_query($query);
}

Edited by RON_ron

in my submit form I have manditory fields and some optional fields. I want to create an array of only all the non empty inputs.

 

Doesn't work.

 

$a1 = array();

for (i=0; i<25; i++) {
if ($_POST['dataA']+$i != "") {
$a1[] = ['dataA']+$i;
$a1[$key] = ['dataA']+$i;
}
}

It's no wonder it doesn't work:

1. No $ on the variable in the for loop

2. You're using addition (+) when you probably mean concatenation (.)

3. You're doing the addition in the wrong place anyways

4. You're trying to add two items to $a1 for every $i

5a. You're probably not using PHP 5.4

5b. If you are you're trying to add a number to an array

6. You pulled $key out of mid air

 

I'm going to guess that your inputs are named "dataA1", "dataA2", and so on. Change that so they're all called "dataA[]". Or if you really want the numbers, "dataA[1]" and "dataA[2]". That way $_POST["dataA"] will be an array - something easier to deal with.

 

As for the code, it's DOA.

$a1 = array();
if (isset($_POST["dataA"]) && is_array($_POST["dataA"])) {
    foreach ($_POST["dataA"] as $key => $value) {
        if (is_string($value) && $value != "") {
            $a1[$key] = $value;
        }
    }
}

Thank you requinix.

I'm getting an error and I dodn't know how to fix it? (Warning: Invalid argument supplied for foreach())

 

Here's what I'm trying to achieve;

1. DataA This is the students ID and DataB is the student name.

2. In my form there are 25 rows to enter the student IDs and student names. When the submit button is clicked, it brings all the data to this php (below).

3. I want this PHP to be able to search the student name and update the ID accordingly for all the 25 students.

 

//all input data is DataA and DataB.

$ar1 = array();
if (isset($_POST['DataA']) && is_array($_POST['DataA'])) {
foreach ($_POST['DataA'] as $key => $value) {
	if (is_string($value) && $value != "") {
		$ar1[$key] = $value;
	}
}
}
$ar2 = array();
if (isset($_POST['DataB']) && is_array($_POST['DataB'])) {
foreach ($_POST['DataB'] as $keys => $values) {
	if (is_string($values) && $values != "") {
		$ar2[$keys] = $values;
	}
}
}

$n=0; //Warning: Invalid argument supplied for foreach()
foreach ($ar1 as $thing) {
$bigar[$n][1] = $thing;
$n++;
}
$n=0; //Warning: Invalid argument supplied for foreach()
foreach ($ar2 as $thing) {
$bigar[$n][2] = $thing;
$n++;
}
foreach ($bigar as $part) { //Warning: Invalid argument supplied for foreach()
$query = sprintf("UPDATE db1 SET code='%s' WHERE name ='%s'", mysql_real_escape_string($part[2]), mysql_real_escape_string($part[1]));
$result = mysql_query($query);
}

Edited by RON_ron

Is that your actual code? Do a var_dump() of $ar1, $ar2, and $bigar before their respective loops and make sure they're arrays. Because somehow they're not, even though I don't see how that's possible with the code you've shown*.

 

* Well yes, $bigar=null. But the other two I don't know.

Edited by requinix

the POST values doesn't seem to be going in to the arrays? Any idea why?

 

 

$ar1 = array();

if (isset($_POST['DataA']) && is_array($_POST['DataA'])) {

foreach ($_POST['DataA'] as $key => $value) {

if (is_string($value) && $value != "") {

$ar1[$key] = $value;

}

}

}

$ar2 = array();

if (isset($_POST['DataB']) && is_array($_POST['DataB'])) {

foreach ($_POST['DataB'] as $keys => $values) {

if (is_string($values) && $values != "") {

$ar2[$keys] = $values;

}

}

}

 

$n=0;

foreach ($ar1 as $thing) {

$bigar[$n][1] = $thing;

$n++;

}

$n=0;

foreach ($ar2 as $thing) {

$bigar[$n][2] = $thing;

$n++;

}

foreach ($bigar as $part) {

$query = sprintf("UPDATE db1 SET code='%s' WHERE name ='%s'", mysql_real_escape_string($part[2]), mysql_real_escape_string($part[1]));

$result = mysql_query($query);

}

Edited by RON_ron

OUTPUT

string(3) "ar1"

string(3) "ar2"

What does this mean?

 

if (isset($_POST['DataA']) && is_array($_POST['DataA'])) {
foreach ($_POST['DataA'] as $key => $value) {
if (is_string($value) && $value != "") {
$ar1[$key] = $value;
}
}
}
echo var_dump(ar1)."<br>";

$ar2 = array();
if (isset($_POST['DataB']) && is_array($_POST['DataB'])) {
foreach ($_POST['DataB'] as $keys => $values) {
if (is_string($values) && $values != "") {
$ar2[$keys] = $values;
}
}
}
echo var_dump(ar2)."<br>";

Edited by RON_ron
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.