Generate a simple array of username using PDO - php

My Database
id username
1 xxx
2 bbb
3 vvv
4 bbbbbb
i need output as
array('xxx','bbb','vvv','bbbbb');
Using PDO i need to fetch username from db & make that to array, is to for checking username exists

If you're only checking if a username exist, it would be optimal to modify your query to do just that, instead of returning excess data:
$query = $pdo->prepare("SELECT `id` FROM `users` WHERE `username` = ? LIMIT 1");
$query->execute(array($username_to_test));
if ($query->rowCount() == 1)
{
// user exists in table
}
If you do happen to need an array of usernames, do something like the following:
$usernames = array();
$query = $pdo->query("SELECT `username` FROM `users`");
while(($row = $query->fetchObject()) != null)
$usernames[] = $row->username;

$pdo = new PDO($dsn,$user,$pass);
$pdos = $pdo->prepare('select username from mytablename');
$pdos ->execute();
$results = array();
while ($row = $pdos->fetch(PDO::FETCH_ASSOC)) {
$results[] = $row['username'];
}
var_dump($results);
Set Your database $dsn, $user and $pass before according to doc.

To do exactly what you've asked:
$query = $dbh -> prepare("SELECT username from users");
if ($query -> execute()){
$user_array = $query -> fetch(PDO::FETCH_ASSOC);
}
Tim Cooper's answer is probably a better solution though.

Related

how can i get the value of COUNT(id)

I'm encountering a problem with this object. I don't know (if it is possible), how to get the value of COUNT(id).
I tried $req[0]->COUNT(id) but "COUNT()" it detected it as a function. How could it be detect as a key?
Here's a var_dump($req):
object(stdClass)[4]
public 'COUNT(id)' => string '1' (length=1)
PHP
$req = $db->query('SELECT COUNT(id) FROM `users` WHERE username ="'.$username.'" AND password = "'.$password.'"');
if($req == 1){
$_SESSION['authentificated'] = true;
$_SESSION['username'] = $username;
}
var_dump($req);
The output of the query should be 0 or 1 if the user is already register or not.
1.You need to add alias for COUNT()
2.After query execution you need to fetch record and then do the comparison
Do like below:-
$req = $db->query('SELECT COUNT(id) as count FROM `users` WHERE username ="'.$username.'" AND password = "'.$password.'"');
$result = mysqli_fetch_assoc($req); // sample example,you need to change accordingly
if($result['count'] == 1){
//your code
}
Note:-
Saving plain password is very bad idea. so use password hashing
Your current code is wide-open for SQL INJECTION. To prevent from it use prepared statements
mysqli::prepare
PDO::prepare
I will do it something like this: https://3v4l.org/YOBGX
Here alias required or else it won't capture that count value the way you want.
$req = $db->query('SELECT COUNT(id) cnt FROM `users` WHERE username ="'.$username.'" AND password = "'.$password.'"');
var_dump($req);
Here is the solution you have not bind the key for that please see below
$req = $db->query('SELECT COUNT(id) as user_exists FROM `users` WHERE username
="'.$username.'" AND password = "'.$password.'"');
if($req == 1){
$_SESSION['authentificated'] = true;
$_SESSION['username'] = $username;
}
var_dump($req);
Try this --
$req = mysqli_query($db,'SELECT (COUNT(id)) as countID FROM `users` WHERE username ="'.$username.'" AND password = "'.$password.'"'));
$row = mysqli_fetch_array($req);
$countID = $row['countID'];
if($countID == 1){
$_SESSION['authentificated'] = true;
$_SESSION['username'] = $username;
}
var_dump($req);

How to display a column value with PDO in PHP and MySQL?

My code:
$db1 = new PDO ( 'mysql:host=localhost;dbname=db;charset=utf8', 'root', '');
$db1->setAttribute ( PDO::ATTR_ORACLE_NULLS, PDO::NULL_TO_STRING )
$qry = $db1->prepare('SELECT user_name FROM user_data WHERE user_id = $userid LIMIT 1');
$qry -> execute(array($userid));
$row = $qry -> fetch();
echo $qry -> user_name;
And it not eching nothing
And I want to find by $userid, and echo the user_name column(like user_id = 1 and it echo Name)
$db1 = new PDO ( 'mysql:host=localhost;dbname=db;charset=utf8', 'root', '');
$db1->setAttribute ( PDO::ATTR_ORACLE_NULLS, PDO::NULL_TO_STRING );
$qry = $db1->prepare("SELECT user_name FROM user_data WHERE user_id = ? LIMIT 1");
$qry -> execute(array($userid));
$row = $qry->fetch();
echo $row->user_name;
Change:
$qry = $db1->prepare('SELECT user_name FROM user_data WHERE user_id = $userid LIMIT 1');
For:
$qry = $db1->prepare('SELECT user_name FROM user_data WHERE user_id = ? LIMIT 1');
You will assign the value to user_id through execute statement
EDIT:
Add semicolon:
$db1->setAttribute ( PDO::ATTR_ORACLE_NULLS, PDO::NULL_TO_STRING ); <<<-- Missed semicolon

how do i implement update i pdo for the following mysql code?

here is my mysql code and equivalent pdo code i need to know what is wrong
$id = $_POST['id'];
$query1=mysql_query("SELECT Quantity,id FROM `yumyum`.`food` where `food`.`id` LIKE $id");
$r = array();
while($r = mysql_fetch_assoc($query1)) {
$output = $r['Quantity'];
echo $output;
$query2=mysql_query("UPDATE food SET Quantity = Quantity - 1 where `food`.`id` LIKE ".$r["id"]);
PDO code
$stmt = $db->prepare("SELECT * FROM yuymuym WHERE id=:id AND Quantity=:Quantity");
$stmt->execute(array($id, $Quantity));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC)
How about this. I don't know what $_POST['id'] is so you have to figure the rest youself. It updates every item with id in $ids array. So this updates items with id 1,2,3,4 and 5.
$db = new PDO('mysql:host=localhost;dbname=yumyum', 'username_here', 'password_here');
$ids = array(1,2,3,4,5);
foreach($ids as $id){
$stmt = $db->prepare("SELECT Quantity, id FROM `food` WHERE `food`.`id` = :id");
$stmt->bindParam(':id', $id);
$stmt->execute();
$row = $stmt->fetch();
if($row){
//uncomment to see $row content
//var_dump($row);
$rowId = (int)$row['id'];
$rowQuantity = (int)$row['Quantity'];
echo $rowQuantity;
$ustmt = $db->prepare("UPDATE `food` SET `Quantity` = `Quantity` - 1 WHERE `food`.`id` = :id");
$ustmt->bindParam(':id',$rowId);
$ustmt->execute();
}else{
var_dump($stmt->errorInfo());
}
}
But PDO basics:
Query (Works with select, insert, update, everything else):
$id = (int)$_POST['id'];
$else = $_POST['string'];
// Connect to database
$db = new PDO('mysql:host=HOST_HERE;dbname=DATABASENAME_HERE', 'USERNAME_HERE', 'PASSWORD_HERE');
// First we prepare our query
$stmt = $db->prepare("... WHERE `id` = :id AND `something` = :else");
// We bind values to our prepared query
$stmt->bindParam(':id',$id);
$stmt->bindParam(':else',$else);
// We execute our query
$success = $stmt->execute();
// If we want to fetch only one row:
$row = $stmt->fetch();
echo $row['id'];
// If we want to fetch all rows:
$rows = $stmt->fetchAll();
foreach($rows as $row){
echo $row['id'];
}
These are very basics, if you don't understand what is really happening here, you should learn some more.

SQL / PHP How to pull data from a table and place it in variable

Assuming I have a uniqid key in my table and that same key is sent to my site in a get method, how do I pull that specific key out and assign all the data from the table to variables. This is what I have so far but cant seem to figure it out.
$query1 = "SELECT *
FROM todo_item2 as ti INNER JOIN todo_category2 as tc ON ti.todo_id = tc.todo_id'
WHERE todo_id = :todo_id";
$statement1 = $db->prepare($query1);
$statement1 -> execute(array(
'todo_id' =>$id
));
while ($row = $statement1->fetch())
{
$text = $row['todo'];
$cat = $row['category'];
$percent = $row['precent'];
$date = $row['due_date'];
}
You should ready about what execute actually does .. the parameters to execute (and I assume you're using PDO or something similar here) are the tokens of the query. What you want is something like:
$query = " ... WHERE todo_id = ?"
$stmt = $db->prepare($query);
$stmt->execute(array($id));
while ($row = $stmt->fetch()) {
//$row is now an associative array of row values.
}
// Start the Load
$query1 = "SELECT *
FROM todo_item2 as ti INNER JOIN todo_category2 as tc ON ti.todo_id = tc.todo_id
WHERE ti.todo_id = :todo_id";
$statement1 = $db->prepare($query1);
$statement1 -> execute(array(
'todo_id' =>$id
));
// Make Sure the Data Exists
if( $statement1->rowCount() == 0 )
{
die('Please Enter a Valid ID Tag - (id)');
}
while($row = $statement1->fetch())
{
$text = $row['todo'];
$cat = $row['category'];
$percent = $row['percent'];
$date = $row['due_date'];
}

Query not returning correct results in function

The following function is set up to:
Collect the user_id from my database, as you can see below WHERE subscriber = '$user'. And then:
return the possible multiple values that user_id are.
However, when I've tried to use this function, it has only collected an array, with the key 0, and value user_id. For apparent reasons I want the array to contain the numerical value that is in the user_id column in my database with the key user_id.
function get_subscribitions($user)
{
$user = mysql_real_escape_string ($user);
$sql = "SELECT 'user_id' FROM `subscribe` WHERE subscriber = '$user'";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
mysql_free_result($result);
return $rows;
}
Can anyone please pinpoint where I'm making the error leading to these related problems?
Any help appreciated, thank you in advance!
It should be:
function get_subscribitions($user)
{
$user = mysql_real_escape_string ($user);
$sql = "SELECT user_id FROM `subscribe` WHERE subscriber = '$user'";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row['user_id'];
}
mysql_free_result($result);
return $rows;
}
There were unnecessary quotes in the query and you were not reading the $row array properly
Try instead
$sql = "SELECT user_id FROM `subscribe` WHERE subscriber = '$user'";
Notice the single quotes missing from around user_id

Categories