can't print single item in a array - php

I don't know what's going on here.
I have this piece of code.
$data = getDataBySession($_COOKIE["session"],$db);
echo $data['name'];
print_r($data);
?>
function.php
function getDataBySession($session, PDO $db){
$query = "SELECT name,
lastname
FROM users
WHERE cookie = :id
";
$query_params = array(
':id' => $session
);
try{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex){
echo "Error > " .$ex->getMessage();
}
$dataUser = $stmt->fetchAll();
return $dataUser;
}
print_r return this: Array ( [0] => Array ( [name] => JOSE [lastname] => SUAREZ ) )
But echo can't show it's content, nor print.
I don't belive it's the function because it returns the array, as you can see.
What am i doing wrong?

Related

Construct http_build_query with PDO and Select

I am trying to create an http_build_query array but it is inserting some diferent characters, this is my Code:
function Conectar(){
try{
$opcoes = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8');
$con = new PDO("mysql:host=localhost; dbname=*****;", "*****", "*****", $opcoes);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $con;
} catch (Exception $e){
echo 'Erro: '.$e->getMessage();
return null;
}
}
$pdo = Conectar();
$sql = "
SELECT dominio
FROM dominios_extraidos
WHERE verificado='0' LIMIT 3
";
$stm = $pdo->prepare($sql);
$stm->execute();
while ($rows = $stm->fetch()) {
$query = http_build_query(array(
'domains' => array(
''.$rows['dominio'].'',
)
));
print_r($query);
}
Creating this output:
domains%5B0%5D=0002021web.com.br%0Adomains%5B0%5D=007import.com.br%0Adomains%5B0%5D=00pet.com.br%0A
But this is my desire output:
domains%5B0%5D=0002021web.com.br&domains%5B1%5D=007import.com.br&domains%5B2%5D=00pet.com.br
My desire output could be generated manually using this code:
$query = http_build_query(array(
'domains' => array(
'0002021web.com.br',
'007import.com.br',
'00pet.com.br',
)
));
print_r($query);
Thank you for your time :)
You want to build up your array properly first, so that it looks like your manual array, then use http_build_query:
$domains = ['domains' => []];
while ($rows = $stm->fetch()) {
$domains['domains'][] = trim($rows['dominio']);
}
$query = http_build_query($domains);
print_r($query);
Create an array of domains in the loop and then after the loop is complete pass it as a param to the http_build_query().
while ($rows = $stm->fetch()) {
$doms[] = trim($rows['dominio']);
}
$query = http_build_query( ['domains' => $doms] );
print_r($query);
This will produce
domains%5B0%5D=0002021web.com.br%0A&domains%5B1%5D=007import.com.br%0A&domains%5B2%5D=00pet.com.br%0A
which equates to
domains[0]=0002021web.com.br
&domains[1]=007import.com.br
&domains[2]=00pet.com.br
0A decoded is \n or Line Feed;
perhaps try sanitizing first with
$query= trim($query, "\x00..\x20\x7F");
this code remove ASCII character from 00 to 20 hex and 7f hex

Function that is supposed to return a value from query

I have this function which I use to get a value from a query. I might be doing something wrong with the execution, or the syntax. When I try to run the query with the data in it, it's fine, but this one returns 0 items.
public function get_modified_event ($type, $id, $employee_id)
{
global $dbh;
$sql =<<<SQL
SELECT outlook_id
FROM dba.events
WHERE spine_item_type = :type
AND spine_id = :id
AND employee_id = :employee_id
SQL;
$stmt = $dbh->prepare( $sql );
$stmt->execute( array(
'id' => $id,
'type' => $type,
'employee_id' => $employee_id,
) );
$rows = $stmt->fetchAll( \PDO::FETCH_ASSOC );
return $rows['outlook_id'];
}
You could try reworking a portion of the code so that it uses this kind of a format:
$stmt = $dbh->prepare( $sql );
if ($stmt->execute( /* your array goes here */ )) {
$rows = $stmt->fetchAll( PDO::FETCH_ASSOC );
if ($rows !== FALSE){
print_r($rows);
}
else
if ( $stmt->rowCount() === 0) {
echo "The info provided is unknown to the database";
}
}
Hopefully you'll get some meaningful results.

Mysql - Get Last inserted ID is not working

I dont know why this is not working. The LAST_INSERT_ID() is not being catched, can someone help me please?
$query = "
INSERT INTO products_categories (
name,
url
) VALUES (
:name,
:url
) SELECT LAST_INSERT_ID();
";
$query_params = array(
':name' => $_POST['name'],
':url' => $_POST['url']
);
try{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex){
echo 0;
return true;
}
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$id_category = $result["id"];
"You can remove your SELECT LAST_INSERT_ID() part from the query and use $db->lastInsertId(); instead." - #barell
Try this;
<?php
$query = "
INSERT INTO products_categories (
name,
url
) VALUES (
:name,
:url
)
";
$query_params = array(
':name' => $_POST['name'],
':url' => $_POST['url']
);
try{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex){
echo 0;
return true;
}
$result = $stmt->fetch(PDO::FETCH_ASSOC);
//$id_category = $result["id"];
$id_category = $db->lastInsertId();
Hope it helps

How to edit multiple rows?

I have tables like this:
-artists
-djs
-track_artist
-track_dj
I am adding two or more artists/djs while adding song via multiple select box. But I couldn't find how to edit those rows.
Adding song function:
$sql = "INSERT INTO sarki (sarki_isim, sarki_tarz, sarki_file, sarki_resim, sarki_eklenmetarihi) VALUES (:isim, :tarz, :file, :resim, NOW())";
$sqlartist = "INSERT INTO trackartist (trackartist_artist, trackartist_track) VALUES (:artistid, :trackid)";
$sqldj = "INSERT INTO trackdj (trackdj_dj, trackdj_track) VALUES (:djid, :trackid)";
try {
$stmt = $this->db->prepare($sql);
$stmt->execute(array(':isim' => $b["isim"], ':tarz' => $b["tarz"], ':file' => $b["file"], ':resim' => $b["resim"]));
$trackid = $this->db->lastInsertId();
foreach ($b["artists"] as $artist) {
$insert = $this->db->prepare($sqlartist);
$insert->execute(array(":artistid" => $artist, ":trackid" => $trackid));
}
foreach ($b["djs"] as $artist) {
$insert = $this->db->prepare($sqldj);
$insert->execute(array(":djid" => $artist, ":trackid" => $trackid));
}
$db = null;
return $stmt;
} catch (PDOException $e) {
echo $e->getMessage();
}

PHP - Mysqli | i'm trying to output data but i keep getting empty array

i'm trying to get user information from database, but it keep giving me an empty array.
code : i.stack.imgur.com/Op4HB.png
$information = array();
$user = 'admin';
$myuser = new mysqli(HOST, USER, PASSWORD, DATABASE);
if ($info = $myuser->prepare("SELECT id,username,email,bd,firstname,lastname,gender,ppicture,cpicture FROM members WHERE username = ?")) {
$info->bind_param("s", $user);
/* execute query */
$info->execute();
/* get result */
$result = $info->get_result();
/* bind result variables */
$info->bind_result($information['id'],$information['username'],$information['email'],$information['birthday'],$information['first_name'],$information['last_name'],$information['gender'],$information['profile_picture'],$information['cover_picture']);
$info->fetch();
$rows = $result->num_rows;
$info->close();
}
if (!$rows) {
redirect('http://example.com/');
} else {
print_r($information);
}
this is what i get :
can someone help me in this ? i use mysqli all the time but i don't know what went wrong this time.
thanks.
Try this
Fetch & display the results inside the while loop
if ($info = $myuser->prepare("SELECT id,username,email,bd,firstname,lastname,gender,ppicture,cpicture FROM members WHERE username = ?")) {
$info->bind_param("s", $user);
/* execute query */
$info->execute();
/* get result */
$result = $info->get_result();
/* bind result variables */
$info->bind_result($information['id'],$information['username'],$information['email'],$information['birthday'],$information['first_name'],$information['last_name'],$information['gender'],$information['profile_picture'],$information['cover_picture']);
$rows = $result->num_rows;
}
if (!$rows) {
redirect('http://example.com/');
} else {
while ($info->fetch()) {
print_r($information);
}
}
EDIT
if ($info = $myuser->prepare("SELECT email FROM members WHERE username = ?")) {
$info->bind_param("s", $user);
/* execute query */
$info->execute();
/* bind result variables */
$info->bind_result($email);
$info->fetch();
printf("%s \n", $email);
}
i fixed it myself
i found the answer at http://php.net
thanks anyways !
<?php
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$query = "SELECT id,username,email,bd,firstname,lastname,gender,ppicture,cpicture FROM members WHERE username = ?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("s", $user);
$stmt->execute();
$res = $stmt->get_result();
$rows = $res->num_rows;
$information = $res->fetch_assoc();
if($rows == 0 ) {
redirect("http://example.com");
}
print_r($information);
?>
PS: account.php is being required by index.php so it gets '$user' from there
output
Array ( [id] => 15 [username] => admin [email] => admin#theboat.tn [bd] => 2017-02-07 [firstname] => Saif [lastname] => Eddin [gender] => male [ppicture] => 1f4c1b47a3910039e60851c453ae4d80_a.jpg [cpicture] => default_c.jpg )

Categories