Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

i have a simple problem with that fetch_array. i like to read out x1 and x2 from table A. the both arrays i need for a counter which will set up another field on another table B to +1. i wrote the following code but it doesnt work and i dont know where is the mistake. maybe someone can help me out. thanks alot.

$get_counter = "SELECT x1, x2 FROM tablename(A) WHERE id='$id'";
        $result2 = mysqli_query($db, $get_counter);

        $row = $result2->fetch_array(MYSQLI_ASSOC);

        $counter = "UPDATE tablename(B) SET xy=xy + 1 WHERE x1=$row["x1"] AND x2=$row["x2"]";
        $result3 = mysqli_query($db, $counter);
share|improve this question
 
What does not work? –  hakre Mar 12 '12 at 12:27
 
We assume tablename(A), tablename(B) are just placeholders here, as that is not a valid syntax. –  Michael Berkowski Mar 12 '12 at 12:31
add comment

3 Answers

up vote 1 down vote accepted

$counter = "UPDATE tablename(B) SET xy=xy + 1 WHERE x1='".$row["x1"]."' AND x2 ='".$row["x2"]."'";

share|improve this answer
 
hello and thanks for helping me out. i had to do it that way to get it work. thanks to all of you. best wishes –  John Mar 12 '12 at 12:49
add comment

Your quoting is faulty in $counter. It is good practice (and sometimes required) to surround arrays or objects in {} inside double-quoted strings.

$counter = "UPDATE tablename(B) SET xy = (xy + 1) WHERE x1={$row['x1']} AND x2={$row['x2']}";

However, if you do not intend to use x1, x2 aside from inside the second query, you can do this with one query and a JOIN. This eliminates the need for the first query and fetch call.

UPDTE 
 tablenameb B JOIN tablenamea A ON B.x1 = A.x1 AND B.x2 = A.x2
SET xy = (xy + 1)
WHERE A.id='$id'
share|improve this answer
add comment

Your SQL contains an error and your script doesn't check for SQL errors.

This:

$row = $result2->fetch_array(MYSQLI_ASSOC);

Should be:

if ($result2 === false) {
    printf("Invalid query: %s\nWhole query: %s\n", mysqli_error(), $get_counter);
    exit();
}

$row = $result2->fetch_array(MYSQLI_ASSOC);

See how $result2 is checked here, and how the SQL error is printed if it failed.

share|improve this answer
 
i added that to all of the queries. finally it was displaying the mistake at result3. thanks alot. –  John Mar 12 '12 at 12:51
 
I'm glad it helped you, please close the question –  jpic Mar 12 '12 at 12:53
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.