1

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);
1
  • We assume tablename(A), tablename(B) are just placeholders here, as that is not a valid syntax. Commented Mar 12, 2012 at 12:31

3 Answers 3

2

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'
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

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
1

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.

1 Comment

i added that to all of the queries. finally it was displaying the mistake at result3. thanks alot.

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.