php - How can I store mysql results in different individual variables with one connection to the databse? -
i working on personal project , need help. after lot of research can't seem find proper solution problem(probably because not php developer - still learning).
ok need 3 post titles database , store each 1 of them in individual variables. need them individual because want use them in different parts of website. have managed doing 3 different queries databse wich suppose bad. there way send 1 query databse , store them @ once inside different variables? tried array , although close enough didn't seem working.
here code:
try { $stmt = $db->query('select posttitle blog_posts order postid desc limit 0,1'); $sslider_title1=''; while($row = $stmt->fetch()){ $sslider_title1 = $row['posttitle']; } } catch(pdoexception $e) { echo $e->getmessage(); } try { $stmt = $db->query('select posttitle blog_posts order postid desc limit 1,2'); $sslider_title2=''; while($row = $stmt->fetch()){ $sslider_title2 = $row['posttitle']; } } catch(pdoexception $e) { echo $e->getmessage(); } try { $stmt = $db->query('select posttitle blog_posts order postid desc limit 2,3'); $sslider_title3=''; while($row = $stmt->fetch()){ $sslider_title3 = $row['posttitle']; } } catch(pdoexception $e) { echo $e->getmessage(); }
so in order running 1 query must do
try { $stmt = $db->query('select posttitle blog_posts order postid desc limit 0,3'); $sslider_title1=''; $sslider_title2=''; $sslider_title3=''; while($row = $stmt->fetch()){ \\ part can't seem solve :p } }
please, not use variables such names. need array
:
$titles = array(); try { $stmt = $db->query('select posttitle blog_posts order postid desc limit 0,3'); while($row = $stmt->fetch()){ $titles[] = $row['posttitle']; } }
then in code can use
echo $titles[0]; echo $titles[1]; echo $titles[2];
for each of titles.
Comments
Post a Comment