PDO Query question - php

I need help finishing this statement. It is frustrating that two of the PHP phone books here gloss over PDO's almost all together.
All I need to do is check the database for a username that is already taken.
Here is the start of the statement.
$sql = " SELECT * FROM users WHERE userid = '$userid'";
$result = $dbh->query($sql);
What parts do I need to add to write my 'if' statement?

Something like this:
$sql = " SELECT * FROM users WHERE userid = '$userid'";
$result = $dbh->query($sql);
$row = $result->fetch();
if ($row)
echo 'Userid is taken';
I'm not sure about your question because you're asking about username but selecting userid... did you mean to select on username?

Related

why wont this query delete details from all tables? [duplicate]

This question already has an answer here:
PHP PDO how to run a multiple query request?
(1 answer)
Closed 3 years ago.
I am trying to delete records from tables matching users ID while i delete the user. but somehow it deletes records only from the cv table.
what i am trying is
if($_GET['deluser'] !='1'){
$qr = "delete from members where member_id IN(".$_GET['deluser'].")";
$qr = "delete from company where caller_id IN(".$_GET['deluser'].")";
$qr = "delete from cv where agent_id IN(".$_GET['deluser'].")";
$st = $db->prepare($qr);
$st->execute();
header('Location: users.php?action=DELETED');
exit;
what could i be doing wrong?
In your case you overwrite the value in $qr every time so you need to execute it, everyone of them separately,
you need also to fix the SQL injection problem so you can fix it
by using bind your data in the execute method or by using bindParam
first, you need to add ? with the same number of input you want to pass
you can check how it work here in this answer
$in = str_repeat('?,', count(explode(',', $_GET['deluser'])) - 1) . '?';
$qr = "delete from members where member_id IN($in)";
$st = $db->prepare($qr);
$st->execute(explode(',', $_GET['deluser']));
$qr = "delete from company where caller_id IN($in)";
$st = $db->prepare($qr);
$st->execute(explode(',', $_GET['deluser']));
$qr = "delete from cv where agent_id IN($in)";
$st = $db->prepare($qr);
$st->execute(explode(',', $_GET['deluser']));
You can read more about BindParam and Execute in the docs

What is the best way to check if something exists with PDO [duplicate]

This question already has answers here:
Row count with PDO
(21 answers)
Closed 5 years ago.
Some one told me rowCount not safe so I like to ask it here, I have 2 examples and like to know what is the safest and nice way to check if something exists?
$sql = "SELECT count(*) FROM users WHERE username = 'administrator'";
$result = $db->prepare($sql);
$result->execute();
echo $result->fetchColumn() ? 'true' : 'false';
or
$sql = "SELECT username FROM users WHERE username = ?";
$result = $db->prepare($sql);
$result->execute(array('administrator'));
echo $result->rowCount() ? 'true' : 'false';
The best way to check it with prepare and fetchColumn
SELECT COUNT(*) statement with the same predicates as your intended
SELECT statement, then use PDOStatement::fetchColumn() to retrieve the
number of rows that will be returned.
$sql = "SELECT COUNT(*) FROM users WHERE username = ?";// use `COUNT(*)`
$result = $db->prepare($sql);
$result->execute(array('administrator'));
echo $result->fetchColumn() ? 'true' : 'false';
SELECT 1 FROM users WHERE username = 'administrator' LIMIT 1
Using rowCount() isn't unsafe, but just improper.
The #1 rule when working with databases is
Always select the exact data you need.
with as less post-processing as possible.
So if you need to check whatever data for existence, then ask your database to check and then fetch the result.
However, you have to keep in mind that there are 2 possible scenarios:
In case you indeed need to check wherever something exists in a database, but don't need the data, then (assuming username has an unique index on it):
$sql = "SELECT 1 FROM users WHERE username = ?";
$result = $db->prepare($sql);
$result->execute(array('administrator'));
echo $result->fetchColumn() ? 'true' : 'false';
But often you need the data itself if it happens to be found. In this case you just select that data:
$sql = "SELECT * FROM users WHERE username = ?";
$result = $db->prepare($sql);
$result->execute(array('administrator'));
$user = $result->fetch();
echo $user ? 'true' : 'false';
I am stressing on it because the wording of the other answer suggests that you have to run 2 queries: one to check the existence and one to get the data, which is a nonsense.
As of the rowCount() method - you need it too seldom to talk about.

PHP : Error in SQL query

hello i have a question about some SQL query that keep give me an error
Code :
$result = mysql_query("SELECT email FROM users WHERE user_id='$uid' and set emailchange=1");
the query keep giving me an error
any help ?
Try following query
$result = mysql_query("SELECT email FROM users WHERE user_id=$uid and emailchange=1");
You can also update after select the data:
$result = mysql_query("SELECT email FROM users WHERE user_id='$uid' and set emailchange=1");
if($result){
$result2 = mysql_query("UPDATE email set emailchange=1 WHERE user_id='$uid'");
}
The error is caused by the set here:
and set emailchange=1
You can't select and update in the same SQL statement, you need to execute the update statement then write a select statement to grab the email - assuming that is what you mean to do so:
Update the field:
$result = mysql_query("UPDATE users set emailchange = 1 where user_id='$uid'");
select the data:
$result2 = mysql_query("select email from users where user_id='$uid'");
You really should escape $uid before passing it to the query and ideally you should be using PDO!

PHP - Unable to retrieve data from the database

For some reason, the query when run through PHP will not return the results. I have tried both queries in the MySQL command line, and they work perfectly there. Here is the code (mysql_connect.php is working perfectly, to clarify).
<?php
error_reporting(-1);
// retrieve email from cookie
$email = $_COOKIE['email'];
// connect to mysql database
require('mysql_connect.php');
// get user_id by searching for the email it corresponds to
$id = mysqli_query($dbc,"SELECT user_id FROM users WHERE email=$email")or die('couldn\'t get id');
// get data by using the user_id in $id
$result = mysqli_query($dbc,"SELECT * FROM users WHERE user_id=$id")or die('couldn\'t get data');
//test if the query failed
if($result === FALSE) {
die(mysql_error());
echo("error");
}
// collect the array of results and print the ones required
while($row = mysql_fetch_array($result)) {
echo $row['first_name'];
}
?>
When I run the script, I get the message "could not get id", yet that query works in the MySQL command line and PHPMyAdmin.
Your code won't work for 2 reasons - $id will not magically turn into integer, but a mysqli result. And email is a string so it should be quoted.
But...
Why is all of that?
If you want to fetch all the data for user, for certain email, just make you second query fetch data by email and remove the first one:
SELECT * FROM users WHERE email='$email';
And don't forget to escape your input, because it's in cookie. Or, use prepared statements as suggested.
Your query is not valid, you should rewrite it with the following and make sure your you have mysqli_real_escape_string of the $email value before you put it into queries:
SELECT user_id FROM users WHERE email='$email'
Better approach is to rewrite your queries using MySQLi prepared statements:
Here how to get the $id value:
$stmt = mysqli_prepare($dbc, "SELECT user_id FROM users WHERE email = ?");
mysqli_stmt_bind_param($stmt, "s", $email);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $id);
mysqli_stmt_fetch($stmt);
You wrote
mysqli_query($dbc,"SELECT user_id FROM users WHERE email=$email");
that is similar to
mysqli_query($dbc,"SELECT user_id FROM users WHERE email=example#example.com");
but it should be
mysqli_query($dbc,"SELECT user_id FROM users WHERE email='example#example.com'");
so you have to do this
mysqli_query($dbc,"SELECT user_id FROM users WHERE email='$email'");
or better
mysqli_query($dbc, 'SELECT user_id FROM users WHERE email=\'' . $email . '\'');
Beside this minor bug
You should be aware of SQL injection if someone changes the value of your cookie.

how do i check for mysql database table field value in creating a query?

if($_SESSION['usergroup']==1) { //admin
$result = mysql_query("the select statement which is written a certain way. this part is not what question is about") or die(mysql_error());
}
else if($_SESSION['userid']==1013) { //managers
$result = mysql_query("the select statement which is written a certain way. this part is not what question is about") or die(mysql_error());
}
else { //everyone else
$result = mysql_query("the select statement which is written a certain way. this part is not what question is about") or die(mysql_error());
}
so what i would like to do is to change this line here:
else if($_SESSION['userid']==1013) {
i want to check if the logged in user has a value of 1 in the user_table in a field called manager. the pseudo code would be something like:
else if(user_table manager field == 1) {
or
else if(if logged in user has a value of 1 in the manager field of the user_table table) {
does this sound like something that can be done?
what i'm trying to accomplish is to edit users and make certain users managers, but i don't want to have to keep editing php files to keep adding those new users every time i make a user a manager. i just want the users that have been upgraded to have access to that middle query automatically.
here is what i don't want to do...
else if($_SESSION['userid']==1013 || $_SESSION['userid']==1014 || $_SESSION['userid']==1015 || $_SESSION['userid']==1016) {
...and keep adding and adding to this line in this fashion.
That definitely sounds like something that can be done. I would use something like this, using PDO to prepare and then execute the statement.
//Prepare the SQL query, using the :user_id parameter which you'll supply in the next statement
$stmt = $con->prepare('SELECT manager FROM user_table WHERE userid = :user_id');
//Execute the SQL, supplying the parameter
$stmt->execute(array(':user_id' => $_SESSION['userid'])'
//Retrieve the value
$manager_role = $stmt->fetchColumn();
Or, you can do the same thing without using PDO by preparing your SQL query before running it.
$sql_query = 'SELECT manager FROM user_table WHERE userid = ' . $_SESSION['userid'];
$manager_role = = mysql_query($sql_query);
....
//Your original code
if($_SESSION['usergroup']==1) { //admin
$result = mysql_query("the select statement which is written a certain way. this part is not what question is about") or die(mysql_error());
}
else if($manager_role == 1) { //managers
$result = mysql_query("the select statement which is written a certain way. this part is not what question is about") or die(mysql_error());
}
else { //everyone else
$result = mysql_query("the select statement which is written a certain way. this part is not what question is about") or die(mysql_error());
}
....

Categories