Steven Sugiarto Wijaya Steven Sugiarto Wijaya - 29 days ago 8
PHP Question

change connection db to PDO

i have recently code change database connection to PDO.
actually i have do it right and success. but i want a little modification in pdo connection.
this is the old code:

$sql = "select * from pengguna where marketing = '$nim_temp'";
$result = mysql_query($sql);
if($result)
{
while ($row = mysql_fetch_array($result))
{
$marketing= $row['marketing'];
$password = $row['password'];
$akses= $row['akses'];
}
}


and my new code using PDO:

$sql = "select * from pengguna where marketing = :nim_temp";
$stmt=$conn->prepare($sql);
$stmt->execute(array(':nim_temp'=>$nim_temp));
$result=$stmt->fetch( PDO::FETCH_ASSOC );

if($result)
{
while($row = $result)
{
//echo '<script type="text/javascript">alert("'.$row['marketing'].'");</script>';
$marketing= $row['marketing'];
$password = $row['password'];
$akses= $row['akses'];
}
}


It is success without $result and if result like:

//$result=$stmt->fetch( PDO::FETCH_ASSOC );
//if($result){
while($row = $stmt->fetch( PDO::FETCH_ASSOC ))


what i want is, i still need
if($result)
to trigger my other code.

Answer

Whether your query was a success or not is now determined by execute(), not by fetch(). So you have to do it like this:

$result = $stmt->execute(array(':nim_temp'=>$nim_temp));

if($result)
{
    while($row = $stmt->fetch(PDO::FETCH_ASSOC))
    { ... }
}
Comments