PHP PDO result from query - php

I am trying to do a query in PHP PDO where it will grab a simple result. So like in my query I need it to find the row where the column group is 'Admin' and show what ever is in the group column. I know that we already know what it should be [Should be admin] but just need to get the query to work. Its only grabbing 1 row from my table, so will I need forsearch?
If I change WHERE group = 'Admin' to WHERE id = '1' it works fine. But I need it so it can be where group = 'admin'
$sql2 = "SELECT * FROM groups WHERE group = 'Admin'";
$stm2 = $dbh->prepare($sql2);
$stm2->execute();
$users2 = $stm2->fetchAll();
foreach ($users2 as $row2) {
print ' '. $row2["group"] .' ';
}
Thanks

group is a reserved word in MySQL, that's why it's not working. In general it's a bad idea to use reserved words for your column and table names.
Try using backticks around group in your query to get around this, so:
$sql2 = "SELECT * FROM groups WHERE `group` = 'Admin'";
Also you should really use placeholders for values, because you're already using prepared statement it's a small change.
Edit: just to clarify my last remark about the placeholders. I mean something like this:
$sql2 = "SELECT * FROM groups WHERE `group` = ?";
$stm2->execute(array('Admin'));

try to use wildcard in your WHERE Clause:
$sql2 = "SELECT * FROM groups WHERE group LIKE '%Admin%'";
Since the value in your table is not really Admin but Administrator then using LIKE and wildcard would search the records which contains admin.

Related

Column number in mysql 'WHERE' condition

How is it possible to select the first column in the Where clause. I am trying to make a php function to retrieve table data based on the id, yet since the titles of the id columns are different in various tables, I need to refer to the first column in the Where clause as the first column is always the id column.
The scenario would be something like the following, but it throws errors and says that there is an error in the SQL syntax.
$stmt = $this->conn->prepare("SELECT * FROM $table WHERE column(1) = :id");
Thanks in advance.
I don't think there's a built-in way to do this. But you can query INFORMATION_SCHEMA.COLUMNS to get the column names.
$col_stmt = $this->conn->prepare("
SELECT column_name
FROM information_schema.columns
WHERE table_schema = DATABASE()
AND ordinal_position = 1
AND table_name = :table");
$col_stmt->execute([':table' => $table]);
$first_col = $col_stmt->fetchColumn();
$stmt = $this->conn->prepare("SELECT * FROM `$table` WHERE `$first_col` = :id");
Since there is no built-in way to do this, I came up with the following code block to get the first column and then use it in my SELECT statements.
$stmt = $this->conn->query("SHOW columns FROM $table");
return $stmt->fetch(PDO::FETCH_LAZY)[0];
I think this strategy is a bit shorter than Barmar's, though his is completely right and to the point.

php/mySQL: querying records by id from array?

i want to query several records by id like:
$ids = array(10,12,14,16,....);
the query would be something like:
select * from users where id=10 or id=12 or id=14 or id=16 ..
is it possible to query it in a more comfortable way like (compared to php):
select * from user where in_array(id, array(10,12,14,16))
thanks
You can use IN instead of OR clauses
select * from users where id IN (put_your_array_here)
Example:
select * from users where id IN (10,12,14,16);
Note:
According to the manual for MySQL if the values are constant IN
sorts the list and then uses a binary search. I would imagine that
OR evaluates them one by one in no particular order. So IN is
faster in some circumstances.
Related post
Try this.
$id = array(10,12,14,16,....);
$ids = join("','",$id);
$sql = "select * from user where id IN ('$ids')";
OR
$ids = implode(',', $id);
$sql = "select * from user where id IN ($ids)";
You can do it like that using implode in PHP:
"select * from users where id in '".implode("','", $ids)."'"
Please be sure that your ids are safe though

using where statement with a sequence of ids

In my table, I have a column that it has a set of users id. its name is users_id.
each id separated with a comma(,).
ex : users_id = '1,2,3,4,5';
if I passed $id=1 to my function, how can I using where statement ?
function($id){
$sql = "select * from content_noti
where ??????"
}
You can add a leading and a trailing , in the field value in DB.
e.g.
Change
1,2,3,4,5
to
,1,2,3,4,5,
So that every Id has leading and trailing comma ,
Now, update the function body:
function($id){
$sql = "select * from content_noti
where users_id LIKE '%,$id,%'"
}
In this case you don't have any possibility of mistake as if you search user id 1 then you will get only 1 and not 11 or 111 or 1343.
Working Demo
if you have multiple ids than it would be better to use IN with query
$sql = "select * from content_noti where id IN (?)"
if you are looking for reverse than use find_in_set
$sql = "select * from content_noti where FIND_IN_SET(?, id)";
You can use regular expressions in mysql:
function($id){
$sql = "SELECT * FROM content_noti WHERE users_id REGEXP '(^|,)" . $i . "($|,)'";
}
SELECT * from content_noti where users_id = "1" OR users_id = LIKE '%1,%' OR users_id = LIKE '%,1%'
Storing multiple chunks of data as a single comma seperated colum is really poor design for databases and if at all possible you should look into normalizing this by making a coupling table and joining on that.
The performance of the above query will be terrible and it'll be hard to maintain.

MySQL selecting from two tables in the same query

I am trying to select everything from two different mysql tables. I imploded an array called friends so that I can select everything about the user's friends from both tables. Originally I wanted to perform one query on one table and then in a while loop a query on the other. But that didn't work. If you know I way I can nest while loops then please be sure to comment/answer this question.
Here's my code:
$friends = implode("','", $friends);
//implode the friends array for sql query
$sql = mysqli_query($con, "SELECT * FROM users, text_post WHERE username IN ('$friends')") or die(mysqli_error($con));
while ($row = mysqli_fetch_assoc($sql)) {
echo $row['last_name']. ' ' . $row['body'];
echo '<br><br>';
}
Note: $row['last_name'] is from the users table and $row['body'] is from the text_post table. I am receiving this error whenever I run my code Column 'username' in where clause is ambiguous
Please help me.
UPDATE:
I changed my query to: $sql = mysqli_query($con, "SELECT * FROM users, text_post WHERE users.username IN ('$friends')") or die(mysqli_error($con)); but now it echo's every match twice:
parker hello
parker hello
simms what is up
simms what is up
simms it's raining
simms it's raining
jorge potato
jorge potato
Why is it doing that?
The only thing that is the same in both tables is the username.
Thanks for your question. The issue here is the error that you are receiving of:
Column 'username' in where clause is ambiguous.
What this means is that the statement that you are running is too obscure.
What you need to do to avoid this is to explicitly define the tables and columns that you are attempting to access and thus be implicit in your statements.
As a rule of thumb try and always define your columns in the following format:
{table_name}.{column_name}
With that being said the following should work:
$friends = implode("','", $friends);
/* implode the friends array for sql query. */
$sql = mysqli_query($con, "SELECT * FROM users, text_post WHERE users.username IN ('$friends') AND text_post.username IN ('$friends')") or die(mysqli_error($con));
while ($row = mysqli_fetch_assoc($sql)) {
echo $row['last_name']. ' ' . $row['body'];
}
Also I would also recommend that you use PHP's PDO Object as appose to the mysqli_query method.
I trust this helps.
both tables have a username. specify it using table.username
apparently both tables have the same column, and you are not prefixing the username column with either table name.
Maybe what you want is a union?
Use table prefix users in where block i.e. users.username
$sql = mysqli_query($con, "SELECT * FROM users, text_post WHERE users.username IN ('$friends')") or die(mysqli_error($con));
Try this:
$friends = implode("','", $friends);
//implode the friends array for sql query
$sql = mysqli_query($con, "SELECT users.last_name,text_post.body FROM users, text_post WHERE username IN ('$friends')") or die(mysqli_error($con));
while ($row = mysqli_fetch_assoc($sql)) {
echo $row['last_name']. ' ' . $row['body'];
}
Your logic would work were it not for username being present in both tables. Because it is, you need to alias your table names so that you can uniquely identify which column you're trying to use in the where clause:
SELECT * from users AS u, text_post as tp
WHERE u.username IN(....)
or shorter:
SELECT * from users u, text_post tp
WHERE u.username IN(....)
As a side note, it's bad practice to SELECT *, you should always explicitly select the columns you want, otherwise your code may crash if you add a column to a table later and forget to update your for loop to include/ignore any changed columns.

PHP: MySQL Select with multiple Where [duplicate]

This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 8 years ago.
I looked mostly everywhere on Stackoverflow for adding multiple WHERE instances but none of them seem to work.
My Select query:
$result = mysql_query("SELECT * FROM $tableName WHERE user = $user AND column = 1"); //query
I tried IN and some other ways but I dont know why it wont get the column. If I take out the user column it works, but I want it to also restrict to the column as well..
Any help will be appreciated!
column is reserved word in mysql. You have to use ` around that kind of column_name and use ' single quotes around string data '$user'
SELECT * FROM $tableName WHERE user = '$user' AND `column` = 1
You need to wrap the username in single-quotes & as mentioned by Yogesh column is a reserved keyword in MySQL. Try this:
user = '$user' AND `column` = 1
So the whole statement becomes:
$result = mysql_query("SELECT * FROM $tableName WHERE user = '$user' AND `column` = 1");
Also, you should be using mysqli or PDO with prepared statements instead.
Rewrite your query. Use the below code:
$result = mysql_query("SELECT * FROM `".$tableName."` WHERE user = '".$user."' AND `column` = 1");
And here I am missing that what is column in query is it name of column?
And you need to give the value in single quota and table name in ` till mark.
try this one:
$sql = 'SELECT * FROM $tableName WHERE user = "'.$user.'" AND `column` = 1';

Categories