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.
Related
I am trying to use the selected id's as an array a other statement. It seems it is not counting all the result as it is much lower that it is.. I have tried to find my answer on google but none of the options are working for me or i do not know how to use them in my case. There are no errors and i have error log on!
Here is my code, what am i doing wrong?
$counttheid = array();
$stmt3 = $mysqli->prepare("SELECT
id
FROM account
WHERE level <= '5' AND door = ? AND `group_name` = ? AND betaald = 'Yes'");
$stmt3->bind_param("ss",$usernamesession,$groupname);
$stmt3->execute();
$result3 = $stmt3->get_result(); //only works when nd_mysli is set on the server!
while ($rowid = $result3->fetch_assoc())
{
$counttheid[] = $rowid['id'];
$countid = implode(',', $counttheid);
}
$sql = "SELECT SUM(mobcash) AS totalcash FROM account WHERE id IN (?)
";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s",$countid);
$stmt->execute();
$stmt->bind_result($row['totalcash']);
while($stmt->fetch()) $sumcash = $row['totalcash'];
//echo print_r($counttheid);
//echo implode(',', $counttheid);
echo $sumcash;
I am no profesional developer just started learning this, any help is welcome!
Since you have edited the question, my original answer is no longer relevant.
I suggest for you to simplify your two queries into a single query. In your first query you select a bunch of ids and in the second query you sum a different value from the same table using the ids. You can just to that in one query:
SELECT SUM(mobcash) AS totalcash
FROM account
WHERE level <= '5'
AND door = ?
AND `group_name` = ?
AND betaald = 'Yes';
Original answer
You use $result->fetch_all(MYSQLI_ASSOC), meaning each row from the result set will be an associative array with the column names as the keys and the cell values as values. That is also the case, if you only select one column.
That means for this example table
id | name | balance
----+------+---------
1 | acc1 | 12.34
2 | acc2 | 1.23
your variable $dataid will have the following value (for the simplified query SELECT id FROM account):
$dataid = [
[
"id": 1
],
[
"id": 2
]
];
To get more familiar with PHP, you could write some foreach loops yourself, but you can also use the built-in PHP function array_column (php.net: array_column):
$ids = array_column($dataids, "id");
From an SQL perspective I would also suggest for you to learn about nested queries, since you could avoid this PHP logic altogether.
I have tried upto end everything to the best of my knowledge but all in vain. I'm building a community website and i am stuck at one thing. I want to display a text on my wall when my friends become friends with other users. Just like Facebook displays it. For eg.
"John doe is now friends with max stone"
And
"John doe is now friends with max stone and 5 other people"
I am successfully getting it displayed but not like the one I showed above. I do it using while loop from notifications table. I tried but couldn't get it like facebook shows. so please help me get this thing done.
I am posting my code so that you can get clear idea of my code and my mistakes in my code so you can clear.
$ check_if_friendship_created = mysql_query ("SELECT * FROM `users_notifications`
WHERE `friend_1_username` IN (SELECT `friend_2_username` FROM `users_friends`
WHERE `friend_1_username` = '". $ logged_user ['username']."')
GROUP BY `friend_2_fullname` ORDER BY `notification_time` DESC");
also to let you all know that my friends table is a symmetrical in design...
looking forward to your positive reponse. Thank you....
why don't you have a separate table for friendship notification? Meaning when user1 is friend with user2 you insert the details to the friendship notification table.
table structure
id reqeust_sent_by request_accepted_by friendship_date
So let's assume John sends friend request and then Jack accepts the request, when Jack accepts the request then you insert that detail to the table. You better use mysqli prepared statements or pdo. So here is mysqli prepared statements
$request_sender = 'John';
$logged_user = 'Jack';
$date = date('Y-m-d H:i:s');
$mydabtase = new mysqli('localhost', 'root', '', 'database_name');
$stmt = $mydatabse->prepare("insert into friendship_notification (request_sent_by, request_accepted_by, friendship_date) values (?,?,?)");
$stmt->bind_param('sss' $request_sender, $logged_user, $date);
$stmt->execute();
$stmt->close();
now to select the data you can do
$stmt = $mydatabase->prepare("select * from friendship_notification where request_sent_by ! = ? or requst_accepted_by ! = ? order by id desc");//do your select here. here we are selecting where either rows are different from the logged in user because we don't want to show the logged in user that he has became friends with somebody else, we show this for other users.
$stmt->bind_param('ss', $logged_user, $logged_user);//follow the same procedure when binding the parameters, s means string. if you have 2 ? then you need 2 s along with 2 variables.
$stmt->execute();
$result = $stmt->get_result();//this gets the results
$total = $result->num_rows;//this returns the total number of rows for the above select query
while($row = $result->fetch_assoc()){
//if the total is less than 3 people we do the below
if($total < 3){
echo $row['request_accepted_by']."is now friends with".$row['request_sent_by'].",";
}
elseif($total > 3 ){
$stmt2 = $mydatabase->prepare("select * from friendship_notification where request_sent_by ! = ? or requst_accepted_by ! = ? order by id desc limit 1");//do your select here
$stmt2->bind_param('ss', $logged_user, $logged_user);
$stmt2->execute();
$result2 = $stmt2->get_result();
$row2 = $result2->fetch_array();//we only need one row so no need for while loop.
echo $row['request_accepted_by']."is now friends with".$row2['request_sent_by']."and ".$total-1." others.";
}
}
So this will display something like
John is now friends with Max and magna. and on the second case
John is now friends with Max and 4 others.
if you want the facebook way then you need to use ajax to auto refresh.
I'm trying to retrieve a filename from a database from table HORSE and column HORSE_IMAGE
$path = "horse_images/".$row["HORSE_IMAGE"];
$query = "DELETE FROM HORSE WHERE HORSE_ID=".$_GET["horseno"]." AND HORSE_IMAGE=".$row["HORSE_IMAGE"];
Currently HORSE_IMAGE returns nothing, but if I change it to HORSE_ID or HORSE_NAME, it works.
i.e. If i echo $row["HORSE_NAME"] it returns "You Beauty".
If I look up the row in the database I can see the filename shop-1.jpg is there.
Any ideas?
If you want to change a single column of a row, use an UPDATE statement. DELETE is for removing complete rows only. And yes, escape anything before using it in your query.
"UPDATE HORSE SET HORSE_IMAGE = NULL WHERE HORSE_ID=".(int)$_GET["horseno"];
As far as I understood the question, ToBe's answer might be correct, but you really should consider using PDO for MySql queries, in order to prevent Sql injection.
Try:
<?php
$query = "UPDATE HORSE SET HORSE_IMAGE = NULL WHERE HORSE_ID = ?";
$db = new PDO(dsn, username, password);
$prep = $db->prepare($query);
$res = $prep->execute(array((int)$_GET["horseno"]));
?>
Take a look at the documentation: http://php.net/manual/de/book.pdo.php
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.
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++
}
}