php/mysql Pagination argument not valid - pagination

After db connection-
`$tbl_name="mytable";`
$adjacents = 3;
$query = "SELECT COUNT (*) as num FROM $mytable";
$total_pages = mysql_fetch_array(mysql_query($query)); this is line 32
$total_pages = $total_pages[num];
$targetpage = "pagination.php"; (the name of this file)
$limit = 20;
error i am getting is-
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in line 32.
can anyone help?
thanks

The problem should be in your query, it should be either:
$query = "SELECT COUNT (*) as num FROM mytable";
or
$query = "SELECT COUNT (*) as num FROM ".$tbl_name."";
You are referencing a variable $mytable that you haven't previously defined

Related

Convert a String into a Hashtable in Powershell

my request is a bit special but quite simple to understand.
I get a string that I would like to exploit as a hashtable but I can't, my format is quite special and I haven't been successful with methods like ConvertFrom-StringData for example.
format preview:
#{id = 04cc943e-14a8-4bf6-8601-bd6fde3cc229; name = 7.10 10-16 - 6.0 * * * * | 1 0 0 0; privileges =}
I would therefore like to be able to access the content of the name attribute.
I spent a lot of time there but without success ...
Thank you for your help
So you may go with a string parsing and use combination of splitting and trimming.
$text = "#{id = 04cc943e-14a8-4bf6-8601-bd6fde3cc229; name = 7.10 10-16 - 6.0 * * * * | 1 0 0 0; privileges =}"
#this is to get rid of #{}
$preparedText = $text.Substring(2,$text.Length-3)
$obj = #{}
foreach ($kv in $preparedText.Split(";")) {
#Get key from string (which is "key = value")
$key = $kv.Trim().Split("=")[0].Trim()
Write-Host "Key = $key"
#Get value from string
$value = $kv.Trim().Split("=")[1].Trim()
Write-Host "Value = $value"
#Assign key-object pair to hashtable
$obj[$key] = $value
}
Write-Host "obj.name = $($obj.name);`nobj.id = $($obj.id);`nobj.privileges = $($obj.privileges)"
Which returns:
obj.name = 7.10 10-16 - 6.0 * * * * | 1 0 0 0;
obj.id = 04cc943e-14a8-4bf6-8601-bd6fde3cc229;
obj.privileges =
An alternative approach is to use the convertfrom-stringdata cmdlet, documented here:
Link to official MS documentation
The ConvertFrom-StringData cmdlet converts a string that contains one or more key and value pairs into a hash table. Because each key-value pair must be on a separate line, here-strings are often used as the input format. By default, the key must be separated from the value by an equals sign (=) character.
Using the OP's example as in #Karolina Ochlik's post:
$text = "#{id = 04cc943e-14a8-4bf6-8601-bd6fde3cc229; name = 7.10 10-16 - 6.0 * * * * | 1 0 0 0; privileges =}"
#this is to get rid of #{}
$preparedText = $text.Substring(2,$text.Length-3)
# replace semicolon with newline - `n needs double quotes
$preparedText.replace(';',"`n") | ConvertFrom-StringData
This creates the output:
Name Value
---- -----
name 7.10 10-16 - 6.0 * * * * | 1 0 0 0
id 04cc943e-14a8-4bf6-8601-bd6fde3cc229
privileges
the real work is done in the single line
$preparedText.replace(';',"`n") | ConvertFrom-StringData
I hope this helps someone.

How to implement nested filters in diesel?

I'm quite new to Rust and Diesel. I'm now trying to implement Diesel filtering for query like this:
-- #param1 is duration in years
-- #param2 is duration in months
SELECT columns FROM a
WHERE
(...dynamic AND clauses)
AND (((a.min_unit = "Years") AND (a.min_duration <= #param1))
OR ((a.min_unit = "Months") AND (a.min_duration <= #param2)))
(...dynamic AND clauses)
After some searches in docs and around the web, I still couldn't find how to do this.
My closest guess is:
let param1 = ...;
let param2 = ...;
let mut query = a::table.select(a::all_columns).into_boxed();
// dynamic clauses: query = query.filter(...) ...
query = query.filter(a::min_unit.eq(Some("Years")).and(a::min_duration.le(Some(param1))))
.or_filter(a::min_unit.eq(Some("Months")).and(a::min_duration.le(Some(param2))));
// dynamic clauses: query = query.filter(...) ...
let results = a::table.load<A>(&*conn);
Anyone has idea?
Thanks!
Your code actually looks correct (I haven't run it). The documentation here points to how it is done: https://docs.diesel.rs/diesel/query_dsl/trait.QueryDsl.html#method.or_filter foo.filter(bar).or_filter(baz) is like foo.filter(bar.or(baz)) but the second one is "nested". So, to get
(id = 5 OR other = 6) AND foo=7
one would do
.filter(id.eq(5).or(other.eq(6))).filter(foo.eq(7)).
Hope that helps!
Well, here is my latest try:
let min_months_predicate = a::min_unit.eq(Some("Months"))
.and(a::min_duration.le(Some(param1)));
let min_years_predicate = a::min_unit.eq(Some("Years"))
.and(a::min_duration.le(Some(param1)));
query = query.filter(min_months_predicate.or(min_years_predicate))
.filter(a::max_duration.ge(Some(param2)));
debug!("TEST QUERY: {:?}", debug_query(&query));
which yields this query:
"SELECT \"a\".\"id\", \"a\".\"code\", .... WHERE (\"a\".\"min_unit\" = $1 AND \"a\".\"min_duration\" <= $2 OR \"a\".\"min_unit\" = $3 AND \"a\".\"min_duration\" <= $4) AND \"a\".\"max_duration\" >= $5"
And when I use sql EXPLAIN with this query, I got this clause:
Filter: ((max_duration >= 60) AND (((min_unit = 'Months'::text) AND (min_duration <= 3)) OR ((min_unit = 'Years'::text) AND (min_duration <= 5))))
which seems correct.

Pyomo Constraint Block in Abstract Model

For a better structure of my Constraints, I want to summarize multiple constraints into a block, so that a don't have to scroll through a long list of separate functions representing my constraints.
My problem is that I'm using an Abstract model and don't know how to define that Block for a set that has not been initialized yet
M.s = pe.Set(dimen=1)
M.chp_minPower = pe.Param(within=pe.Reals,mutable=True)
M.chp_maxPower = pe.Param(within=pe.Reals,mutable=True)
M.chp_posGrad = pe.Param(within=pe.Reals,mutable=True)
M.chp_negGrad = pe.Param(within=pe.Reals,mutable=True)
M.chp_k = pe.Param(within=pe.Reals,mutable=True)
M.chp_c = pe.Param(within=pe.Reals,mutable=True)
M.chp_f1 = pe.Param(within=pe.Reals,mutable=True)
M.chp_f2 = pe.Param(within=pe.Reals,mutable=True)
M.gasCost = pe.Param(within=pe.Reals,mutable=True)
M.chpOn = pe.Var(M.s, within=pe.Binary)
M.chpSwitchON = pe.Var(M.s,within=pe.Binary)
M.chpPel = pe.Var(M.s,within=pe.NonNegativeReals)
M.chpPth = pe.Var(M.s, within=pe.NonNegativeReals)
M.chpQGas = pe.Var(M.s, within=pe.NonNegativeReals)
def chp_block_rule1(nb,i):
#Constraints
nb.chpPelMax = pe.Constraint(expr=M.chpPel[i] <= M.chp_maxPower * M.chpOn[i])
nb.chpPelMin = pe.Constraint(expr=M.chpPel[i] >= M.chp_minPower * M.chpOn[i])
#b.sellBin = pe.Constraint(expr=b.sell[i]/M.maxSell <= M.sellBin[i]
nb.chpCogen = pe.Constraint(expr=M.chpPth[i] == M.chp_f1 * M.chpPel[i] + M.chp_f2 * M.chpOn[i])
nb.chpConsumption = pe.Constraint(expr=M.chpQGas[i] == M.chp_c * M.chpOn[i] + M.chp_k + M.chpPel[i])
M.chp_block = pe.Block(M.s, rule=chp_block_rule1)
ValueError: Error retrieving component chpPel[1]: The component has
not been constructed.
Does anybody know how to work with blocks in Abstract models?
I'm not 100% sure but I guess expr tries to actually evaluate the expression, and because chpPel is a variable (thus has no value) it breaks.
In order to delay the evaluation of the expression (i.e. pass the expression into the solver as symbolic), you can use rule instead of expr.
As you probably know rule takes a function. If the expression is short enough, you can use a lambda function.
nb.chpPelMax = pe.Constraint(rule=lambda M: M.chpPel[i] <= M.chp_maxPower * M.chpOn[i])
Side note: you can just use list(range(...)) instead of the list comprehension.

Need to cut a string(Table Name) from Query in c#

My String/Query looks like this
insert into Employee Values(1,2,'xxx');
update Employee2 set col1='xxx' where col2='yyy';
select * from Employee3;
I need to take/have TableName alone. Table name won't be constant it will be differed(Employee,Employee2,Employee3) according to DB. I'm new to C# please help me. Thanks in advance.
To get the name of a table from a query (or in this case, a string named 'sql'), try the following:
string sql = "select * from table ";
int index1 = 0;
int index2 = 0;
int currentIndex = 0;
int numSpaces = 0;
char[] chArray = sql.ToCharArray();
foreach (char c in chArray)
{
if (c == ' ')
{
numSpaces++;
if (numSpaces == 3)
index1 = currentIndex;
if (numSpaces == 4)
{
index2 = currentIndex;
break;
}
}
currentIndex++;
}
int length = index2 - index1;
string tableName = sql.Substring(index1, length);
MessageBox.Show(tableName);
Warning - this solution is based on finding the word between the 3rd and 4th space character. This limits you to have a very predictable query structure - more complicated queries may not work with this solution. Your query structure needs to be:
"select column_name1,column_name2,column_name3 from table "
Your query must not have spaces between columns and must have a space at the end aswell. Sorry for the limitations but its the best I can come up with ;)

linq inline string operation

I've a method that returns this exception.
LINQ to Entities does not recognize the method 'System.String stringCutter(System.String)' method, and this method cannot be translated into a store expression.
public List<ProductReqNoDate> GetRequestsQuery()
{
var query = (from r in db.talepler
select new ProductReqNoDate
{
talepEdenBirim = r.talepEdenBirim,
talepNo = r.talepNo,
talepTarihi = r.talepTarihi,
urunAdi = stringCutter((from p in db.urunler
where p.talepNo == r.talepNo
select p.urunAd).FirstOrDefault()) // <--This
}).AsQueryable();
return query.ToList();
}
string stringCutter(string txt)
{
return string.IsNullOrEmpty(txt) ? "" : txt.Length <= 30 ? txt : txt.Substring(0, 30) + "...";
}
when i use this string operations inline, it works. but its too long,
urunAdi = ((from p in db.urunler where p.talepNo == r.talepNo select p.urunAd).FirstOrDefault()).Length <= 30 ?
((from p in db.urunler where p.talepNo == r.talepNo select p.urunAd).FirstOrDefault()) :
((from p in db.urunler where p.talepNo == r.talepNo select p.urunAd).FirstOrDefault()).Substring(0, 30) + "..."
How can i refer (from p in db.urunler where p.talepNo == r.talepNo select p.urunAd).FirstOrDefault()) as txt maybe; so i can use stringCutter method inline like:
urunAdi=string.IsNullOrEmpty(txt) ? "" : txt.Length <= 30 ? txt : txt.Substring(0, 30) + "...";
Is there a way of shortening this code. , thanks
EF is trying to map the function stringCutter into SQL. Which it can't because it does not know about it. The inline version only uses functions that EF knows to map to SQL expressions/function.
IQueryable<> cannot convert your expression to be used with the back-end store. You need to bring a string into memory first, then you can use IEnumerable<>'s projection method to call your method, like this:
return (from r in db.talepler
select new // First, use an anonymous type to read the building blocks
{
r.talepEdenBirim,
r.talepNo,
r.talepTarihi,
urunAdiStr = (from p in db.urunler
where p.talepNo == r.talepNo
select p.urunAd).FirstOrDefault()
}
).AsQueryable()
.ToList() // Force the data into memory
.Select(anon => new ProductReqNoDate {
talepEdenBirim = anon.talepEdenBirim,
talepNo = anon.talepNo,
talepTarihi = anon.talepTarihi,
urunAdi = stringCutter(anon.urunAdiStr) // Now stringCutter is available
}).ToList();

Resources