{"id":10356,"date":"2022-09-23T12:30:18","date_gmt":"2022-09-23T07:00:18","guid":{"rendered":"https:\/\/jassweb.com\/solved\/solved-retrieve-data-from-db-using-function-pdo\/"},"modified":"2022-09-23T12:30:18","modified_gmt":"2022-09-23T07:00:18","slug":"solved-retrieve-data-from-db-using-function-pdo","status":"publish","type":"post","link":"https:\/\/jassweb.com\/solved\/solved-retrieve-data-from-db-using-function-pdo\/","title":{"rendered":"[Solved] retrieve data from db using function pdo"},"content":{"rendered":"<p> [ad_1]<br \/>\n<\/p>\n<div id=\"answer-16608245\" class=\"answer js-answer accepted-answer js-accepted-answer\" data-answerid=\"16608245\" data-parentid=\"16608189\" data-score=\"3\" data-position-on-page=\"1\" data-highest-scored=\"1\" data-question-has-accepted-highest-score=\"1\" itemprop=\"acceptedAnswer\" itemscope itemtype=\"https:\/\/schema.org\/Answer\">\n<div class=\"post-layout\">\n<div class=\"votecell post-layout--left\"><\/div>\n<div class=\"answercell post-layout--right\">\n<div class=\"s-prose js-post-body\" itemprop=\"text\">\n<p>Change the function to this:<\/p>\n<pre><code>function run_db($sqlcom,$exe){\n    $conn = new PDO('mysql:host=localhost;dbname=dbname', 'usr', 'pass');\n    $conn-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);\n    $stmt = $conn-&gt;prepare($sqlcom);\n    $stmt-&gt;execute($exe);\n    return $stmt;\n}\n<\/code><\/pre>\n<p>and the call to that function to:<\/p>\n<pre><code>try {\n    $stmt = run_db('SELECT * FROM posts WHERE status= :published ORDER BY id DESC LIMIT 5',array(':published' =&gt; 'published'));   \n    while ($result = $stmt-&gt;fetch(PDO::FETCH_ASSOC)) {\n        $contents = $result['content'];\n        $title = $result['title'];\n<\/code><\/pre>\n<hr>\n<p><strong>EDIT:<\/strong> Better solution is the one that <strong>jeroen<\/strong> advices &#8211; to <strong>return all the fetched objects at once<\/strong>:<\/p>\n<pre><code>function run_db($sqlcom,$exe){\n    $conn = new PDO('mysql:host=localhost;dbname=dbname', 'usr', 'pass');\n    $conn-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);\n    $stmt = $conn-&gt;prepare($sqlcom);\n    $stmt-&gt;execute($exe);\n    return $stmt-&gt;fetchAll(PDO::FETCH_ASSOC);\n}\n<\/code><\/pre>\n<p>Then calling this way:<\/p>\n<pre><code>try {\n    $data = run_db('SELECT * FROM posts WHERE status= :published ORDER BY id DESC LIMIT 5',array(':published' =&gt; 'published'));   \n    foreach($data as $result) {\n        $contents = $result['content'];\n        $title = $result['title'];\n<\/code><\/pre>\n<hr>\n<p><strong>EDIT 2:<\/strong> Anyway &#8211; wrapping such a logic into one function is not very good idea. now You are limited with executing of only <code>SELECT<\/code> queries and the resulting array containing always only record&#8217;s associative array. What if You would like to (for any reason) retrieve the array of <strong>objects<\/strong>, or even <strong>only one single value<\/strong>? What if You would like to execute <code>INSERT<\/code>, <code>UPDATE<\/code>, <code>DELETE<\/code> queries???<\/p>\n<p>If You for sure want to go this way, then I&#8217;d suppose creating a class with functions like this:<\/p>\n<pre><code>class MyPDO {\n    private $connection;\n\n    static $instance;\n\n    function __construct() {\n        $this-&gt;connection = new PDO('mysql:host=localhost;dbname=dbname', 'usr', 'pass');\n        $this-&gt;connection-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);\n    }\n\n    static function getInstance() {\n        return self::$instance ?  : self::$instance = new MyPDO;\n    }\n\n    \/\/ retrieves array of associative arrays\n    function getAssoc($sqlcom, $exe) {\n        $stmt = $this-&gt;connection-&gt;prepare($sqlcom);\n        $stmt-&gt;execute($exe);\n\n        return $stmt-&gt;fetchAll(PDO::FETCH_ASSOC);\n    }\n\n    \/\/ retrieves array of objects\n    function getObj($sqlcom, $exe) {\n        $stmt = $conn-&gt;prepare($sqlcom);\n        $stmt-&gt;execute($exe);\n\n        return $stmt-&gt;fetchAll(PDO::FETCH_OBJ);\n    }\n\n    \/\/ retireves one single value, like for SELECT 1 FROM table WHERE column = true\n    function getOne($sqlcom, $exe) {\n        $stmt = $conn-&gt;prepare($sqlcom);\n        $stmt-&gt;execute($exe);\n\n        return $stmt-&gt;fetchColumn();\n    }\n\n    \/\/ just executes the query, for INSERT, UPDATE, DELETE, CREATE ...\n    function exec($sqlcom, $exe){\n        $stmt = $conn-&gt;prepare($sqlcom);\n\n        return $stmt-&gt;execute($exe);\n    }\n}\n<\/code><\/pre>\n<p>Then You can call it this way:<\/p>\n<pre><code>try {\n    $pdo = MyPDO::getInstance();\n    foreach($pdo-&gt;getAssoc('MySQL QUERY'), array($param, $param)) as $result) {\n        print_r($result);\n    }\n} catch(\\Exception $e) {\n    \/\/ ...\n}\n<\/code><\/pre>\n<\/p><\/div>\n<div class=\"mt24\"><\/div>\n<\/div>\n<p>            <span class=\"d-none\" itemprop=\"commentCount\">1<\/span> <\/p><\/div>\n<\/div>\n<p>[ad_2]<\/p>\n<p>solved retrieve data from db using function pdo <\/p>\n","protected":false},"excerpt":{"rendered":"<p>[ad_1] Change the function to this: function run_db($sqlcom,$exe){ $conn = new PDO(&#8216;mysql:host=localhost;dbname=dbname&#8217;, &#8216;usr&#8217;, &#8216;pass&#8217;); $conn-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $conn-&gt;prepare($sqlcom); $stmt-&gt;execute($exe); return $stmt; } and the call to that function to: try { $stmt = run_db(&#8216;SELECT * FROM posts WHERE status= :published ORDER BY id DESC LIMIT 5&#8217;,array(&#8216;:published&#8217; =&gt; &#8216;published&#8217;)); while ($result = $stmt-&gt;fetch(PDO::FETCH_ASSOC)) { $contents &#8230; <a title=\"[Solved] retrieve data from db using function pdo\" class=\"read-more\" href=\"https:\/\/jassweb.com\/solved\/solved-retrieve-data-from-db-using-function-pdo\/\" aria-label=\"More on [Solved] retrieve data from db using function pdo\">Read more<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[320],"tags":[413,855,339],"class_list":["post-10356","post","type-post","status-publish","format-standard","hentry","category-solved","tag-function","tag-pdo","tag-php"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>[Solved] retrieve data from db using function pdo - JassWeb<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/jassweb.com\/solved\/solved-retrieve-data-from-db-using-function-pdo\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"[Solved] retrieve data from db using function pdo - JassWeb\" \/>\n<meta property=\"og:description\" content=\"[ad_1] Change the function to this: function run_db($sqlcom,$exe){ $conn = new PDO(&#039;mysql:host=localhost;dbname=dbname&#039;, &#039;usr&#039;, &#039;pass&#039;); $conn-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $conn-&gt;prepare($sqlcom); $stmt-&gt;execute($exe); return $stmt; } and the call to that function to: try { $stmt = run_db(&#039;SELECT * FROM posts WHERE status= :published ORDER BY id DESC LIMIT 5&#039;,array(&#039;:published&#039; =&gt; &#039;published&#039;)); while ($result = $stmt-&gt;fetch(PDO::FETCH_ASSOC)) { $contents ... Read more\" \/>\n<meta property=\"og:url\" content=\"https:\/\/jassweb.com\/solved\/solved-retrieve-data-from-db-using-function-pdo\/\" \/>\n<meta property=\"og:site_name\" content=\"JassWeb\" \/>\n<meta property=\"article:published_time\" content=\"2022-09-23T07:00:18+00:00\" \/>\n<meta name=\"author\" content=\"Kirat\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Kirat\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"2 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-retrieve-data-from-db-using-function-pdo\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-retrieve-data-from-db-using-function-pdo\/\"},\"author\":{\"name\":\"Kirat\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31\"},\"headline\":\"[Solved] retrieve data from db using function pdo\",\"datePublished\":\"2022-09-23T07:00:18+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-retrieve-data-from-db-using-function-pdo\/\"},\"wordCount\":142,\"publisher\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\"},\"keywords\":[\"function\",\"pdo\",\"php\"],\"articleSection\":[\"Solved\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-retrieve-data-from-db-using-function-pdo\/\",\"url\":\"https:\/\/jassweb.com\/solved\/solved-retrieve-data-from-db-using-function-pdo\/\",\"name\":\"[Solved] retrieve data from db using function pdo - JassWeb\",\"isPartOf\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#website\"},\"datePublished\":\"2022-09-23T07:00:18+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-retrieve-data-from-db-using-function-pdo\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/jassweb.com\/solved\/solved-retrieve-data-from-db-using-function-pdo\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-retrieve-data-from-db-using-function-pdo\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/jassweb.com\/solved\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"[Solved] retrieve data from db using function pdo\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/jassweb.com\/solved\/#website\",\"url\":\"https:\/\/jassweb.com\/solved\/\",\"name\":\"JassWeb\",\"description\":\"Build High-quality Websites\",\"publisher\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/jassweb.com\/solved\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\",\"name\":\"Jass Web\",\"url\":\"https:\/\/jassweb.com\/solved\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png\",\"contentUrl\":\"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png\",\"width\":693,\"height\":132,\"caption\":\"Jass Web\"},\"image\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/\"}},{\"@type\":\"Person\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31\",\"name\":\"Kirat\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775798750\",\"contentUrl\":\"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775798750\",\"caption\":\"Kirat\"},\"sameAs\":[\"http:\/\/jassweb.com\"],\"url\":\"https:\/\/jassweb.com\/solved\/author\/jaspritsinghghumangmail-com\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"[Solved] retrieve data from db using function pdo - JassWeb","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/jassweb.com\/solved\/solved-retrieve-data-from-db-using-function-pdo\/","og_locale":"en_US","og_type":"article","og_title":"[Solved] retrieve data from db using function pdo - JassWeb","og_description":"[ad_1] Change the function to this: function run_db($sqlcom,$exe){ $conn = new PDO('mysql:host=localhost;dbname=dbname', 'usr', 'pass'); $conn-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $conn-&gt;prepare($sqlcom); $stmt-&gt;execute($exe); return $stmt; } and the call to that function to: try { $stmt = run_db('SELECT * FROM posts WHERE status= :published ORDER BY id DESC LIMIT 5',array(':published' =&gt; 'published')); while ($result = $stmt-&gt;fetch(PDO::FETCH_ASSOC)) { $contents ... Read more","og_url":"https:\/\/jassweb.com\/solved\/solved-retrieve-data-from-db-using-function-pdo\/","og_site_name":"JassWeb","article_published_time":"2022-09-23T07:00:18+00:00","author":"Kirat","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Kirat","Est. reading time":"2 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/jassweb.com\/solved\/solved-retrieve-data-from-db-using-function-pdo\/#article","isPartOf":{"@id":"https:\/\/jassweb.com\/solved\/solved-retrieve-data-from-db-using-function-pdo\/"},"author":{"name":"Kirat","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31"},"headline":"[Solved] retrieve data from db using function pdo","datePublished":"2022-09-23T07:00:18+00:00","mainEntityOfPage":{"@id":"https:\/\/jassweb.com\/solved\/solved-retrieve-data-from-db-using-function-pdo\/"},"wordCount":142,"publisher":{"@id":"https:\/\/jassweb.com\/solved\/#organization"},"keywords":["function","pdo","php"],"articleSection":["Solved"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/jassweb.com\/solved\/solved-retrieve-data-from-db-using-function-pdo\/","url":"https:\/\/jassweb.com\/solved\/solved-retrieve-data-from-db-using-function-pdo\/","name":"[Solved] retrieve data from db using function pdo - JassWeb","isPartOf":{"@id":"https:\/\/jassweb.com\/solved\/#website"},"datePublished":"2022-09-23T07:00:18+00:00","breadcrumb":{"@id":"https:\/\/jassweb.com\/solved\/solved-retrieve-data-from-db-using-function-pdo\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/jassweb.com\/solved\/solved-retrieve-data-from-db-using-function-pdo\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/jassweb.com\/solved\/solved-retrieve-data-from-db-using-function-pdo\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/jassweb.com\/solved\/"},{"@type":"ListItem","position":2,"name":"[Solved] retrieve data from db using function pdo"}]},{"@type":"WebSite","@id":"https:\/\/jassweb.com\/solved\/#website","url":"https:\/\/jassweb.com\/solved\/","name":"JassWeb","description":"Build High-quality Websites","publisher":{"@id":"https:\/\/jassweb.com\/solved\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/jassweb.com\/solved\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/jassweb.com\/solved\/#organization","name":"Jass Web","url":"https:\/\/jassweb.com\/solved\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/","url":"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png","contentUrl":"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png","width":693,"height":132,"caption":"Jass Web"},"image":{"@id":"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/"}},{"@type":"Person","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31","name":"Kirat","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/image\/","url":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775798750","contentUrl":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775798750","caption":"Kirat"},"sameAs":["http:\/\/jassweb.com"],"url":"https:\/\/jassweb.com\/solved\/author\/jaspritsinghghumangmail-com\/"}]}},"_links":{"self":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts\/10356","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/comments?post=10356"}],"version-history":[{"count":0,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts\/10356\/revisions"}],"wp:attachment":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/media?parent=10356"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/categories?post=10356"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/tags?post=10356"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}