简体   繁体   中英

How can I extract a row from my PDO query?

I am getting a syntax error on line 18 of this code, which is the section containing the variable {$user}.

I want to extract the 3 variables from the query and put them into PHP variables in the code.

$user = 'xxxxx';
$password = 'xxxxx';
$db = 'xxxxx';
$host = 'xxxxx';
$conn = new PDO("mysql:host=$host; dbname=$db", $user, $password);
//$conn = new PDO("mysql:host=$host;dbname=$db;charset=utf8", $user, $password, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);


//7 day users
$query = "SELECT user,email_address,DATEDIFF(NOW(),OrderDate) AS DateDiff
FROM MyTable WHERE DATEDIFF(NOW(),OrderDate) >= 6 AND enabled = 1 AND products_id IN (377) AND user = 'xxxxx'";
$stmt = $conn->query($query);
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
    extract($row);
        $to = "aa@ab.com";
        $subject = "expiries - ";
        $message = {$user};
        $from = "aa@ab.com";
        $headers = "From: $from";
        mail($to,$subject,$message,$headers);


        }

The expected result should be the get the user from the SQL query into a variable called $message

a while loop on ->fetch is redundant. Fetch returns a single row of data in an array format. Thus, a while loop is not needed here (as a loops intended use is to loop data).

From the docs :

PDOStatement::fetch — Fetches the next row from a result set

FETCH_ASSOC:
PDO::FETCH_ASSOC: returns an array indexed by column name as returned in your result s

The return value of this function on success depends on the fetch type. In all cases, FALSE is returned on failure.

So it returns an array. Just simply use:

try {
    $data = $stmt->fetch(PDO::FETCH_ASSOC);
    $column = $data['column'];
    # your code
} catch (Exception $e) {
    # err handling
}

Edit based on comment:

If the result set has multiple rows, how do you loop through them?

You can use a foreach loop using ->fetchAll()

PDOStatement::fetchAll — Returns an array containing all of the result set rows

# here we declare our SQL and pass in params for a prepared statement
$sql = 'SELECT * FROM table where `field` = :value;';
$res = $conn->prepare($sql);
$res->execute(array(':value' => $_POST['value'])); # exec the qry

# loop through the data and print_r $row
foreach ($res->fetchAll(PDO::FETCH_ASSOC) as $row)
{
    echo '<pre>'. print_r($row, 1) .'</pre>';
}

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