简体   繁体   中英

Nesting a PHP string with a SQL command into another SQL insert statement

sql_insert = "INSERT INTO pics (filename) VALUES ('$fileName')";
$results_insert = $conn->query($sql_insert);

$max = "SELECT pic_id FROM pics WHERE pic_id = (SELECT MAX(pic_id) FROM pics)";

$sql_update = "UPDATE users 
            SET pic_id = '$max'
            WHERE username = '$username'" ;

The error I am receiving is:

Error: Unknown column 'pic_id' in 'field list'

I am not sure how to nest a PHP string with a SQL command into another SQL insert statement. I have already double checked that the pics table exists as well as the pic_id column.

EDIT: I am now trying to use PDO to accomplish this.

$t = $pdo->beginTransaction();

$sth = $pdo->prepare('SELECT MAX(pic_id) FROM pics');
$sth -> execute();
$pic_id = $sth->fetch(PDO::FETCH_ASSOC);

$sth = $pdo->prepare('UPDATE users SET username = :username, password = :password, email = :email, name = :name, country_id = :country_id, pic_id = :pic_id WHERE username = :username');
$sth->bindParam(':pic_id', $pic_id, PDO::PARAM_INT);
$sth->bindParam(':username', $username, PDO::PARAM_STR);
$sth->execute();

$sth = $pdo->prepare('INSERT INTO pics (pic_id, filename, filepath) VALUES (:pic_id, :fileName, :resized_file)');
$sth->bindParam(':fileName', $fileName, PDO::PARAM_STR);
$sth->execute();

$pdo->commit();

The reason why I moved the insert into the pics table below the users table was because the pic_id in pics references the pic_id in users . I am however still getting the same error:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'pic_id' in 'field list'

A lot of programs (MySQLI, PDO) have methods that will return the ID of the last inserted item, but I'm not really sure what program you're using to interact with your database.

Generic Method

SELECT pic_id FROM pics ORDER BY pic_id DESC LIMIT 1;

MySQLI Method

$max = $mysqli->insert_id;

PDO Method

$max = $pdo->lastInsertId();

I'd use PDO and binding parameters instead of using PHP string values. Also I suppose you should do all these operations within one transaction. So I'd rewrite code as follow:

$t = $pdo->beginTransaction();

$sth = $pdo->prepare('INSERT INTO pics (filename) VALUES (:fileName)');
$sth->bindParam(':fileName', $fileName, PDO::PARAM_STR);
$sth->execute();

$id = $pdo->lastInsertId();

$sth = $pdo->prepare('UPDATE users SET pic_id = :id WHERE username = :username');
$sth->bindParam(':id', $id, PDO::PARAM_INT);
$sth->bindParam(':username', $username, PDO::PARAM_STR);
$sth->execute();

$pdo->commit();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM