简体   繁体   中英

Using MySQL variable with PHP variable within a transaction

Using MySQL and PHP I wrote the following transaction code. In the code in first yellow colour block I assign a string value to a php variable $b. I want to use this value in second yellow colour block MySQL transaction statement.

I like to combine/concatenate $b with the MySQL variable @A obtained from sale no row 7. Say MySQL variable @A give a value "try this" then I want to insert "try this my add" for the saledesc field for the saleno row 10 as in the second yellow line block $conn->query("INSERT INTO sales(saleno,saledesc) VALUES('10',@A$b)");

But the above insert is failing. What's the correct statement syntax/way to do this. My code is as follows:

$b = "my add";

$sqlstat = "SELECT @A:=saledesc FROM sales WHERE saleno='7' ";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);

    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    //Transaction Start
    $conn->beginTransaction();
    $conn->query("$sqlstat");

$conn->query("INSERT INTO sales(saleno,saledesc) VALUES('10',@A$b)");

    $conn->commit();

    }
    catch(PDOException $e)
    {
    echo $sql . "<br>" . $e->getMessage();
    $conn->rollback();
    }
    $conn = null;

The @A MySQL variable lives in the MySQL server, and the $b variable lives in the context of your php program. The expression @A$b is trying to concatenate them, but that yields strange results when php sends your query to MySQL.

 INSERT INTO sales(saleno,saledesc) VALUES('10',@Amy add)   // wrong!

(Who is Amy? Why are you expecting her to add something? MySQL can't make sense of this.)

You should do the concatenation of the two variables in your query explicitly, using something like this.

$conn->query("INSERT INTO sales(saleno,saledesc) VALUES('10',CONCAT(@A, '$b'))");

By the way, this isn't a transaction in the RDBMS sense.

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