I want to retrieve a single item of data from my database to then use as a value for an input element.
Using the below will retrieve each instance of SubmittedBy in the DB so results in multiple results.
var UserId = WebSecurity.CurrentUserId;
var db = Database.Open("testDB");
var selectQueryString = "Select SubmittedBy FROM Posts WHERE UserId=#0";
var data = db.Query(selectQueryString, UserId);
#foreach(var row in data)
{
<input type="email" name="emailfrom" id="emailfrom" value="#SubmittedBy"/>
}
How do I retrieve SubmittedBy so it only gives the one result i.e. without the foreach loop?
Thanks in advance!!!
If by your data restriccions are you going to obtain 1 and only 1 value for an specific UserId, you could use
var SubmyttedValue = db.QueryValue(selectQueryString, UserId);
There is a method created specifically for this purpose called QuerySingle - just change your query like this:
var data = db.QuerySingle(selectQueryString, UserId);
I hope this helps!
Change your query like this:
Select SubmittedBy FROM Posts WHERE UserId=#0 LIMIT 1
Related
I am using sqlite database in Flutter. with provide and sqlite libraries. I want to get ordered list of String in the database when I get the list from sqlite. How can I achieve this? Thank you for your response!
You can use orderBy variable inside query method like this:
Future<List<SingleShiftModel>> getShiftModelsForParticularGroup(
String groupId) async {
Database db = await database;
final List<Map<String, dynamic>> maps = await db.query(
allShiftsTableName,
where: 'parentId = ?',
orderBy: "date ASC", // here you can add your custom order exactly like sqlite but EXCLUDE `ORDER BY`.
whereArgs: [groupId],
);
return List.generate(
maps.length,
(i) => SingleShiftModel.toShiftModelObject(maps[i]),
);
}
I have this view method -
public ActionResult Index()
{
var db = new ApplicationDbContext();
var auctions = db.Auctions.ToArray();
return View(auctions);
}
which correctly returns an array of all auctions in my database. But I want to return just the most popular ones. I want to do something like this:
public ActionResult Index()
{
var db = new ApplicationDbContext();
var auctions = db.Auctions.getMostPopular.ToArray();
return View(auctions);
}
Where getMostPopular() is a method in my model containing all my auctions and looks like so at the moment:
public static List<Auction> getMostPopular()
{
var query = "SELECT* FROM AUCTIONS WHERE EndTime > CONVERT(date, GETDATE()) ORDER BY viewCount DESC;" }
}
So how do I correctly write this getMostPopular() method?
And is this the correct path to go writing it in the model? Or should I write the query in the controller Index action, and if so what would that look like?
Correct is relative. Your proposed SQL statement would seem to do the trick. Ordering the results by the ViewCount desc would appear to be the main part of implementing your method get most popular. If you're already considering a date filter, you might also consider the top clause such as select top 10 * from Table order by ViewCount desc, to only consider a fixed number of most popular items.
I'm trying to get latest inserted id from a table using this code:
$id = $tbl->fetchAll (array('public=1'), 'id desc');
but it's always returning "1"
any ideas?
update: I've just discovered toArray();, which retrieves all the data from fetchAll. The problem is, I only need the ID. My current code looks like this:
$rowsetArray = $id->toArray();
$rowCount = 1;
foreach ($rowsetArray as $rowArray) {
foreach ($rowArray as $column => $value) {
if ($column="id") {$myid[$brr] = $value;}
//echo"\n$myid[$brr]";
}
++$rowCount;
++$brr;
}
Obviously, I've got the if ($column="id") {$myid[$brr] = $value;} thing wrong.
Can anyone point me in the right direction?
An aternative would be to filter ID's from fetchAll. Is that possible?
Think you can use:
$id = $tbl->lastInsertId();
Aren't you trying to get last INSERT id from SELECT query?
Use lastInsertId() or the value returned by insert: $id = $db->insert();
Why are you using fetchAll() to retrieve the last inserted ID? fetchAll() will return a rowset of results (multiple records) as an object (not an array, but can be converted into an array using the toArray() method). However, if you are trying to reuse a rowset you already have, and you know the last record is the first record in the rowset, you can do this:
$select = $table->select()
->where('public = 1')
->order('id DESC');
$rows = $table->fetchAll($select);
$firstRow = $rows->current();
$lastId = $firstRow->id;
If you were to use fetchRow(), it would return a single row, so you wouldn't have to call current() on the result:
$select = $table->select()
->where('public = 1')
->order('id DESC');
$row = $table->fetchRow($select);
$lastId = $row->id;
It sounds like it's returning true rather than the actual value. Check the return value for the function fetchAll
i have alot of tables with alot of columns and want to generate xml using linq without having to specify
the column names. here's a quick example:
users
---------------
user_id
name
email
user_addresses
---------------
address_id
user_id
city
state
this is the xml i want to generate with linq would look like
<user>
<name>john</name>
<email>john#dlsjkf.com</email>
<address>
<city>charleston</city>
<state>sc</state>
</address>
<address>
<city>charlotte</city>
<state>nc</state>
</address>
</user>
so i'm guessing the code would look something like this:
var userxml = new XElement("user",
from row in dc.Users where user.id == 5
select (what do i put here??)
);
i can do this for one table but can't figure out how to generate the xml for a linked table (like user_addresses).
any ideas?
ok found a way to get the xml i want, but i have to specify the related table names in the query...which is good enough for now i guess. here's the code:
XElement root = new XElement("root",
from row in dc.users
where row.user_id == 5
select new XElement("user",
row.AsXElements(),
new XElement("addresses",
from row2 in dc.user_addresses
where row2.user_id == 5
select new XElement("address", row2.AsXElements())
)
)
);
// used to generate xml tags/elements named after the table column names
public static IEnumerable<XElement> AsXElements(this object source)
{
if (source == null) throw new ArgumentNullException("source");
foreach (System.Reflection.PropertyInfo prop in source.GetType().GetProperties())
{
object value = prop.GetValue(source, null);
if (value != null)
{
bool isColumn = false;
foreach (object obj in prop.GetCustomAttributes(true))
{
System.Data.Linq.Mapping.ColumnAttribute attribute = obj as System.Data.Linq.Mapping.ColumnAttribute;
if (attribute != null)
{
isColumn = true;
break;
}
}
if (isColumn)
{
yield return new XElement(prop.Name, value);
}
}
}
}
You need to use a join. Here's one way:
var query = from user in dc.Users
from addr in dc.UserAddress
where user.Id == addr.UserId
select new XElement("user",
new XElement("name", user.Name),
new XElement("email", user.Email),
new XElement("address",
new XElement("city", addr.City),
new XElement("state", addr.State)));
foreach (var item in query)
Console.WriteLine(item);
i have alot of tables with alot of
columns and want to generate xml using
linq without having to specify the
column names.
Not quite sure how you want to achieve that. You need to state the column names that go into the XML. Even if you were to reflect over the field names, how would you filter the undesired fields out and structure them properly without specifying the column names? For example how would you setup the address part? You could get the fields by using this on your User and UserAddress classes: User.GetType().GetFields() and go through the Name of each field, but then what?
I've got two form fields from which the user submits a 'category' and an 'item'.
The following code inserts the category fine (I modified it from the WebMatrix intro PDF) but I've no idea how to then insert the 'item' into the Items table. I'll also need to add the Id of the new category to the new item row.
This is the code that's working so far
#{ var db = Database.OpenFile("StarterSite.sdf");
var Category = Request["Category"]; //was name
var Item = Request["Item"]; //was description
if (IsPost) {
// Read product name.
Category = Request["Category"];
if (Category.IsEmpty()) {
Validation.AddFieldError("Category", "Category is required");
}
// Read product description.
Item = Request["Item"];
if (Item.IsEmpty()) {
Validation.AddFieldError("Item",
"Item type is required.");
}
// Define the insert query. The values to assign to the
// columns in the Products table are defined as parameters
// with the VALUES keyword.
if(Validation.Success) {
var insertQuery = "INSERT INTO Category (CategoryName) " +
"VALUES (#0)";
db.Execute(insertQuery, Category);
// Display the page that lists products.
Response.Redirect(#Href("~/success"));
}
}
}
I'm guessing/hoping this is a very easy question to answer so hopefully there isn't much more detail required - but please let me know if there is. Thanks.
There's a Database.GetLastInsertId method within WebMatrix which returns the id of the last inserted record (assuming it's an IDENTITY column you are using). Use that:
db.Execute(insertQuery, Category);
var id = (int)db.GetLastInsertId(); //id is the new CategoryId
db.Execute(secondInsertQuery, param1, id);