1

I have populated an array using explode from a comma separated string variable. Now I need to access the data in the array.

I used:

print_r($values); // to see how the data was stored
//output
Array ( 
  [0] => Array ( 
         [0] => 1rv09is001 
         [1] => 07IS72 ) 
  [1] => Array ( 
         [0] => 1RV09IS064   
         [1] => 07IS72 ) 
)

I tried:

$a = count($values);
for($i;$i<$a;$i++){
$sql="UPDATE subject 
      SET attendance=attendance+1 
      WHERE usn=$values[$i][0] AND subCode=$values[$i][1]
     ";

echo "$sql";
mysql_query($sql);
}

It isn't working.

1
  • 1
    The mysql_* functions are deprecated, use PDO or mysqli_* instead. Commented Nov 3, 2012 at 12:06

3 Answers 3

1

Complex variable names (or arrays, for that matter) need to be enclosed in curly brackets when used inside of strings. Also, strings in MySQL need to be designated as such with quotes (single ' or double "):

$a = count($values);
for ($i = 0; $i < $a; $i++) {
    $sql = "UPDATE subject SET attendance=attendance+1 WHERE usn='{$values[$i][0]}'  AND subCode='{$values[$i][1]}'";
    echo "$sql";
    mysql_query($sql);
}

Also, you need to initialize $i with a value when used in a for loop.

Sign up to request clarification or add additional context in comments.

1 Comment

$values[$i][0] is a string, you need to put single quotes
0

You should quote strings that goes into your sql (also you should escape them). http://dev.mysql.com/doc/refman/5.0/en/entering-queries.html

2 Comments

He shouldn't escape them, he should use prepared statements
Of course, but now he won't get the concept of binding variables/values. I think at first he should understand the basics.
0

Update your SQL statement:

$sql = "UPDATE subject SET attendance = attendance+1 where usn='" . $values[$i][0] . "' and subCode='" . $values[$i][1] . "'";

As far as I can see $values contains String values, which need to be quoted in SQL. Furthermore it is helpful to escape " . $variable . " array accesses.

Tested it locally and it works.

2 Comments

i printed the $sql and it turned out UPDATE subject SET attendance=attendance+1 WHERE usn='Array[0]' AND subCode='Array[1]'
Try to put echo mysql_error(); after your statement or submit the $sql manually to the database via PHPmyAdmin to get some error message.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.