I'm trying to retrieve an email address from a table in MySql using $keyword (keyword can be anything in the question field) to identify the row. I am successful in finding the row I need with the query below but it returns the entire row, how does one pull just the email out of the row and store it as $email?
Query:
$result = mysql_query("SELECT * FROM ask WHERE date = '$keyword' order by ask_id")
or die(mysql_error());
Table:
| ask_id | store | fname | lname | email | phone | city| state | zip_code |question | sku | date |
Just select only the column you need email instead of them all *
$result = mysql_query("SELECT email FROM ask WHERE date = '$keyword' order by ask_id")
Note that mysql_* function are deprecated, better to switch to either mysqli or PDO. So you will be able to use prepared statements and you will avoid any risk of mysql injection, learn more here How can I prevent SQL injection in PHP?
SELECT `email` FROM ask WHERE date = '$keyword' order by ask_id
Use code above instead. SELECT * FROM... in your mysql statement means select everything.
$result = mysql_query("SELECT columnName AS email FROM ask WHERE date = '" . $keyword . "' ORDER BY ask_id");
while($row = mysql_fetch_assoc($result)){
$row['email']; // Here Do Anything With Email...
}
First off, the obligatory mysql_* commands are deprecated, don't use them, kittens will die and your dog will get shot etc. For more on that, please see this question.
If you only want to retrieve one column from your MySQL database you can do so by specifying the column after your SELECT, instead of an asterisk. So you would have a query as follows:
SELECT email FROM ask WHERE date = '$keyword' order by ask_id
You can use this as follows in PHP code:
$result = mysql_query("SELECT email FROM ask WHERE date = '$keyword' order by ask_id")
or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
var_dump($row);
}
To reiterate, you should not be using the mysql_* functions. There are superior replacements available, as detailed in the question referenced above.
Related
i have the following table for new_supplier_request:
Id | ref | User | Manager (Varchar)
1 12 James Henry O'Brien
I also have my internal_users table:
Id | User_firs_name | user_last_name(Varchar)
1 Henry O'Brien
i am using the following mysql query to give a manager permission (who is logged in) to view some content if the managers name appears for that row of data in the manager column of my new_supplier_request table
$_SESSION['username'] = internal_users.user_first_name
$_SESSION['username2'] = internal_users.user_last_name
$user = $_SESSION['username']." ".$_SESSION['username2'];
$sql34 = "select * from new_supplier_request, internal_users where new_supplier_request.status!= 'complete' and new_supplier_request.action_taken ='none' AND new_supplier_request.user_id = internal_users.user_id AND requestee_manager = '$user'";
$result = $conn->query($sql34);
For some reason this works fine if the last name does not contain an apostrophe, but because this managers last name is O'Brien for some reason when i check in my query it is failing because it is having difficulty reading the apostrophe in the name, if i change henry's last name to something like James then it works. can someone please explain what i am doing wrong? Thanks
You should consider using PDO's prepared statements with bound parameters.
This way, your requests would be safer and a lots of problem with string parameters should be solved.
$query = $pdo->prepare('
select *
from new_supplier_request, internal_users
where new_supplier_request.status <> :status
and new_supplier_request.action_taken = :action_taken
AND new_supplier_request.user_id = internal_users.user_id
AND requestee_manager = :user
');
$query->bindValue(':status', 'complete');
$query->bindValue(':action_taken', 'none');
$query->bindValue(':user', $user);
$query->execute();
$results = $query->fetchAll();
Check this one:
$_SESSION['username'] = mysqli_real_escape_string($conn, internal_users.user_first_name);
$_SESSION['username2'] = mysqli_real_escape_string($conn, internal_users.user_last_name);
Pass $conn->real_escape_string($user) instead of $user in the query. You should NEVER use variable values directly in the query without enforcing a type or escaping them as you will leave the code vulnerable to SQL injection attacks.
I have been researching for days now. I always get something like this (this is what I think is the best answer):
SELECT `COLUMN_NAME`
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA`='yourdatabasename'
AND `TABLE_NAME`='yourtablename';
Yeah this one runs perfectly in SQL, but I still have no idea how I will create a PHP script to show it the same way as it does in SQL. Can anyone give me a code?
I'm really confused right now. Please help..
without PDO:
$sql = "SHOW FIELDS FROM users;";
$result_sql = mysql_query($sql) or die ("Error!\n");
while ($row = mysql_fetch_array($result_sql)) {
echo $row['Field']."<br>\n";
}
Apparently you need to retrieve data from a mysql table and then do stuff with it in php. There are several ways to do this, here is my favorite:
<?php
$query="SELECT `COLUMN_NAME`
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA`='yourdatabasename'
AND `TABLE_NAME`='yourtablename'";
$result=mysql_query($query); //This will store the whole result table in $result
$rows=array(); //Initialize array
while($row=mysql_fetch_object($result)) $rows[]=(object) $row; //Store each row of the result table in the array $rows
//Now you can access, for example, the third row and second column by saying:
echo $rows[2]->name_of_second_column
?>
Also refer to this tutorial. on how to retrieve data from a database and manipulate it afterwards.
you can do this by in mysql mysql_field_name()
Use of mysql_* is discouraged so use either pdo or mysqli
with them you can do this by
mysqli_fetch_field_direct() //for mysqli
PDOStatement::getColumnMeta() //for pdo
for example after OP comment
$sql = "SELECT * from Person";
$result = mysql_query($sql,$con);
$name = mysql_field_name($result, 0);
explanation how to use the mysql_field_name()
Syntex
mysql_field_name(data,fieldOffset)
+------------+------------------------------------------------------------------+
| data | Required. Specifies which data pointer to use. The data |
| | pointer is the result from the mysql_query() function |
+------------+------------------------------------------------------------------+
|fieldOffset |Required. Specifies which field to start returning. 0 indicates |
| |the first field |
+------------+------------------------------------------------------------------+
good read
PDO Tutorial for MySQL Developers
I'm trying to Implement the facebook registration. It works and i'm getting back all the data I need. Now I want to assign a username to the user like this:
$username = ''.$first_name.'.'.$lastname.'';
The problem is that I don't know if a user with the same name and last name will register to the website and i would like to check if the username is taken and add a sequence number to the basic $username (facebook does the same), like this:
name.lastname
name.lastname.1
name.lastname.2
etc
I tried with:
$temp_username = ''.$first_name.''.$last_name.'';
$check_username = mysql_query("SELECT username FROM users WHERE username = '$temp_username'");
$num_rows = mysql_num_rows($check_username);
if ($num_rows == 0){
$username = strtolower($temp_username);
} else {
$username = strtolower(''.$temp_username.'.'.$num_rows.'');
}
but of course it doesn't work because there is always just one user with that username.
EDIT*** this is how I fix it (thanks to zander):
$temp_username = ''.$first_name.''.$last_name.'';
$num_rows = mysql_num_rows(mysql_query("SELECT username FROM users WHERE username = '$temp_username' OR username LIKE '$temp_username%' "));
$username = strtolower(''.$temp_username.'.'.$num_rows.'');
$num_rows = mysql_num_rows(mysql_query("SELECT username FROM users WHERE username = '$temp_username' OR username LIKE '$temp_username.%' ")); will return the number of rows you actually expect. Then, use $username = strtolower(''.$temp_username.'.'.$num_rows.''); to get it done. No need of loops.
The following SELECT determines the user with the highest number if there are any
select max(reverse(SUBSTRING(reverse(username), 1, LOCATE('.', reverse(username))-1))) trail
from users
where username like 'John.Smith.%';
SQL Fiddle Demo
Add it to PHP like this
...
if ($num_rows == 0){
$username = strtolower($temp_username);
} else {
... query for the max number here
... concatenate the username with the max number
}
Ah and last but not least. Make sure your code is not vulnerable to SQL injection. Use bind parameters. Good start is this answer: Best way to defend against mysql injection and cross site scripting
There are many existing answers that correctly suggest using the LIKE operator in your WHERE clause. But there is one critical issue that none of the existing answers have addressed.
Two people could attempt to add the same username at the same (or nearly the same) time. Each would SELECT the count of existing usernames that are LIKE that name, and they each would generate the same number suffix, and you still get duplicates.
I am neither a mysql developer nor php developer, so I won't provide much in the way of specific syntax.
You will want to make sure your users table uses the InnoDB storage engine. Your code will need to:
START TRANSACTION
SELECT FOR UPDATE to make sure only one person can get the count of
a particular username at a given time
INSERT your new user
COMMIT your transaction.
See Select for update for more information.
Use this code instead:
$check_username = mysql_query("SELECT username FROM users WHERE username = '$temp_username' OR username LIKE '$temp_username.%' ");
example this will match:
johnsmith or joshnsmith.X where x will be 1 , 2 , 3 .......etc
DB Dump
CREATE TABLE Users (
`username` varchar(255) PRIMARY KEY,
`firstname` varchar(255),
`lastname` varchar(255)
);
INSERT INTO Users (`username`, `firstname`, `lastname`) VALUES (
'praveen.kumar', 'Praveen', 'Kumar'
),(
'praveen.kumar.1', 'Praveen', 'Kumar'
),(
'praveen.kumar.2', 'Praveen', 'Kumar'
);
Now to the SQL, we can do this way:
SELECT *
FROM `Users`
WHERE `username` LIKE "praveen.kumar%"
ORDER BY `username` DESC
Gives an output:
+-----------------+-----------+----------+
| USERNAME | FIRSTNAME | LASTNAME |
+-----------------+-----------+----------+
| praveen.kumar.2 | Praveen | Kumar |
| praveen.kumar.1 | Praveen | Kumar |
| praveen.kumar | Praveen | Kumar |
+-----------------+-----------+----------+
And you can get the latest one this way:
SELECT *
FROM `Users`
WHERE `username` LIKE "praveen.kumar%"
ORDER BY `username` DESC
LIMIT 1
The PHP Code:
<?php
# Outputs the largest number with that username.
$nextUser = substr($userNameFromDB, strrpos($userNameFromDB, "."));
$nextUser++;
?>
SQL Fiddle: http://sqlfiddle.com/#!2/ad149/1
Use the count() function and the like operator:
$check_username = mysql_query("
SELECT count(username)
FROM users
WHERE username like '$temp_username%'
");
It will return the number of existent names. No need to call mysql_num_rows.
You should use the count() function
$query = mysql_query("
SELECT count(user_name) cnt
FROM users
WHERE username = '$just_registered_username'
");
and then fetch the result using
$row = sql_fetchrow($query);
And then get the count of users as
$next_index = $row->cnt;
Then append it to the new username
$new_username = "{$just_registered_username}.{$next_index}";
Don't forget to add comments to your final code.
Also try and use PDO for database access.
If you want to find a user name that does not exist, you have to try combinations, until you find a non existing username.
Therefore, loop until you find a non existing name:
$temp_username = $first_name . $last_name;
$i=1;
$found = false;
while(!$found) {
$check_username = mysql_query(
"SELECT username FROM users WHERE username = '$temp_username'");
$found = mysql_num_rows($check_username);
if ($found){
$username = strtolower($temp_username);
}
else{
$temp_username = $first_name . $last_name . '.' . $i;
$i++
}
}
I'm trying to pull multiple rows from a single table. I'm trying to pull either all males or all females in different zip codes.
<?php
$zipCodes = array("55555", "66666", "77777", etc...);
$fetchUser = mysql_query("select * from users where gender = '$_POST[gender]' ".implode(" or zipCode = ", $zipCodes)." order by id desc");
while($var = mysql_fetch_array($fetchUser)) {
code...
}
?>
You should use IN on this,
SELECT ...
FROM tableName
WHERE gender = '$_POST[gender]' AND
zipCode IN (55555, 6666, 77777)
currently your code is vulnerable to SQL Injection. Please read on PDO or MySQLI extension.
Read more on this article: Best way to prevent SQL injection in PHP
PHP PDO: Can I bind an array to an IN() condition?
// Prevent SQL injection for user input
$fetchUser = mysql_query("select * from users where gender = '".filter_var($_POST[gender], FILTER_SANITIZE_STRING)."' OR zipCode IN (".implode(",", $zipCodes).") order by id desc");)
I have a table with 4 record.
Records: 1) arup Sarma
2) Mitali Sarma
3) Nisha
4) haren Sarma
And I used the below SQL statement to get records from a search box.
$sql = "SELECT id,name FROM ".user_table." WHERE name LIKE '%$q' LIMIT 5";
But this retrieve all records from the table. Even if I type a non-existence word (eg.: hgasd or anything), it shows all the 4 record above. Where is the problem ? plz any advice..
This is my full code:
$q = ucwords(addslashes($_POST['q']));
$sql = "SELECT id,name FROM ".user_table." WHERE name LIKE '%".$q."' LIMIT 5";
$rsd = mysql_query($sql);
Your query is fine. Your problem is that $q does not have any value or you are appending the value incorrectly to your query, so you are effectively doing:
"SELECT id,name FROM ".user_table." WHERE name LIKE '%' LIMIT 5";
Use the following code to
A - Prevent SQL-injection
B - Prevent like with an empty $q
//$q = ucwords(addslashes($_POST['q']));
//Addslashes does not work to prevent SQL-injection!
$q = mysql_real_escape_string($_POST['q']);
if (isset($q)) {
$sql = "SELECT id,name FROM user_table WHERE name LIKE '%$q'
ORDER BY id DESC
LIMIT 5 OFFSET 0";
$result = mysql_query($sql);
while ($row = mysql_fetch_row($result)) {
echo "id: ".htmlentities($row['id']);
echo "name: ".htmlentities($row['name']);
}
} else { //$q is empty, handle the error }
A few comments on the code.
If you are not using PDO, but mysql instead, only mysql_real_escape_string will protect you from SQL-injection, nothing else will.
Always surround any $vars you inject into the code with single ' quotes. If you don't the escaping will not work and syntax error will hit you.
You can test an var with isset to see if it's filled.
Why are you concatenating the tablename? Just put the name of the table in the string as usual.
If you only select a few rows, you really need an order by clause so the outcome will not be random, here I've order the newest id, assuming id is an auto_increment field, newer id's will represent newer users.
If you echo data from the database, you need to escape that using htmlentities to prevent XSS security holes.
In mysql, like operator use '$' regex to represent end of any string.. and '%' is for beginning.. so any string will fall under this regex, that's why it returms all records.
Please refer to http://dev.mysql.com/doc/refman/5.0/en/pattern-matching.html once. Hope, this will help you.