how can i print my password into three variables - php

Query is as below
$query = "SELECT password FROM passwordhistory where userid=? order by id desc limit 3";
$stmt2 = $mysqli->prepare($query);
$stmt2->bind_param('i',$id);
$stmt2->execute();
$res=$stmt2->get_result();
while($row=$res->fetch_object()) {
foreach($row as $t->password) {
echo $password[1];
}
}
In the above code I want print password in to three variables. I am not able to do this.

Change your code to this :
$i = 0;
while($row=$res->fetch_object())
{
foreach($row as $t->password)
{
echo $newPass.$i = $password[1];
$i++;
}
}

I think you can use str_split function.
foreach($row as $t->password)
{
$array = str_split($password[1],3);
}
Check the manual here

Related

How do I display content with PDO based on num_rows?

Apparently, the num_rows property does not work in PDO as it would with mysqli.
Normally, with mysqli, my code would look like this:
<?php
$conn = new mysqli('127.0.0.1','root','mypassword','mydbname');
if($conn->connect_errno){
die("Sorry, could not connect.");
}
$id = 1;
$qry = "SELECT * FROM customers WHERE id = ?";
$getCustomers = $conn->prepare($qry);
$getCustomers->bind_param("i",$id);
$getCustomers->execute();
$result = $getCustomers->get_result();
$count = $result->num_rows;
if($count == 0){
echo "Sorry, there are no results";
}else{
while($row = $result->fetch_object()){
echo $row->id;
echo $row->fname;
echo $row->lname;
echo $row->entry_date;
}
}
?>
How do I create the equivalent with PDO? Here is what I have tried so far:
<?php
try{
$conn = new PDO('mysql:host=127.0.0.1;dbname=mydbname','root','mypassword');
}catch(PDOException $e){
echo $e;
}
$id = 1;
$qry = $conn->prepare("SELECT * FROM customers WHERE id = :id");
$qry->execute([':id'=>$id]);
$rows = $qry->fetchAll(PDO::FETCH_OBJ);
$count = count($rows);
if($count == 0){
echo "Sorry, there are no results for your criteria";
}else{
for($i = 0; $i < $count; $i++){
echo $rows->fname;
}
}
?>
Yeah isn't PDO great ;p no need to count rows when you have already got them.
To loop over your result as you have an array.
Change:
for ($i = 0; $i < $count; $i++){
echo $rows->fname;
}
To:
for ($i = 0; $i < $count; $i++){
echo $rows[$i]->fname;
}
Or better just use a foreach.
foreach ($rows as $row) {
echo $row->fname;
}
The statement
fetchAll(PDO::FETCH_OBJ) returns an array containing all of the result set rows as described here. To get the size of the array use sizeof($count). That should give you the size of the array.
To answer your question specifically. You can use rowCount() to retrieve the number of rows in a result:
$qry = $conn->prepare("SELECT * FROM customers WHERE id = :id");
$qry->execute([':id'=>$id]);
$count = $qry->rowCount();
$rows = $qry->fetchAll(PDO::FETCH_ASSOC); //my personal preference
for($i=0; $i < $count; $i++) {
echo $rows[$i]['fname'];
}
To more closely replicate your mysqli code:
while($row = $qry->fetch(PDO::FETCH_OBJ) {
echo $row->fname;
}
Of course, you should always check $conn->errorCode() after each database execution to ensure something go sideways on you.
UPDATE:
As Lawrence points out, rowCount() does not work with MS SQL Server. An alternative in that case is to use fetchAll() and count().

PHP Mysql fetched data blank

Having a bit of an issue with my php code..
$stmt = $db->prepare("SELECT * FROM mytable WHERE TheGroup = :SearchName ORDER BY TheTime DESC");
$stmt->bindParam(':SearchName', $request, PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$count = count($result);
for ($i = 0; $i < $count; $i++) {
$mTheAvatar = $result[$i]->TheAvatar;
$mTheDirection= $result[$i]->TheDirection;
$mTheGroup = $result[$i]->TheGroup;
$mTheMedia = $result[$i]->TheMedia;
$mTheMessage = $result[$i]->TheMessage;
$mTheSenderName= $result[$i]->TheSenderName;
$mTheThumbImage = $result[$i]->TheThumbImage;
$mTheTime = $result[$i]->TheTime;
$mTheMediaExtension = $result[$i]->TheMediaExtension;
echo "hello";
echo $mTheAvatar;
echo " <- this is avatar";
}
If I do a Var_dump() I see the data being requested without a problem.
If I echo the variables , they are blank..
I have triple checked that the table column names are correct..
the $mTheAvater is a pic in table, if that gives a possible clue, but the rest are blank as well so not sure what is up?!?
You can test:
$mTheAvatar = $result[$i]['TheAvatar'];
As I know in the FETCH_ASSOC it returns data in above structure.
You are trying to read them as if they are objects, but PDOStatement::fetchAll returns an array, so your code should look like:
for ($i = 0; $i < $count; $i++) {
$mTheAvatar = $result[$i]['TheAvatar'];
$mTheDirection= $result[$i]['TheDirection'];
.
.
.
.
echo "hello";
echo $mTheAvatar;
echo " <- this is avatar";
}
If you want to handle objects, you should use PDOStatement::fetchObject
This should be better - 1) it's using foreach; 2) unset(); 3) different structure
$stmt = $db->prepare("SELECT * FROM mytable WHERE TheGroup = :SearchName ORDER BY TheTime DESC");
$stmt->bindParam(':SearchName', $request, PDO::PARAM_STR);
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
if($results){
foreach($results as $result_data) {
echo $result_data['TheAvatar'];
echo $result_data['TheDirection'];
//and so on
unset($result_data);
}
}
else{
echo 'Empty';
}

fetch multiple rows of same id in different variable

I have two rows contaning data of same id.
It has different adresses in different rows for the same id.
I want to fetch both the adress in different variable in php.
How can i do this? Please help!
Below is the code:
foreach($row_address as $address)
{
echo "<br> Address :" .$address;
$info=Array();
$data=explode(' ', $address );
$info[1]=$data[0];
$info[2]=$data[1];
$info[3]=$data[2];
echo "City :".$info[1];
echo "Country :".$info[2];
echo "Pin Code :".$info[3];
}
function hoteladdresstable($id)
{
global $conn;
/*$sql2 = "select AddressLine from hoteladdress where Hotel_Id= " .$id;
$result2 = mysql_query($sql2,$conn);
$row2 = mysql_fetch_assoc($result2,MYSQL_NUM);
return $row2;*/
$query = "select AddressLine from hoteladdress where Hotel_Id = " .$id;
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result))
{
$d[] = $row['AddressLine'];
}
return $d;
}
It gives me both the address of the same id in one variable only.
I want them in two different variables.
You are already getting an array of addresses in $d.
What you can do is:
$d = array();
while ($row = mysql_fetch_assoc($result)) {
$d[$row['Address_ID']] = $row['AddressLine'];
}
extract($d, EXTR_PREFIX_ALL, 'ad');
If you have address ids 2 and 4, you will get two variables
$ad_2 and $ad_4
You should use parameterized queries. Use PHP's PDO:
$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$STH = $DBH->prepare('select AddressLine from hoteladdress where Hotel_Id = :id');
$STH->bindParam(':name', $id);
$STH->execute();
$d = array();
while($row = $STH->fetch()) {
$d[] = $row['AddressLine'];
}
http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059
Don't want your queries getting injected with attacks.
I suggest you to use mysqli instead.
$data = array();
while($row = mysqli_fetch_assoc($result)){
$data[] = $row;
}
return $data;
and then
foreach($data as $oneRow){
echo $oneRow['AddressLine']; //and all other stuff that you want.
}
you can verify it:
print_r($data);

Getting PHP and MySQL to read url

So I want to be able to use a WHERE command in SQL to select certain values from a table. This is my current code however it doesn't work
$MobileNumber = $_GET["MobileNumber"];
$TeamGroup = $_GET["TeamGroup"];
if($_REQUEST=['MobileNumber']) {
$Item = "SELECT a,b,c,d FROM Item WHERE MobileNumber = $MobileNumber";
} elseif($_REQUEST=['TeamGroup']) {
$Item = "SELECT a,b,c,d FROM Item WHERE TeamGroup = $TeamGroup";
} else {
$Item = "SELECT a,b,c,d FROM Item";
};
$result = mysql_query($Item) or die ("Error in query: $query. ".mysql_error());
if (mysql_num_rows($result) > 0) {
$row = mysql_fetch_assoc($result);
print '<table><tr>';
foreach($row as $name => $value) {
print "<th>$name</th>";
}
print '</tr>';
while($row) {
print '<tr>';
foreach($row as $value) {
print "<td>$value</td>";
}
print '</tr>';
$row = mysql_fetch_assoc($result);
}
print '</table>';
} else {
echo "No Items Assigned";
};
It works for when the url is test.php?MobileNumber=... but not when its has TeamGroup or nothing in the url. The url I have is like this: test.php?TeamGroup=11
EDIT: Added more code to let you see what I am trying to display
if($_REQUEST=['MobileNumber']){ its a wrong syntax
Try this
add this line in your url ?MobileNumber=Put your mobile num here. Thanks
than for Team group again this ?TeamGroup=put team group here.
if($_GET['MobileNumber']==TRUE){
$MobileNumber=$_GET['MobileNumber'];
$Item = "SELECT a,b,c,d FROM Item WHERE MobileNumber = $MobileNumber";
}
elseif($_GET['TeamGroup']==TRUE){
$TeamGroup=$_GET['TeamGroup'];
$Item = "SELECT a,b,c,d FROM Item WHERE TeamGroup = $TeamGroup";
}
else{
$Item = "SELECT a,b,c,d FROM Item";
}
This statement:
if($_REQUEST=['MobileNumber'])
will always be true, because you're assigning the ['MobileNumber'] array to the $_REQUEST global.
If you're trying to check whether the values are set in the $_REQUEST global, do the following:
if( isset($_REQUEST['MobileNumber']))
If you want to compare something using if condition then it must be like this
if(something == true){
// then do something
}
else{
//do something
}
Check the manual for more
What you are trying to do is not a valid one in php.You need to change this
if($_REQUEST=['MobileNumber']){
I think you can try like this
if(isset($_GET['MobileNumber']) && trim($_GET['MobileNumber'])){
And
elseif(isset($_GET['TeamGroup']) && trim($_GET['TeamGroup'])){
this should work...
if(isset($_GET['MobileNumber'])) //can also use if(isset($_GET['MobileNumber']) && !empty($_GET['MobileNumber']))
{
$Item = "SELECT a,b,c,d FROM Item WHERE MobileNumber = ".$MobileNumber;
}
elseif(isset($_GET['TeamGroup']))
{
$Item = "SELECT a,b,c,d FROM Item WHERE TeamGroup = ".$TeamGroup";
}
else{
$Item = "SELECT a,b,c,d FROM Item";
}
You could try this:
$MobileNumber = $_GET["MobileNumber"];
$TeamGroup = $_GET["TeamGroup"];
if(isset($_GET["MobileNumber"])) {
//If you enclose fields/table in `` and values in '' you won't run into quoting issues
//It's OK to not quote numbers, but you can quote them to stay standard
$Item = "SELECT `a`, `b`, `c`, `d` FROM `Item` WHERE `MobileNumber` = '$MobileNumber'";
};
if(isset($_GET["TeamGroup"])) {
$Item = "SELECT `a`, `b`, `c`, `d` FROM `Item` WHERE `TeamGroup` = '$TeamGroup'";
};
if(!isset($_GET["MobileNumber"]) && !isset($_GET["TeamGroup"])) {
$Item = "SELECT `a`, `b`, `c`, `d` FROM `Item`";
};
//Switch to mysqli_*
$result = mysqli_query($dbLink, $Item) or die ("Error in query: $Item. " . mysqli_error());
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
print '<table><tr>';
foreach($row as $name => $value) {
print "<th>$name</th>";
};
print '</tr>';
while($row) {
print '<tr>';
foreach($row as $value) {
print "<td>$value</td>";
};
print '</tr>';
$row = mysqli_fetch_assoc($result);
};
print '</table>';
} else {
echo "No Items Assigned";
};
That
moves from mysql_* to mysqli_* (check my syntax - most of the mysqli_* functions are the same but there are a few differences)
uses isset & !isset to determine which query to use
encloses your query string in ticks and quotes to help make sure you don't forget to quote something properly
fixes your or die catch (you were referencing $query which didn't seem to exist)

php - function return values dynamically

I want to return a set of values from function till the point they exist....
for example....
function abc($i="3"){
for($a=1;$a<=$i;$a++) {
$name='t'.$i;
$$name = "ae".$a;
}
//now i am returning values
return array($t1,$t2,$t3,$t4,$t5,$t6,$t7,$t8,$t9,$t10);
//but i only want to return $t1,$t2,$t3 depending on $i
}
Thanks....
#therefromhere
I am also creating an array in the loop , I'll paste the original code so that you can understand it in a better way
function extracting_comments($table, $fields,$condition,$order,$limit){
$query="SELECT ".$fields."
FROM ".$table."
WHERE ".$condition."
ORDER BY ".$order."
LIMIT ".$limit." ";
if($stmt = $this->conn->prepare($query)) {
$stmt->execute();
$row = array_pad(array(), $stmt->field_count, '');
$params = array();
foreach($row as $k=>$v) {
$params[] = &$row[$k];
echo $params[0];
}
call_user_func_array(array($stmt,'bind_result'),$params);
$i=0;
while($stmt->fetch()) {
$i++;
$name='t'.$i;
$$name = array();
foreach ($row as $b=>$elem) {
$atul[$b]=$row[$b];
}
$$name=$atul;
}
return array($t1,$t2,$t3,$t4,$t5,$t6,$t7,$t8,$t9,$t10);
$stmt->close();
}
}
now their are only 5 rows of data so their is no point returning $t6,$t7,$t8,$t9,$t10
and i want to fix it ,and i am calling the function using
$extract=extracting_comments($table, $fields,$condition,$order,$limit);
please help...thanks
Just build the array in your for loop:
function abc($i=3) {
$array = array();
for ($a=1; $a<=$i; $a++) {
$array[] = "ae".$a;
}
return $array;
}
After you edited your question an revealed us your actual problem, see here my proposal:
function extracting_comments($table, $fields, $condition, $order, $limit) {
$retVal = array();
$query = "SELECT ".$fields."
FROM ".$table."
WHERE ".$condition."
ORDER BY ".$order."
LIMIT ".$limit." ";
if ($stmt = $this->conn->prepare($query)) {
$stmt->execute();
$row = array_pad(array(), $stmt->field_count, '');
call_user_func_array(array($stmt, 'bind_result'), $row);
while ($stmt->fetch()) {
$retVal[] = $row;
}
$stmt->close();
return $retVal;
}
}
I believe this will help you. You have very complicated code with a lot of side effects and bug, you'd better to consider to redisgn it. Also putting statements after return will no have any effect, since it wouldn't be invoked.
function extracting_comments($table, $fields,$condition,$order,$limit){
$query="SELECT ".$fields."
FROM ".$table."
WHERE ".$condition."
ORDER BY ".$order."
LIMIT ".$limit." ";
if($stmt = $this->conn->prepare($query)) {
$stmt->execute();
$row = array_pad(array(), $stmt->field_count, '');
$params = array();
foreach($row as $k=>$v) {
$params[] = &$row[$k];
echo $params[0];
}
call_user_func_array(array($stmt,'bind_result'),$params);
$i=0;
$result = array();
while($stmt->fetch()) {
$i++;
foreach ($row as $b=>$elem) {
$atul[$b]=$row[$b];
}
$result[]=$atul;
}
$stmt->close();
return $result;
}
}
It'd be cleaner to build the array as you go along, then you wouldn't need the temporary variables:
function abc($i="3") {
$myArray = array();
for($a=1;$a<=$i;$a++) {
$myArray[] = "ae" . $a; // add new values to the end of the array
}
return $myArray;
}
If you want to check if the variables exist (and are not null), use isset().

Categories