How to add a row to array with PDO - mysql

How can I add a row to array using PDO. Previously i did it like this $message = array('status' => 'ok'; But when I try to use this in PDO like this it does't work
try {
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->query($sql);
$employees = $stmt->fetchAll(PDO::FETCH_OBJ);
$employees['status'] = 'ok';
$employees = array($employees);
$dbh = null;
header('Content-Type: application/json');
echo '{"key":'. json_encode($employees) .'}';
}

Try
$employees = $stmt->fetchAll(PDO::FETCH_ASSOC);
If you want to typecast $employees into an array, you should be using
$employees = (array)$employees;

Related

getting error back from Prepared statement in case sql injection

I'm trying to test my prepared statement that is protecting one field to get the error message in case of SQL injection. I tried until now thousands of attacks, and all of the values I gave were accepted. Am I using a wrong syntax or attack? I can't see where the problem is. Here is my code:
try {
// $host = "localhost";
// $username = "root";
// $password = "root";
// $db_name = "pokemon";
$conn = new PDO('mysql:host='.$host.';dbname='.$db_name.';', $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$meldung="";
$name =$_REQUEST['name'];
$gewicht = $_REQUEST['Gewicht'];
$größe =$_REQUEST['Größe'];
$spezies = $_REQUEST['Spezies'];
$stufe =$_REQUEST['Stufe'];
$atacke =$_REQUEST['Attacke'];
$array = explode(',', $_REQUEST['Attacke']);
$stmt = $conn->prepare("INSERT INTO Pokemon (`Name`,`Gewicht`,`grosse`,`spezies`,`stufe`) VALUES (:Name, '".$gewicht."', '".$größe."', '".$spezies."', '".$stufe."')");
$stmt->bindParam(':Name', $name);
// $stmt->bindParam(':Gewicht', $gewicht);
// $stmt->bindParam(':grosse', $größe);
// $stmt->bindParam(':spezies', $spezies);
// $stmt->bindParam(':stufe', $stufe);
$stmt->execute();
}
catch(PDOException $e)
{
$meldung = "Error: " . $e->getMessage();
echo $meldung;
}
thanks

wordpress json_decode is not working, I am trying to get value form wp_option table

When I am trying to decode JSON with this code the output is
ArrayArray ( [0] => )
I do not know why WordPress doesn't support this
<?php
global $wpdb;
$mylink = $wpdb->get_results( "SELECT option_value FROM wp_options WHERE option_id=62167", ARRAY_N );
$raw = stripslashes_deep($mylink);
$data = array();
foreach ($raw as $json) {
echo $json;
$item = #json_decode($json, true);
$data[] = $item;
print_r($data);
}
?>
Hello you need to unserealize the data first when your query get data from database,
That is serealized data and when we get it from db we need to unserealize it.
global $wpdb;
$mylink = $wpdb->get_results("SELECT option_value FROM wp_options WHERE option_id=1223",ARRAY_A);
$raw = stripslashes_deep($mylink);
$data = $raw[0]['option_value'];
$datas = unserialize($data);
foreach ($datas as $key => $value) {
print_r($value);
}

How can I return a query object in Yii2?

How can I return all results of yii\db\Query as an object from a query like this one?
$query = new Query;
$query->select('id, name')
->from('user')
->limit(10);
$rows = $query->all();
Try this way
use yii\db\Query;
$query = new Query;
// compose the query
$query->select('id, name')
->from('user')
->limit(10);
// build and execute the query
$rows = $query->all();
// accessing the value
foreach ($rows as $row){
echo $row['name'];
}
for accessing via $row->name;
try with
use common\models\User; // or you app or backend depend where you have models
$rows = User::find()->limit(10)->all();
foreach ($rows as $row){
echo $row->nome;
}

write custom query with zend framework 2

I want to perform a custom query in zf2. Now I have a Album controller and AlbumTable. Inside AlbumTable, I want to perform an join operation. But I am unable to do this.Please give me some suggation.
below my code:
namespace WebApp\Table;
use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Sql\Sql;
new Zend\Db\Adapter\Adapter;
class UserTable
{
protected $tableGateway;
public function __construct(TableGateway $tableGateway)
{
$this->tableGateway = $tableGateway;
}
public function searchUser($search)
{
$search = "mehedi";
$adapter = new Adapter();
$sql = new Sql($adapter);
$select = $sql->select();
$select->from('foo');
$select->join('profiles', 'user.user_id = profiles.ownerId', array('name'));
$select->where(array('id' => 2));
$statement = $sql->prepareStatementForSqlObject($select);
$results = $statement->execute();
return $results;
}
}
The issue is you are trying to instantiate your Adapter with no parameters, when it requires at least a driver :
$adapter = new Adapter(); // Bad
$adapter = new Adapter($driver); // ..
You should use the ServiceManager to get your Adapter, did you start with the Skeleton Application?
It should have already been injected into the TableGateway for you..
$adapter = $this->getAdapter();
An example of instantiating an Adapter:
$config = $serviceLocator->get('Config');
$adapter = new Adapter($config['db']);
where you specify your setup inside your config, local.php will do:
return array(
/**
* Database Config
*/
'db' => array(
'driver' => 'pdo',
'dsn' => 'mysql:dbname=dbname;host=localhost',
'username' => 'root',
'password' => 'password',
),
I got some solution of this problem with helping all of here.
$adapter = $this->tableGateway->getAdapter();
/* $adapter variable is used to fetch Adapter
configuration from serivce manager. */
$sql = new Sql($adapter);
$select = $sql->select();
$select->from('foo');
$select->join('profile', 'foo.skillId = profile.id', array('name'));
$statement = $sql->prepareStatementForSqlObject($select);
$results = $statement->execute();
/* if you want you can see your
desired output in here. */
foreach ($results as $person) {
echo "<pre>";
print_r($person);
}
return $results;
It's because the join method expects an array for the join table. Also I personally would prefix the tables in the query, something like this:-
$search = "mehedi";
$adapter = new Adapter();
$sql = new Sql($adapter);
$select = $sql->select();
// PREFIXED THE foo table f
$select->from(array('f' =>'foo'));
// PREFIXED THE profiles table p
$select->join(array('p' => 'profiles'), 'user.user_id = profiles.ownerId', array('name'));
$select->where(array('id' => 2));
$statement = $sql->prepareStatementForSqlObject($select);
$results = $statement->execute();
return $results;

MySQL & PDO : about efficiency

I have the following code :
<?php
try {
# MySQL with PDO_MYSQL
$DBH = new PDO("mysql:host=*****;dbname=****", "****", "*****");
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
# statement handle (prevents injection)
$STH = $DBH->prepare("SELECT Adresse FROM Agences");
$STH->execute();
# statement handle (prevents injection)
$STHNAMES = $DBH->prepare("SELECT `numero-agence` FROM Agences");
$STHNAMES->execute();
$storeArray = Array();
$nameArray = Array();
while ($row = $STH->fetch()) {
$storeArray[] = $row['Adresse'];
}
while ($row = $STHNAMES->fetch()) {
$nameArray[] = $row['numero-agence'];
}
echo json_encode(
Array("theAddress" => $storeArray,
"theName" => $nameArray)
);
}
catch(PDOException $e) {
echo 'There was an issue inserting thing into database: '.$e->getMessage();
}
?>
My question is : is there a way to combine the two queries and still have an associative array to send back to the client JSON-encoded ? (I am querying this bit of PHP with an ajax call, and need the resulting data)
Thanks.
Can be done in the same query:
# statement handle (prevents injection)
$STH = $DBH->prepare("SELECT Adresse, `numero-agence` FROM Agences");
$STH->execute();
$storeArray = Array();
$nameArray = Array();
while ($row = $STH->fetch()) {
$storeArray[] = $row['Adresse'];
$nameArray[] = $row['numero-agence'];
}