basic mysqli insert query not working - mysqli

Anyone can spot the problem with this query?
I am stuck on this little part of the project but just can't see the error.
$mysqli->query("INSERT INTO item (name, description, buyPrice, price, qty, brandID, primaryCategoryID, secondaryCategoryID, thirdCategoryID, supplierID) VALUES ('{$_POST['name']}', '{$_POST['description']}', '$buyPrice', '$price', '{$_POST['Qty']}', '{$_POST['brandID']}', '{$_POST['primaryCategoryID']}', '{$_POST['secondaryCategoryID']}', '{$_POST['thirdCategoryID']}', '{$_POST['supplierID']}')");
the query is just not working.
The following UPDATE query works perfectly tho, and im sure the $_POST variable are passed correctly in both cases:
$mysqli->query("UPDATE item SET name = '{$_POST['editInventoryName']}', description = '{$_POST['editInventoryDescription']}', buyPrice = '$buyPrice', price = '$price', brandID = '{$_POST['editInventoryBrand']}', supplierID = '{$_POST['editInventorySupplier']}', primaryCategoryID = '{$_POST['editInventoryPrimaryCat']}', thirdCategoryID = '{$_POST['editInventoryThirdCat']}', secondaryCategoryID = '{$_POST['editInventorySecondaryCat']}' WHERE id = '{$_POST['editInventoryID']}'");

Remove the brackets around the $_POST varibles:
$mysqli->query("INSERT INTO item (name, description, buyPrice, price, brandID, primaryCategoryID, secondaryCategoryID, thirdCategoryID, supplierID) VALUES ('".$_POST['name']."', '".$_POST['description']."', '".$buyPrice."', '".$price."', '".$_POST['brandID']."', '".$_POST['primaryCatergoryID']."', '".$_POST['secondaryCategoryID']."', '".$_POST['thirdCatgoryID']."', '".$_POST['supplierID']."')");

The problem was that a $_POST variable was passed empty and therefore the query did not execute.
Sorry for the dumb question coding for too many hours got to this! :)

Related

DynamoDB Swift4 complex query

I am trying to make a complex query in swift to get data from DynamoDB.
I am able to get all information by using the userID. However there are times that I may not know the entirety of the userID and need to make a more complex query.
For instance, if I know the first name and the last name, and the user id format is "firstname:lastname:email", I need to be able to query all userID's that include the first and last name, then add a where for another column.
I am very new to dynamo and want to accomplish something like the sql query below.
SQL example:
SELECT * FROM mytable
WHERE column2 LIKE '%OtherInformation%'
AND (column1 LIKE '%lastname%' OR column1 LIKE '%firstname%')
Here is the code I have in swift4 for getting the userID if I know it exaclty, not entirely sure how to modify this for complex queries.
func queryDBForUser(Fname: String, Lname: String) {
let userId = Fname + "." + Lname + ":" + (UIDevice.current.identifierForVendor?.uuidString)!
self.UserId = userId
let objectMapper = AWSDynamoDBObjectMapper.default()
let queryExpression = AWSDynamoDBQueryExpression()
queryExpression.keyConditionExpression = "#userId = :userId"
queryExpression.expressionAttributeNames = ["#userId": "userId",]
queryExpression.expressionAttributeValues = [":userId": userId,]
objectMapper.query(CheckaraUsers.self, expression: queryExpression, completionHandler: {(response: AWSDynamoDBPaginatedOutput? ,error: Error?) -> Void in
if let error = error {
print("Amazon DynamoDB Error: \(error)")
return
}
I have also tried many variations along the lines of the following code, with no luck:
queryExpression.keyConditionExpression = "#FirstName = :firstName and #LastName = :lastName,"
queryExpression.expressionAttributeNames = ["#FirstName": "FirstName" , "#LastName": "LastName"]
queryExpression.expressionAttributeValues = [":FirstName": Fname,":LastName": Lname]
Any help would be greatly appreciated, thanks in advance!
You won't be able to do this with a DynamoDB query. When you query a table (or index) in DynamoDB you must always specify the complete primary key. In your case that would mean the full value of "firstname:lastname:email".
You could sort of do this with a DynamoDB scan and a filter expression, but that will look at every item in your table, so it could be slow and expensive. Amazon will charge you for the read capacity necessary to look at every item in the table.
So if you really wanted to, the filter expression for the scan operation would be something like:
"contains (#FirstName, :firstName) and contains (#LastName, : lastName)"
Note that contains looks for an exact substring match, so if you want case insensitive matches (like ILIKE in SQL) it won't work.
If you need to do these types of queries then you need to evaluate whether or not DynamoDB is the right choice for you. DynamoDB is a NoSQL key/value store basically. It trades limited querying functionality for scalability and performance. If you are coming at DynamoDB from a SQL background and are expecting to be able to do freeform queries of anything in your table, you will be disappointed.
Got the query working by adding a secondary index to my DynamoDB table, although this is not what I initially wanted, it still works as now I can query for a value that exists in both columns I needed, without doing a table scan and filtering after.
query code:
queryExpression.indexName = "Index-Name" queryExpression.keyConditionExpression = "#LastName = :LastName and #otherValue = :otherValue"
queryExpression.expressionAttributeNames = ["#LastName": "LastName" , "#otherValue": "otherValue"]
queryExpression.expressionAttributeValues = [":LastName": Lname,":otherValue": self.otherValue!]

Why can't I create model based results from lync but I can do anything through SqlQuery?

Any idea why this doesn't work
return View((from u in db.Users
select new Models.Users()
{
Id = u.Id,
Username = u.Username,
Password = "-"
}).ToList());
And this works like a charm? :]
return View(db.Users.SqlQuery("SELECT Id, Username, '-' AS Password FROM Users"));
Since you didn't really give a ton of information I'm gonna take a shot in the dark. EF doesn't allow you to select to a class that represents a database entity. I'm assuming the Models.Users class is the same class being used in your db.Users? You should just be able to create like a UserDto with the same fields and I think that will work. If it doesn't give more info and I'll try to help more.

Laravel and Eloquent: Specifying columns in when retrieving related items

This is a followup post to: Laravel 4 and Eloquent: retrieving all records and all related records
The solution given works great:
$artists = Artist::with('instruments')->get();
return \View::make('artists')->withArtists($artists);
It also works with just:
$artists = Artist::get();
Now I'm trying to specify the exact columns to return for both tables. I've tried using select() in both the statement above and in my Class, like this:
ArtistController.php
$artists = Artist::select('firstname', 'lastname', 'instruments.name')->get();
or:
$artists = Artist::with(array('instruments' => function($query) {
$query->select('name');
}))->get();
(as suggested here and while this doesn't throw an error, it also doesn't limit the columns to only those specified)
or in Artist.php:
return $this->belongsToMany('App\Models\Instrument')->select(['name']);
How would I go about getting just the firstname and lastname column from the artists table and the name column from instruments table?
Not sure what I was thinking. I think working on this so long got me cross-eyed.
Anyhow, I looked into this a lot more and searched for answers and finally posted an issue on GitHub.
The bottom line is this is not possible as of Laravel v4.1.
https://github.com/laravel/laravel/issues/2679
This solved it:
Artists.php
public function instruments() {
return $this->hasMany('App\Models\Instrument', 'id');
}
Note that I changed this to a hasMany from a belongsToMany which makes more sense to me as a musicians (or Artist) would have many Instruments they play and an Instrument could belong to many Artists (which I also alluded to in my previous questions referenced above). I also had to specify 'id' column in my model which tells the ORM that instrument.id matches artist_instrument.id. That part confuses me a bit because I thought the order for hasMany was foreign_key, primary_key, but maybe I'm thinking about it backwards. If someone can explain that a bit more I'd appreciate it.
Anyhow, the second part of the solution...
In ArtistsController.php, I did this:
$artists = Artist::with(array(
'instruments' => function($q) {
$q->select('instruments.id', 'name');
})
)->get(array('id', 'firstname', 'lastname'));
That gives me exactly what I want which is a collection of Artists that contains only the firstname and lastname columns from the artists table and the name column for each of the instruments they play from the instruments.
$artists = Artist::with(array('instruments' => function ($query) {
$query->select('id', 'name');
}))->get('id', 'firstname', 'lastname');

EF Code First - convert string to int in query

I need to convert String to Int32 value in my query. It must be done on sql server-side, not in memory.
I've seen answers how to do this in Model First approach, LINQ to Entities.
here and here
But I need it to be done with Code First.
I write query to DbSet<>.
Is there any way to do this? Please, help :)
New Answer:
The only way I can find information for is to use a custom query.
For instance:
from user in Users.SqlQuery("SELECT Id, CAST(Age AS INT) as Age, FirstName, LastName FROM Users")
select new
{
id = user.Id,
Age = user.Age
}
In my tests it seems every value for property on the entity you map to have to be included in the select even if you select to a custom object that do not include every property. In my example above I include FirstName and LastName even though they aren't used in the select.
Old answer:
About converting to string on sql-side:
You can use SqlFunctions.StringConvert if you cast your int to a double or decimal first
Problem with converting int to string in Linq to entities
from user in Users
select new
{
IdAsText = SqlClient.SqlFunctions.StringConvert((decimal)user.Id)
}
The cast to float or decimal is necessary because the STR-function on the sql-server requires a float: Why is there no int overload for SqlFunctions.StringConvert
Update:
In LINQPad the generated SQL-query from the above comes out to:
SELECT
[Extent1].[Id] AS [Id],
STR( CAST( [Extent1].[Id] AS decimal(19,0))) AS [C1]
FROM [dbo].[Users] AS [Extent1]

Is there a way to update a database field based on a list?

Using JPA, I have a list of entries from my database :
User(id, firstname, lastname, email)
That I get by doing:
List<User> users = User.find("lastname = ?", "smith");
And I'd like to update all in one request, by doing something like this :
"UPDATE USER SET email = null IN :list"
and then set the parameter "list" to users
Is it possible? if so, how?
Thanks for your help :)
Well, you could embed the query that you used to obtain list in the where clause of the update.
UPDATE User a SET a.email = null
WHERE user IN (SELECT b FROM User b WHERE lastName = :?)
By doing this you'd be doing the query to search the list and the update in single update query.
How do you like that? Do you think this could work?
-EDIT-
Since you want to use the original list of items instead of a list just retrieved from the database, you can still ensure you build the original list like this
UPDATE User a SET a.email = null
WHERE user IN (SELECT b FROM User b WHERE lastName IN(:originalList))
Then when you invoke it, you can do something like this:
Collection<String> originalList = Arrays.asList("Kenobi", "Skywalker", "Windu");
query.setParameter("originalList", originalList);
By this, you can still ensure the query will only contain items in your original list and not any possible new item from the database, provided that that last name is a candidate key in the database, otherwise I would recommend that you use the ID for the subquery instend of the last name.
if you have jpa+hibernate you can use entityManager.createQuery() for creating hql query
like that:
String hql = "UPDATE Supplier SET name = :newName WHERE name IN :name";
entityManager.createQuery(hql);