The best and most secure way to echo results with pdo - php

Hi i am new to PDO and i just learn how to make a Query, i have read a lot about this everywhere on the internet, without luck, and then i tryed this, but i am still wondering if this is the right way to do it? How is the best way to make this to a class, because when i tryed, i did not got any kind of error, and any respond either.
<?php
require_once 'dbconfig.php';
// (echo test) $name_structure='%s';
// (echo test) $title_structure='%s';
try {
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$sql = 'SELECT *
FROM portfolio';
$q = $conn->prepare($sql);
$q->execute(array('%son'));
$q->setFetchMode(PDO::FETCH_ASSOC);
while ($r = $q->fetch()) {
echo sprintf($name_structure, $r['name']);
echo sprintf($title_structure, $r['title']);
echo sprintf($description_structure, $r['description']);
echo sprintf($img_structure, $r['img']);
echo sprintf($project_end_structure, $r['project_end']);
}
} catch (PDOException $pe) {
die("Could not connect to the database $dbname :" . $pe->getMessage());
}

As you forgot to explain what is "this" you are trying, here are two possible scenarios:
In case "this" is for getting all the records from database, the code would be
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$stmt = $conn->query('SELECT * FROM portfolio');
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row['name'];
echo $row['title'];
echo $row['description'];
echo $row['img'];
echo $row['project_end'];
}
in case "this" is about selecting only certain records, code it as follows
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$stmt = $conn->prepare('SELECT * FROM portfolio WHERE name LIKE ?');
$stmt->execute(array('%son'));
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row['name'];
echo $row['title'];
echo $row['description'];
echo $row['img'];
echo $row['project_end'];
}
How is the best way to make this to a class,
PDO is already a class, mind you. So, insead of making it into another, just learn how to use PDO.
i have read a lot about this everywhere on the internet, without luck,
Here you go, I wrote a tutorial that makes sense (at least for anyone who have basic PHP/SQL training), The only proper guide on PDO

Related

How to print the contents of a query to a blank page

Hello everyone,
Just a quick question, I am querying a database and i was wondering can anyone help me print the results of the query from a database into a new tab window. I think i have an idea on how to do it, but can someone guide me. So before i call the $statement->execute(); function in php should i create a tag?
So for example,
<?php
if (isset($_GET['submit'])) {
$stat = (!empty($_GET['stat']) ? trim($_GET['stat']) : '');
try {
$dsn = sprintf('mysql:host=%s;dbname=%s;charset=utf8', $databasehost, $dbname);
$database_handler = new PDO($dsn, $dbuser, $dbpass, array(
PDO::ATTR_EMULATE_PREPARES=>false,
PDO::MYSQL_ATTR_DIRECT_QUERY=>false,
PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION
));
$statement = $database_handler->prepare("SELECT * FROM tags WHERE bin = "Teller";)
$statement->bindParam(':stat', $stat, PDO::PARAM_STR);
$statement->execute();
$queryResult = $statement->fetchAll(PDO::FETCH_ASSOC);
$_SESSION['queryResult'] = $queryResult;;
$statement->execute();
}
catch (PDOException $e) {
print "Error: " . $e->getMessage();
}
?>
Is this possible? Please mind my lack of knowledge, i am a beginner in php.

Chat system foreach dynamic

What I'm trying to do is a User -> Admin || Admin -> User) chat system. What I've come up with so far looks really messed up, I tried JOIN on the select via SQLfiddle and it didn't work out so good.
Hopefully someone has a better idea and knows how to solve this problem.
My live chat PHP code -> http://pastebin.com/6z9ajCMW
And for my database structure for the live_chat and live_chat_admin it's here -> http://sqlfiddle.com/#!2/ae70ec/26
And to get a basic idea of what I'm trying to make.
Maybe you should try to create a unique id for each chat so it easier for you to retrive it. Tables will be similar to something like this.
Everytime a user starts a new chat, a new row is inserted in chat_unique. This will prevent other users to join a chat.
However, your page will reload everytime someone sends a new message. The best way would be to use Ajax.
Here you go
You just need to align right and left accordingly to the admin and the user that you have in your form as i have like in the below code
i.e.,
echo '<div align="right">';
and ending with
echo '</div>';
Code :
<?php
echo '<div class="live_chat">';
$user = 'root';
$pass = '';
// admin chat
$conn = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $conn->prepare("SELECT * FROM live_chat_admin WHERE receiver = :user_id");
$sth->bindValue(':user_id', '2', PDO::PARAM_INT);
$sth->execute();
foreach ($sth as $row) {
// Test message #1
echo '<div align="right">';
echo '<div class="admin_date">'.date('M j <b\\r/> H:i', strtotime($row['message_date'])).'</div>';
echo '<div class="admin_bubble">'.$row['message'].'</div>';
echo '<br /><br />';
echo '</div>';
}
$conn = NULL;
// user chat
#$conn = new PDO('mysql:host='. DB_HOST .';dbname='. DB_NAME . ';charset=utf8', DB_USER, DB_PASS);
#$conn = new PDO('mysql:host=127.0.0.1;dbname=test;charset=utf8', root);
$user = 'root';
$pass = '';
$conn = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $conn->prepare("SELECT * FROM live_chat WHERE user_id = :user_id");
$sth->bindValue(':user_id', '2', PDO::PARAM_INT);
$sth->execute();
foreach ($sth as $row) {
// Test message #1
echo '<div class="user_date">'.date('M j <b\\r/> H:i', strtotime($row['message_date'])).'</div>';
echo '<div class="user_bubble">'.$row['message'].'</div>';
echo '<br /><br />';
}
$conn = NULL;
echo '</div>';
?>
So your screen will be as you expected
Solved my problem with a bit of help from #Eddy Ella.
I first of deleted live_chat_admin and moved receiver to live_chat instead.
And then I used CASE WHEN for switching between id's from user to admin.
Result, exactly as I wanted it.
PHP: http://pastebin.com/GXJEK6u4
SQL: http://sqlfiddle.com/#!2/7081b/5
Result:

PDO mySql Connection

There is a link that I found a while back. What I would like to know is:
How do I query a simple SELECT * FROM table_name using PDO?
I tried playing around with the examples here but I was not getting any results back. All along I have been using the mysql_connect method which I dont want to use anymore. I would like to use following:
<?php
$host="127.0.0.1"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="microict-intrasys"; // Database name //
//$id = 5;
try {
$conn = new PDO('mysql:$host;$db_name,', $username, $password);
$stmt = $conn->prepare('SELECT version FROM system_info');
// $stmt->execute(array('id' => $id));
$result = $stmt->fetchAll();
if ( count($result) )
{
foreach($result as $row)
{
print_r($row);
}
}
else
{
echo "No rows returned.";
}
}
catch(PDOException $e)
{
echo 'ERROR: ' . $e->getMessage();
}
?>
First create the pdo instance and connect...
$db = new PDO('mysql:host=127.0.0.1;dbname=yourDBName;charset=utf8', 'username', 'password');
I use charset as well to have the correct formated data here... but you dont have to use it. Connection string could also look like
PDO("mysql:host=127.0.0.1;dbname=yourDBName" , $username, $password);
(using $username & $password here)
since working with pdo i ran into speed issues when i use localhost instead of 127.0.0.1 PDO seems to use the DNS to translate localhost into 127.0.0.1 and this causes speed. And im talking about seconds just for connecting to DBs
after connecting you can query like
$stmt = $db->query("SELECT * FROM table");
and than fetch could results like
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row['field1'].' '.$row['field2']; //etc...
}
or
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
print_r($result);
so than you should have at least some result.... (simple way)
I guess your problem is...
accourdig to your source you have a issue in your connectionstring....
<?php
$host="127.0.0.1"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="microict-intrasys"; // Database name
//$id = 5;
try {
$conn = new PDO('mysql:host={$host};dbname={$db_name}', $username, $password);
// you neeeeeed this--^ and this--^
$stmt = $conn->prepare('SELECT version FROM system_info');
$stmt->execute(array('id' => $id));
$result = $stmt->fetchAll();
if ( count($result) )
{
foreach($result as $row)
{
print_r($row);
}
}
else
{
echo "No rows returned.";
}
}
catch(PDOException $e)
{
echo 'ERROR: ' . $e->getMessage();
}
?>
you are missing some in your connection string! kinda typo
your parsed string looks like
"mysql:localhost;microict-intrasys"
and thats wrong. it must look like
//"mysql:host=localhost;dbname=microict-intrasys"
"mysql:host=127.0.0.1;dbname=microict-intrasys" // better
PDO Check
if (!defined('PDO::ATTR_DRIVER_NAME')) {
echo 'PDO unavailable';
}

two mysqli querys, one in a while loop

Can't seam to find the answer to this.
I have a mysqli loop statement. And in that loop I want to run another query. I cant write these two sql together. Is that possible?
I thought since I use stmt and set that to prepare statement. So i add another variable stmt2. Running them seperate works, but run it like I wrote it gives me "mysqli Fatal error: Call to a member function bind_param() on a non-object"
Pseudocode :
loop_sql_Statement {
loop_another_sql_statement(variable_from_firsT_select) {
echo "$first_statement_variables $second_statemenet_variables";
}
}
$sql = "select dyr_id, dyr_navn, type_navn, dyr_rase_id, dyr_fodt_aar, dyr_kommentar, dyr_opprettet, dyr_endret
from dyr_opphald, dyr, dyr_typer
where dyropphald_dyr_id = dyr_id
and dyr_type_id = type_id
and dyropphald_opphald_id = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("i",
$p_opphald_id);
$stmt->execute();
$stmt->bind_result($dyr_id, $dyr_navn, $type_navn, $dyr_rase_id, $dyr_fodt_aar, $dyr_kommentar, $dyr_opprettet, $dyr_endret);
echo "<table>";
while($stmt->fetch()) {
echo "<tr><td>$dyr_navn</td><td>$type_navn</td><td>$dyr_rase_id</td><td>$dyr_fodt_aar</td><td>";
$sql2 = "select ekstra_ledetekst, ekstradyr_ekstra_verdi from dyr_ekstrainfo, ekstrainfo where ekstradyr_ekstra_id = ekstra_id and ekstradyr_dyr_id = ?";
try {
$stmt2 = $mysqli->prepare($sql2);
$stmt2->bind_param("i",
$dyr_id);
$stmt2->execute();
$stmt2->bind_result($ekstra_ledetekst, $ekstra_ledetekst);
echo "<td>";
while($stmt2->fetch()) {
echo "$ekstra_ledetekst => $ekstra_ledetekst<br>";
}
}catch (Exception $e) {}
echo "</td></tr>";
}
echo "</table>";
The answer:
Silly me, I didnt know I had to have two mysqli connection. So the solution was to declare another mysqli connection.
$mysqli = new mysqli($start, $name, $pwd, $selected_db);
$mysqli2 = new mysqli($start, $name, $pwd, $selected_db);
You should be able to do that, although you make have to start a second connection.

MySQL MATCH, AGAINST not works with PDO

I have this simple code to make search results depending on relevance:
$stmt = $db->query('SELECT * FROM `apps` WHERE MATCH(appName, appSeller) AGAINST("angry")');
$appCount = $stmt->rowCount();
echo $appCount;
And it's not showing any results!
Thanks in advance for your help,
Marcell
Stackoverflow's usability is below zero.
Because there is no way to make a half-screen banner shown to everyone posting a question under PDO tag:
Enable ERRMODE_EXCEPTION when connecting to PDO before asking a question.
Because it is pointless to ask without an error message, yet error message most likely will render a question unnecessary.
$dsn = 'mysql:host=localhost;dbname=test;charset=utf8';
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
);
$pdo = new PDO($dsn,'root','', $opt);
Try
'SELECT * FROM `apps` WHERE MATCH(appName, appSeller) AGAINST("angry")'
in phpmyadmin and see if it really returns anything.
try this
<?php
// Connection data (server_address, database, name, poassword)
$hostdb = 'localhost';
$namedb = 'tests';
$userdb = 'username';
$passdb = 'password';
try {
// Connect and create the PDO object
$db = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
$db->exec("SET CHARACTER SET utf8"); // Sets encoding UTF-8
// Define and perform the SQL SELECT query
$sql = "SELECT * FROM `apps` WHERE MATCH(appName, appSeller) AGAINST("angry")";
$stmt = $db->query($sql);
// If the SQL query is succesfully performed ($stmt not false)
if($stmt !== false) {
$cols = $stmt->columnCount(); // Number of returned columns
echo 'Number of returned columns: '. $cols. '<br />';
// Parse the result set
foreach($stmt as $row) {
echo $row['id']. ' - '. $row['name']. ' - '. $row['category']. ' - '. $row['link']. '<br />';
}
}
$db = null; // Disconnect
}
print_r($sth->errorInfo());
}
?>
enclose your code in try and catch blocks, then you should get a clue to where your going wrong in your SQL syntax:
try {
// your code
} catch ( PDOException £e ) {
echo $e->getMessage();
exit();
}

Categories