I am created a prepared select query and it appears the query is not picking up the DESC or I have the bind_param structured wrong. I am trying to get the last id of the user_id's image to display. The user's image displays, but it is the first id image they have. I tried doing ASC and it was the same thing.
Am I doing this right?
$sql = "
SELECT *
FROM profile_img
WHERE user_id = ?
ORDER BY ? DESC LIMIT 1
";
if ($stmt = $con->prepare($sql)) {
$stmt->bind_param("ss", $user_id, `id`);
$stmt->execute();
if (!$stmt->errno) {
// Handle error here
}
$stmt->bind_result($id, $user_id, $profilePic);
$pics = array();
while ($stmt->fetch()) {
$pics[] = $profilePic;
}
echo '<img id="home-profile-pic" src=" '.$profilePic.'">';
}
I don't think you can :
Use placeholders in an order by clause
Bind column names : you can only bind values -- or variables, and
have their value injected in the prepared statement.
You can use number instead of field name in the 'order by' clause
Why you have put ? after "order by" statement?
Your order by should reference to either id of your "profile_img" table or any timestamp field in that table...
e.g. $sql = "
SELECT *
FROM profile_img
WHERE user_id = ?
ORDER BY id DESC LIMIT 1
";
here replace id (i am assuming this name) with the primary key field name of profile_image table
or
$sql = "
SELECT *
FROM profile_img
WHERE user_id = ?
ORDER BY created_on DESC LIMIT 1
";
here created_on (which i have also assumed) can be replaced by any timestamp field if you any in profile_img table
Related
I am planning to execute an update statement using a prepared statement that makes use of a dynamically changing number of columns. for eg: in the first update statement I update only name and age of a table. in the second instance, I update age, city, state, country..etc. in the next instance, I update 150 columns like this.
can someone provide me what is the perfect approach for this in java?
following is the example
If the user provides input for name and age then I update
UPDATE table1 set name = <> ,age = <>;
If the user provides input for city name state country and pin then the update statement should be like this-
UPDATE table1 set name = <>, city = <>,state= <>,country=<>, pin = <>;
Build your sql query like this
update demotable set col1 = case when #col1 is null then col1 else #col1 end
OR
Here #col is passed as value from front end.
from which you may create dynamic sql
declare #col1 nvarchar(max) /// from front you can pass your column value with its column name like: col1 = 'col1'
declare #Query = 'update demotable set = ' + #col1 /// it create query as update demotable set col1 = 'col1'
PREPARE stmt1 FROM #Query ;
EXECUTE stmt1
DEALLOCATE PREPARE stmt1;
I am new to MYSQL but this logic will surely work.
You can write one statement like this:
UPDATE table1
SET name = COALESCE(?, name),
age = COALESCE(?, age),
city = COALESCE(?, city),
. . .
Notes:
This assumes that the values are not being set to NULL.
The ? is a placeholder for a parameter. Don't munge query strings with user input.
Presumably you want a WHERE clause to limit what rows get updated.
Here i made table called sub_master with column sub_id and name, insertion and deletion working perfectly fine with this, so put those functions here as well to get reference for update function
and i'm using PostgreSQL for this.
In command line UPDATE query is working fine and query as:
UPDATE school_submaster SET name ='' WHERE sub_id = ;
private void InsertRowActionPerformed(java.awt.event.ActionEvent evt)
{
String query = "INSERT INTO school_submaster (sub_id, \"name\") VALUES ("+SidInput.getText()+",'"+SnameInput.getText()+"')";
executeSQlQuery(query, "Inserted");
}
private void UpdateRowActionPerformed(java.awt.event.ActionEvent evt)
{
String query = "UPDATE school_submaster SET 'name' ='"+SnameInput.getText()+"'+WHERE sub_id = "+SidInput.getText();
executeSQlQuery(query, "Updated");
}
private void DeleteRowActionPerformed(java.awt.event.ActionEvent evt)
{
String query = "DELETE FROM school_submaster WHERE sub_id = "+SidInput.getText();
executeSQlQuery(query, "Deleted");
}
Only use single quotes for string and date constants. Never use single quotes around column names or table names.
Your update is:
UPDATE school_submaster
SET 'name' ='<something>'+WHERE sub_id = "+SidInput.getText();
This has the additional issue of a + in the query string. It should look ore like:
UPDATE school_submaster
SET name = '<something>'
WHERE sub_id = "+SidInput.getText();
But even that is not true. You need to learn to use parameters to pass parameters into queries. The query should be some variant of:
UPDATE school_submaster
SET name = ?
WHERE sub_id = ?
Where the ? is a placeholder for a parameter (it might also be #name or something else).
You are missing a space in the sql WHERE clause, so add it as shown below:
String query = "UPDATE school_submaster SET 'name' ='"+
SnameInput.getText()+"' WHERE sub_id = "+SidInput.getText();
Hi I have been trying to select more than one rows by calling the procedure through CallableStatement. While I am trying to populate the result set to the combo box the code returns the error as follows.
Java Error:
java.sql.SQLException: Subquery returns more than 1 row
Stored Procedure :
CREATE DEFINER=`user_name`#`%` PROCEDURE `GET_USER_PROFILE`(
IN p_user_id VARCHAR(150),
IN p_role VARCHAR(150),
OUT p_user_data VARCHAR(200),
OUT p_city VARCHAR(150),
OUT p_state VARCHAR(150),
OUT p_country VARCHAR(150),
OUT q_Msg VARCHAR(150))
BEGIN
DECLARE available INT DEFAULT 0;
SET p_city = (SELECT CITY FROM countries GROUP BY CITY);
SET p_state = (SELECT STATE FROM countries GROUP BY STATE);
SET p_country = (SELECT COUNTRY FROM countries GROUP BY COUNTRY);
SELECT COUNT(EMAIL) INTO available FROM STAFF_PROFILE WHERE EMAIL = p_user_id AND ROLE = p_role;
IF(available=1) THEN
SET p_user_data = (SELECT * FROM STAFF_PROFILE WHERE EMAIL = p_user_id AND ROLE = p_role );
else
SET q_Msg = 'USER_LOGGED_FIRST';
END IF;
END
#DaveHowes and #Ilya are correct, the issue is with your SQL statement.
Lets say in your Countries table consists of the following:
city state country
'New York' 'New York' 'USA'
'Los Angeles' 'California' 'USA'
'Chicago' 'Illinois' 'USA'
'Ottawa' '' 'Canada'
Now, if we take your sub queries from your example:
SELECT city FROM countries GROUP BY city
would return:
city
'New York'
'Los Angeles'
'Chicago'
'Ottawa'
You're trying to assign a multiple results to a varchar hence you get the exception "Subquery returns more than 1 row".
Im trying to create an SQL Statement that will differentiate between employees types. For example if the Boolean Type Manager Column is checked it will return. Im using the info to fill a Manager on Duty JCombo in Java.
Im trying
String sql = "SELECT Employees.Name FROM Employees WHERE Manager = 'true' ORDER BY Name ASC";
Cant seem to get it right.
In SQL the boolean field will be a bit so your SQL statement will need to be
String sql = "SELECT Employees.Name FROM Employees WHERE Manager = 1 ORDER BY Name ASC";
in SQL a boolean field is a bit field (0 or 1) so you have to check as:
String sql = "SELECT Employees.Name FROM Employees WHERE Manager = 1 ORDER BY Name ASC"
I have a table with the following fields :
PersonnelTable Table fields:
* FirstName
* LastName
* Address
* IdNumber
* UserName
* Password
* Status
In that table I allow duplicate records .
I want to remove one occurrence from that table where :
String sqlStatement = "DELETE FROM `PersonnelTable` WHERE `Password` = ? AND `UserName` = ? ";
m_prepared.setString(1, _password); // set the password
m_prepared.setString(2, _username); // set the user-name
int rowsAffected = m_prepared.executeUpdate();
But that query would remove all the records where Password = ? and UserName = ?
How can I remove only one record using that query ?
Thanks
The LIMIT clause can be used in UPDATE or DELETE statements too:
"DELETE FROM `PersonnelTable` WHERE `Password` = ? AND `UserName` = ? LIMIT 1"
How can I remove only one record using that query ?
You can use the "LIMIT 1" clause of mySQL's DELETE statement.
But if you want to remove all but last rows, you need to do this:
BEGIN TRANSACTION;
SELECT COUNT(*) FROM `PersonnelTable` WHERE `Password` = ? AND `UserName` = ? FOR UPDATE;
DELETE FROM `PersonnelTable` WHERE `Password` = ? AND `UserName` = ? LIMIT ?; # (last fetched count - 1)
COMMIT;