Fetch a single column by a multi select - php

I would save the id of each user in a session for get later name ... in my login system. I would do that on each login.
But the problem: If i Select more columns with the sql i cant fetch a single column.
How i can fetch one column even tough i selected more columns in the sql.
I tried something like that:
$sth->fetch(PDO::FETCH_ASSOC)['password']
But it isnĀ“t working on my code:
$sth = $X['dbh']->prepare("SELECT `password` `id` FROM `users` WHERE `uid` = :uid; ");
if (! $sth->execute(array(
':uid' => $X['param']['uid'],
))) {
//check for right name, passwort ...
}

How i can fetch one column even tough i selected more columns in the sql.
Nohow.
Either select only one column, or fetch all that you have selected. Otherwise it would make no sense to select.
And after fetching an array, you can access its members all right.
$user = $sth->fetch(PDO::FETCH_ASSOC);
$pass = $user['password'];
then later in the code you can use $user['id'] as well.

Related

How to insert a particular value from one database table into another using '$row'?

I am currently trying to make a system which selects a user at random from the table 'users' and appends it to another table 'agreeuser' or 'disagreeuser' depending on whether or not the user has the 'opinion' value of 'like' or 'dislike'. I am doing this by using $row to select the full row where the user has the opinion of 'like', but it doesn't seem to be adding the data stored in '$row[username]' to the 'user' column of the 'agreeuser' or 'disagreeuser' table.
I have already tried storing the '$row['username'] value as a variable and using this in the value aspect of the query, but it doesn't seem to have worked. I have also tried combining the INSERT and SELECT queries and it still has no effect. Can anyone tell me what I am doing wrong, please? :)
if($_SESSION['pageLoaded'] != "true") {
$selectLikesQuery = "SELECT * FROM users WHERE opinion = 'like' ORDER BY RAND() LIMIT 1";
$likeSelectorResult = mysqli_query($userConnect, $selectLikesQuery);
while($row = mysqli_fetch_assoc($likeSelectorResult)) {
$removeCurrentAgreeContent = "TRUNCATE TABLE agreeUser";
$addAgreeUserQuery = "INSERT INTO agreeUser (user) VALUE ('$row[username]')";
mysqli_query($chatConnect, $removeCurrentAgreeContent);
mysqli_query($chatConnect, $addAgreeUserQuery);
}
$selectDislikesQuery = "SELECT * FROM users WHERE opinion = 'dislike' ORDER BY RAND() LIMIT 1";
$dislikeSelectorResult = mysqli_query($userConnect, $selectDislikesQuery);
while($row = mysqli_fetch_assoc($dislikeSelectorResult)) {
$removeCurrentDisagreeContent = "TRUNCATE TABLE disagreeUser";
$addDisagreeUserQuery = "INSERT INTO disagreeUser (user) VALUE ('$row[username]')";
mysqli_query($chatConnect, $removeCurrentDisagreeContent);
mysqli_query($chatConnect, $addDisagreeUserQuery);
}
$_SESSION['pageLoaded'] = "true";
}
I need the username from 'users' to be inserted into the 'user' column of 'agreeuser'. Thanks for any help, and apologies if I'm doing something stupid :)
Why don't you use SQL views to just see needed data in "a virtual table", instead of creating duplicate data?
Views is a very helpful feature.
For example, make a SELECT query to find needed rows:
SELECT * FROM users WHERE opinion = 'dislike'
If this select suits you, just add:
CREATE OR REPLACE VIEW v_agreeUsers AS SELECT * FROM users WHERE opinion = 'dislike'
And make the same for users who agree:
CREATE OR REPLACE VIEW v_disagreeUsers AS SELECT * FROM users WHERE opinion = 'like'
To be honest, I don't understand why do you do random select and insert users only one by one.
In case you want to get only one and random user, just run this query after you've already created views mentioned upper:
SELECT * FROM v_agreeUsers ORDER BY RAND() LIMIT 1
SELECT * FROM v_disagreeUsers ORDER BY RAND() LIMIT 1
Good luck! :)

handling database with php best option

i am doing a mini project of social networking , i am having a doubt about table .
let see , i need to provide post in their page. to do this,should i have to create table for each user or just create one table and use it for multiple users (data can be fetched by selecting particular user name and display it in their page ).
which is the best way?
my php code:
<?php
$query="select * from table_name where user=$username order by time desc;";
?>
To answer your question
It's best to just use 1 table of users and have a separate able for your posts. Your users table should have all the information for each specific users with 1 unique value that is automatically generated by the MySQL database. (Use auto-increment) And in the posts table you should have all the data for each post with a user_id column that holds the unique value from the users table, this way you know who posted it.
Here is a mockup table structure:
Users table:
uid | name | email
Posts table:
uid | user_id | message
user_id in the posts table should always be equal to some uid in the users table.
Every single table should always have some unique value that is assigned its primary value
My real concern
I am very concerned with the security of your application. Prepared statements are WAY easier to use, and WAY more secure.
In the code snippet that you shared:
<?php
$query="select * from table_name where user=$username order by time desc;";
?>
this query is very insecure, as Bobby Tables would tell you. I'm not sure why type of database connection you are using, but I suggest PDO. I wrote a function that makes this very very easy, here is the snippet for that:
This is a file I usually call connection.php that you can import on any page you need to use your database.
<?php
$host = 'localhost';
$db = '';
$user = '';
$pass = '';
$charset = 'utf8';
$dsn = "mysql:host={$host};dbname={$db};charset={$charset}";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new PDO($dsn, $user, $pass, $opt);
function pdoQuery($query, $values = []) {
global $pdo;
if(!empty($values)) {
$stmt = $con->prepare($query);
$stmt->execute($values);
} else {
$stmt = $con->query($query);
}
return $stmt;
}
?>
This function allows you to EASILY use prepared statements by just
including the connection.php page and writing queries in a way that is
readable, clean, and secure. As I'm sure a lot of people reading this are not used to Prepared Statements or know how they
work, the rest of this post will explain that.
One of the biggest differences here is that instead of using String
Interpolation in
your query, you will set variables as question marks ?, so your
query looks like this: UPDATE table SET user=? instead of UPDATE
table SET user='$user' - and the variables will be sent later for
safety, so this prevents SQL Injection.
This it the way your query would look now:
pdoQuery("SELECT * FROM `table_name` WHERE user=? ORDER BY `time` DESC", [$username]);
This is basically how it works:
pdoQuery(string $query, array $variables)
If you pass no variables, it automatically uses the query() function, if you do pass variables it automatically binds and executes the statements. No matter what query you do, the function always returns the query as an object, so you can act on it using any method you can normally use on a PDO query after the execute.
If you know how these work, you can stop reading here :) I put some
exmaples below of some of the ways you can manipulate the return data
to do what you need to do.
This function returns the object of the query you requested, so if you wanted to loop through all of the results of your query you use it like this:
$stmt = pdoQuery("SELECT * FROM `table_name` WHERE `user`=? ORDER BY time DESC", [$username])->fetchAll();
foreach($stmt as $row) {
$row['name']."<br>";
}
Or if you just wanted to get a single column from a specific row, you could use it like this:
$username = pdoQuery("SELECT `username` FROM `users_table` WHERE uid=? ORDER BY `time` DESC", [$uid])->fetchColumn();
Which will return the username from user where uid=$uid as a string
or if you wanted several values from 1 specific row, you could do
$user = pdoQuery("SELECT `username`,`name`,`email` FROM `users_table` WHERE uid=? ORDER BY time DESC", [$uid])->fetch();
Which will return to $user as an array that has the username, name, and email of the user.
You can also use this function to INSERT, UPDATE, or basically any type of query you can think of. This is how you insert:
pdoQuery("INSERT INTO `table_name` (`name`,`col2`, `col3`) VALUES (?,?,?)", [$name, $col1, $col2]);
My PDO Class
Since writing this post, I have created a new database wrapper class called GrumpyPDO (Hosted on Github).
This class method returns the object of the query you requested, so if you wanted to loop through all of the results of your query you use it like this:
Fetch All
GrumpyPDO Long Syntax
$stmt = $db->run("SELECT * FROM `table_name` WHERE `user`=? ORDER BY time DESC", [$username])->fetchAll();
GrumpyPDO Short Syntax
$stmt = $db->all("SELECT * FROM `table_name` WHERE `user`=? ORDER BY time DESC", [$username]);
Loop:
foreach($stmt as $row) {
$row['name']."<br>";
}
Single Column Return
Or if you just wanted to get a single column from a specific row, you could use it like this:
//Long Syntax
$username = $db->run("SELECT `username` FROM `users_table` WHERE uid=? ORDER BY `time` DESC", [$uid])->fetchColumn();
//Short
$username = $db->cell("SELECT `username` FROM `users_table` WHERE uid=? ORDER BY `time` DESC", [$uid]);
Which will return the username from user where uid=$uid as a string
Entire Row Return
or if you wanted several values from 1 specific row, you could do
//Long Syntax
$user = $db->run("SELECT `username`,`name`,`email` FROM `users_table` WHERE uid=? ORDER BY time DESC", [$uid])->fetch();
//Short Syntax
$user = $db->row("SELECT `username`,`name`,`email` FROM `users_table` WHERE uid=? ORDER BY time DESC", [$uid]);
Which will return to $user as an array that has the username, name, and email of the user.
DML Queries
You can also use this function to INSERT, UPDATE, or basically any type of query you can think of. This is how you insert (All DML's are similar):
$db->run("INSERT INTO `table_name` (`name`,`col2`, `col3`) VALUES (?,?,?)", [$name, $col1, $col2]);

Can I count rows and get a column value at the same time with SQL?

I'm using a SELECT COUNT(*) in order to verify that a user exists with PHP PDO and MySQL. I'd also like to get a specific column value. There is only ever one value/row or no value/row per user.
I'm trying to do something like this:
$stmt = $link->prepare('SELECT COUNT(*) AND column FROM table WHERE user=:user');
What I'm hoping to get back is, 1, and the column value. Where I can then bind the column value to a variable.
If not, I'll have to first do the SELECT COUNT(*) then do another query to get the column name after verifying that the user and this column exists from the SELECT COUNT(*) query.
You just need to think a little.
"count(*)" is not a special method "to verify that a user exists". It's just a query where you select count because you just have no idea what to select else.
But as long as you have a column to select, you don't need no counts anymore.
Therefore, just select your value, and as long as you are getting it, you can tell that a user exists
$stmt = $link->prepare('SELECT column FROM table WHERE user=:user');
$stmt->execute([$user]);
$col = $stmt->fetchColumn();
if ($col) {
// user exists
$something = $col; // use $col as you wanted
}
While selecting count() and a column without a group by operator is a tricky query, and you should avoid it in general.
SELECT count(*), column FROM table where user=:user
It's what you want no ?
Otherwise you can count the number of result in php
$pdo = new PDO('mysql:host=XXX.fr.mysql;dbname=YYYY', 'ZZZ', 'TTT', $pdo_options);
$response = $pdo->query('SELECT column FROM table');
$count = 0;
while ($data = $response->fetch())
{
$count++;
}
$reponse->closeCursor();

PHP/MySQL query deleting data but not re-inserting

I have this PHP Code:
$stmt = $pdo_conn->prepare("DELETE from tickets_extra_emails where ticketnumber = :ticketnumber ");
$stmt->execute(array(':ticketnumber' => $ticket["ticketnumber"]));
$cc_contact_line = '';
foreach(explode("\n", $_POST["cc_contacts"]) as $cc_contact_line) {
//then insert new if its not blank
if(filter_var($cc_contact_line, FILTER_VALIDATE_EMAIL)) {
//see if it currently exists
$stmt = $pdo_conn->prepare("SELECT * from tickets_extra_emails where ticketnumber = :ticketnumber and email_address = :email_address ");
$stmt->execute(array(':ticketnumber' => $ticket["ticketnumber"], ':email_address' => $cc_contact_line));
$records = $stmt->fetchAll(PDO::FETCH_ASSOC);
if(count($records) == 0) {
echo 'insert '.$ticket["ticketnumber"].' - '.$cc_contact_line.'<br>';
$stmt = $pdo_conn->prepare("INSERT into tickets_extra_emails (ticketnumber, email_address) values (:ticketnumber, :email_address) ");
$stmt->execute(array(':ticketnumber' => $ticket["ticketnumber"], ':email_address' => $cc_contact_line));
}
}
}
that makes each line of a textarea a variable in a foreach loop.
if i put lines in the textarea and submit the form, it saves the data but then if there is already data in and i submit the form, it removes it.
what do i have wrong in my code? I have commented everything it does
Theres a significant difference between MySQL INSERT and UPDATE.
You will need to check against the database where you are inserting to and use a query to check if there is data existing in that row. Based on that query you can restructure your insert statement to be conditional and switch from an INSERT to an UPDATE.
Deleting existing data will not allow you to re-insert into the rows, the rows are existing and therefor require UPDATE. However if you are removing whole rows then you can indeed re insert the rows. I see this as not entirely efficient, when you can utilize the efficiency of UPDATE to its benefit here.
AFAIK, fetchAll will fail if there are 0 rows, so you won't be able to run a count on the records. Do you have errors enabled or logged?
I see what you are trying to do and why you want to delete then reinsert, although maybe not the best approach.
Update: Apparently rowCount() shouldn't be relied on for selects, so I think the best alternative is to change your select query to select a count. This will always return a value as long as the query is valid so you shouldn't have to worry about the fetch failing. As you noticed below, I just changed the SELECT * to a SELECT count(*) so this will count how many rows match your constraints. Then use fetchColumn() to select the first column of the first row (the count).
$stmt = $pdo_conn->prepare("SELECT count(*) from tickets_extra_emails where ticketnumber = :ticketnumber and email_address = :email_address ");
$stmt->execute(array(':ticketnumber' => $ticket["ticketnumber"], ':email_address' => $cc_contact_line));
$records = $stmt->fetchColumn();

Show data from a specific row in MySQL

I'm building a simple bug tracking tool.
When you create a new project, all the info you fill in in the form, gets stored in the database.
When you create the new project you get redirected to a unique project page.
On top of the page it shows the name of the project, but it's not the name of the project I just created, it always shows the name of the first project in the MySQL table.
How can I show the name of the project I just created?
With this query I retrieve the data from the database.
$query = "SELECT CONCAT(name)
AS name FROM projects";
$result = #mysql_query ($query)
With this I show the project name, but it always shows the name of the first record in the table.
<?php
if ($row = mysql_fetch_array ($result))
echo '<h5>' . $row['name'] . '</h5>';
?>
It isn't yet SQL Injection prove and is far from complete... But I'm really struggling with this problem.
You need an AUTO_INCREMENT field on your table for a unique identifier (at least, you really should). Then you can do something like this:
<?php
$sql = new MySQLi('localhost', 'root', '', 'database');
$sql->query('INSERT INTO `projects` (`name`) VALUES ("Test Project");');
$projectID = $sql->insert_id; // Returns the auto_increment field value of the last insert query performed
// So this assumes you have a field in your table called "id" in this example
$res = $sql->query('SELECT CONCAT(`name`) AS `name` FROM `projects` WHERE `id` = '.$projectID.';');
if ($row = $res->fetch_assoc()) {
echo '<h5>'.$row['name'].'</h5>';
}
?>
Since you were calling for a redirect to the unique project page, you should have something like this: header("Location: project.php?id=$projectID");
Then, on project.php, you can attempt to fetch the project with the query above, only your query's WHERE clause should be something like:
'`id` = '.intval($_GET['id']).';'
Technically, you could pass all the project info along to the next page as a request or a session cookie and save yourself a query altogether. Just make sure you keep the id handy so it's easy to update the record.
Try using ORDER BY.
$query = "SELECT CONCAT(name)
AS name FROM projects ORDER BY id DESC";
This would show the most recent project (assuming you have an ID column).
However, a much better way is to have an ID variable on the page.
$query = "SELECT CONCAT(name)
AS name FROM projects WHERE id=?";

Categories