mysql_affected_rows() always returns 1 even though no row was updated - mysql

What I am trying to do is: (programmatically)
Update status where id is something, if no rows where updated, give error: we cannot find the record with id something, otherwise give message success.
Here I am using mysql_affected_rows() to know if a row was updated or not, but it always return 1, so the user gets a success message, even though there was no row updated.
Can anyone tell me what could it be?
Here's the code:
function update_sql($sql) {
$this->last_query = $sql;
$r = mysql_query($sql);
if (!$r) {
$this->last_error = mysql_error();
return false;
}
$rows = mysql_affected_rows();
if ($rows == 0) return true; // no rows were updated
else return $rows; }
This code returns 1.

That is because true will print out as "1" if you use echo. For debugging try using var_dump(), or let your function return 0 (which seems to me, in this case, the better option).
One little note; I think you should try to make your code a bit more readable (if the code in your question has the same layout as the code in your file). Try to indent code blocks, use separate lines for closing curly brackets, etc...

This is just a guess...
Maybe your function works as excepted? Maybe this piece of code if ($rows == 0) return true; works fine, and returns true but you treat that value as integer (boolean true can be displayed as 1)? Do: var_dump(uddated_sql('YOUR QUERY')) and check whether it returns boolean true or integer 1 value.

Related

Natural sorting Ajax Datatables in Codeigniter

Struggling to figure out how to set natural sorting in AJAX Datatables using Codeigniter Active record.
The field that should be sorted has, in most cases, just digits...in other cases a string, so the MySQL table field is set as VARCHAR.
I need to srt naturally the field to be displayed in Datatables.
The Active record Codeigniter query is the following.
function list_all($limit,$start,$col,$dir)
{
$this->rmi_db->select ("
$this->table_dev.id,
$this->table_dev.fl,
$this->table_dev.mm,
$this->table_dev.batch,
$this->table_dev.n,
$this->table_dev.ditta,
$this->table_dev.tipo,
$this->table_dev.costruzione,
$this->table_dev.motori,
$this->table_dev.nc,
$this->table_dev.serie,
$this->table_dev.ca,
$this->table_dev.consegna,
$this->table_dev.matr_usaf AS usaf,
$this->table_dev.matr_usn AS usn,
$this->table_dev.matr_caf AS caf,
$this->table_dev.matr_raf AS raf,
$this->table_dev.codici,
$this->table_dev.note,
$this->table_dev.reg_civili,
$this->table_dev.matricola_civ,
$this->table_dev.prima_reg,
$this->table_dev.n_contratto,
$this->table_dev.data_contratto,
$this->table_dev.importo_contratto,
$this->table_dev.note_contratto,
$this->table_dev.f29,
$this->table_dev.f30,
");
$this->rmi_db->from("$this->table_dev");
$this->rmi_db->where("$this->table_dev.mm !=", "");
$this->rmi_db->limit($limit, $start);
$this->rmi_db->order_by($col, $dir);
$query = $this->rmi_db->get();
if($query->num_rows()>0)
{
return $query->result();
}
else
{
return null;
}
}
The mm field should be sorted naturally. I have no idea how and if it's possible to fix the issue.
I tried the solution in this discussion solutions, the Bin way, but the select doesn't work properly ( got 500 server error)
Thanks a lot for any help
Using Solution, Try below. It should work but not tested.
function list_all($limit,$start,$col,$dir)
{
$this->rmi_db->select ("
$this->table_dev.id,
$this->table_dev.fl,
$this->table_dev.mm,
$this->table_dev.mm, CAST($this->table_dev.mm as SIGNED) AS casted_column,//changed
$this->table_dev.batch,
$this->table_dev.n,
$this->table_dev.ditta,
$this->table_dev.tipo,
$this->table_dev.costruzione,
$this->table_dev.motori,
$this->table_dev.nc,
$this->table_dev.serie,
$this->table_dev.ca,
$this->table_dev.consegna,
$this->table_dev.matr_usaf AS usaf,
$this->table_dev.matr_usn AS usn,
$this->table_dev.matr_caf AS caf,
$this->table_dev.matr_raf AS raf,
$this->table_dev.codici,
$this->table_dev.note,
$this->table_dev.reg_civili,
$this->table_dev.matricola_civ,
$this->table_dev.prima_reg,
$this->table_dev.n_contratto,
$this->table_dev.data_contratto,
$this->table_dev.importo_contratto,
$this->table_dev.note_contratto,
$this->table_dev.f29,
$this->table_dev.f30,
");
$this->rmi_db->from("$this->table_dev");
$this->rmi_db->where("$this->table_dev.mm !=", "");
$this->rmi_db->limit($limit, $start);
$this->rmi_db->order_by($col, $dir);
$this->rmi_db->order_by('casted_column', 'ASC'); // changed
$this->rmi_db->order_by($this->table_dev.mm, 'ASC'); // changed
$query = $this->rmi_db->get(); //changed
if($query->num_rows()>0)
{
return $query->result();
}
else
{
return null;
}
}
comment if you face any issue

Apache2 Perl vHosts Error

I just worked through this tutorial and modified the table by adding another column. I want to check the value before adding the template script. It didn't work and the script includes the template-ssl every time. It is important that this script works with MySQL, mass vhosts is not possible.
$My::dir = #row[3];
$My::encrypted = #row[4];
if ($My::encrypted == 'ssl') {
$s->add_config(["Include /etc/apache2/sites-available/template-ssl"]);
}
else {
$s->add_config(["Include /etc/apache2/sites-available/template-def"]);
}
I think the variables doesn't work but if(#row[4] == "ssl") also fire as true every time. Even when the DataRow contains "def".
Ok, it was too simple. The error was that you compare stings with "xx" eq "yy" and numbers with 1 == 2.

Check next record exists in database

I am using Zend fetch method to fetch huge number of records from database for creating reports.Since fetchAll is costly as compared to fetch i am using it.And if its the last row i need to add some additinoal logic.So my question is that is there a way to check if next record exists or not inside the while loop. I am using it like the following
//$select is the select query
$objDb = Zend_Registry::get('db');
$objAchQry = $objDb->query($select);
while($arrResult = $objAchQry->fetch()) {
//Do something
//I need to do something here if its the last record like
/*
if($last_rec)
do something
*/
}
Is there a way to check if the current one is last record or if any other record exists. I know to do it by taking count of records and incrementing a counter inside the loop.But i dont need it.Any solutions.?
"is there a way to check if next record exists" The condition on your while loop does exactly just that. The loop won't execute any more if no more rows exist to fetch.
Think of it this way:
while($arrResult = $objAchQry->fetch()) {
//Do something
}
// Now I'm just after the last record
/*
do something
*/
If you really need to do something before the last row is processed, you could modify your code to
$total_records = // get total no of rows
$counter = 0;
while($arrResult = $objAchQry->current()) {
//Do something
$counter ++;
//I need to do something here if its the last record like
if( ! $bojAchQry->next()) {
// The row currently being processed is the last one.
} else {
break;
}
}
One way - You can track with counter,
$total_records = // get total no of rows
$counter = 0;
while($arrResult = $objAchQry->fetch()) {
//Do something
$counter ++;
//I need to do something here if its the last record like
if($counter == $total_records ) // this iteration will be the last one.
//do something
}

What does this line of Actionscript do?

I'm looking at the as3delaunay library and most of the code is clear to me. This part is not, however (note the line that I put preceded with an arrow):
public function circles():Vector.<Circle>
{
var circles:Vector.<Circle> = new Vector.<Circle>();
for each (var site:Site in _sites)
{
var radius:Number = 0;
var nearestEdge:Edge = site.nearestEdge();
=======>> !nearestEdge.isPartOfConvexHull() && (radius = nearestEdge.sitesDistance() * 0.5);
circles.push(new Circle(site.x, site.y, radius));
}
return circles;
}
For reference, isPartOfConvexHull() is found in Edge.as and looks like this:
internal function isPartOfConvexHull():Boolean
{
return (_leftVertex == null || _rightVertex == null);
}
What does !nearestEdge.isPartOfConvexHull() do? Does that mean that the radius = nearestEdge.sitesDistance() * 0.5 only executes if false is returned from the call to isPartOfConvexHull()? Does that stop execution of any other code?
It is equivalent to:
if (!nearestEdge.isPartOfConvexHull()) {
radius = nearestEdge.sitesDistance() * 0.5;
}
In the following line:
var b:Boolean = expression1 && expression2;
expression2 will not be evaluated if expression1 is false because we already know the final result: b = false.
Now in the following line:
expression1 && expression2;
The same thing happens except the fact that we are not assigning the result to a variable.
And this is exactly what happens in the line you are asking about where !nearestEdge.isPartOfConvexHull() is the first expression and (radius = nearestEdge.sitesDistance() * 0.5) is the second expression.
To extends #sch answer with some explanations (I didn't knew if editing answer to almost double it was ok).
This is based on lazy execution of the interpreter. If (!nearestEdge.isPartOfConvexHull()) is False then there's no need to execute the second part of the AND statement to know it'll be False, then it's left unexecuted. If it's true the evaluation of the complete statement is needed (and then done) to tell wether or not this boolean is True. So this is equivalent to an if statement.
TMHO this is bad code since it's to much condensed and hard to understand.

Multidimensional Array insert into Mysql rows

I have an Array (twodimensional) and i insert it into my database.
My Code:
$yourArr = $_POST;
$action = $yourArr['action'];
$mysql = $yourArr['mysql'];
$total = $yourArr['total'];
unset( $yourArr['action'] , $yourArr['mysql'] , $yourArr['total'] );
foreach ($yourArr as $k => $v) {
list($type,$num) = explode('_item_',$k);
$items[$num][$type] = $v;
$pnr= $items[$num][pnr];
$pkt= $items[$num][pkt];
$desc= $items[$num][desc];
$qty= $items[$num][qty];
$price= $items[$num][price];
$eintragen = mysql_query("INSERT INTO rechnungspositionen (artikelnummer, menge, artikel, beschreibung,preis) VALUES ('$pnr', '$qty', '$pkt', '$desc', '$price')");
}
I get 5 inserts in the Database but only the 5th have the informations i want. The firsts are incomplete.
Can someone help me?
Sorry for my english.
check if You have sent vars from browser in array (like
input name="some_name[]" ...
also You can check, what You get at any time by putting var_dump($your_var) in any place in script.
good luck:)
You probably want to have your query and the 5 assignments above that outside of the foreach. Instead in a new loop which only executes once for every item instead of 5 times. Your indentation even suggests the same however your brackets do not.
Currently it is only assigning one value each time and executing a new query. After 5 times all the variables are assigned and the last inserted row finally has everything proper.
error_reporting(E_ALL);
$items = array();
foreach($yourArr as $k => $v) {
// check here if the variable is one you need
list($type, $num) = explode('_item_', $k);
$items[$num][$type] = $v;
}
foreach($items as $item) {
$pnr = mysql_real_escape_string($item['pnr']);
$pkt = mysql_real_escape_string($item['pkt']);
$desc = mysql_real_escape_string($item['desc']);
$qty = mysql_real_escape_string($item['qty']);
$price = mysql_real_escape_string($item['price']);
$eintragen = mysql_query("INSERT INTO rechnungspositionen (artikelnummer, menge, artikel, beschreibung,preis) VALUES ('$pnr', '$qty', '$pkt', '$desc', '$price')");
}
Switching on your error level to E_ALL would have hinted in such a direction, among else:
unquoted array-keys: if a constant of
the same name exists your script will
be unpredictable.
unescaped variables: malformed values
or even just containing a quote which
needs to be there will fail your
query or worse.
naïve exploding: not each $_POST-key
variable will contain the string
item and your list will fail, including subsequent use of $num