Problemas para ejecutar la consulta mysql de múltiples tablas desde PHP

I am attempting to match rows in a mysql table using the values from table1.column1 y la table2.column3 and then copy the value from table2.column2 dentro table1.column1 for each match. The query below does what I need to do, but only when I execute it manually (through phpmyadmin). When I try to execute it from PHP I receive the error Unknown column table1.column1 in 'field list'. Here is my PHP code:

<?php
mysql_connect($host,$user,$pass);
$db_selected = mysql_select_db($data);

$sql = "UPDATE table1 t1, table2 t2 
        SET t1.column1 = t2.column2 
        WHERE t1.column1 = t2.column3";

$result = mysql_query($sql);

if (!$result) {
  echo mysql_error();
} ?>

I know that the mysql connection info works because I am able to execute other queries. From my research on the error it seems that I might need backticks around some part of the query but after several tries I can't figure out the correct way.

EDIT 1 - As requested here is the real query:

UPDATE wp_mf_custom_groups,wp_mf_posttypes
SET wp_mf_custom_groups.post_type=wp_mf_posttypes.type
WHERE wp_mf_custom_groups.post_type=wp_mf_posttypes.id

Outputs the error

Unknown column 'wp_mf_custom_groups.post_type' in 'field list'

Additional information I just realized might be conflicting with it. Before this happens I also renamed the table using:

RENAME TABLE wp_mf_module_groups TO wp_mf_custom_groups

Maybe since the table was just renamed it cant reference it?

preguntado el 01 de febrero de 12 a las 14:02

Back ticks are only necessary if you're using a reserved word as a field or table name. Randomly sprinkling them around the query will NOT help. Did you doublecheck if your table1 contains a column1 ¿campo? -

You need to include your table schema. -

@Crontab: Not if the two tables are in the same database and that's the database that is selected. -

Are you sure you're connecting to the right database? Not some older version elsewhere? Using the right database? -

El Unknown column error tells me that the field doesn't exist in wp_mf_custom_groups. I know you said it works if you do it as a raw query through phpMyAdmin - perhaps use the "Create PHP code" button there. -

2 Respuestas

Worked when I added backticks to the columns only after WHERE

UPDATE wp_mf_custom_groups,wp_mf_posttypes
SET wp_mf_custom_groups.post_type=wp_mf_posttypes.type
WHERE wp_mf_custom_groups.`post_type=wp_mf_posttypes.id

Respondido 02 Feb 12, 02:02

If query works with PHPmyadmin try this

<?php
$con = mysql_connect($host,$user,$pass) or die('Failed to connect');
$db_selected = mysql_select_db('db_name', $con);

$sql = "UPDATE table1 t1, table2 t2 
    SET t1.column1 = t2.column2 
    WHERE t1.column1 = t2.column3";

$result = mysql_query($sql, $con);

if (!$result) {
  echo mysql_error();
} ?>

Respondido 01 Feb 12, 18:02

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.