jeudi 13 août 2015

Dynamic fields only updating first row


I have a dynamic form (with dynamically adding rows).
This form has 2 normal input fields which send data to table 'orcamen'
and 4 dynamic fields which are stored in table 'tbl_orderdetail'.
When I try to update the dynamically added fields, the table stores only the first row.

This is my edit page that fetches correctly the values from both tables:

<?php 

mysql_connect("localhost","root");
mysql_select_db("alpha");



$id = $_GET["id"];
settype($id, "integer");

    $resultado=mysql_query("SELECT * FROM orcamen WHERE id = $id");

    $orcrow=mysql_fetch_object($resultado);

//This is the table that gets the dynamic rows          
$query = mysql_query( "SELECT * FROM tbl_orderdetail WHERE order_id=$id");

mysql_close();
?>

And here is the html code of the dynamic rows:

<form   method="post" action="salva_orc.php">   
<input type="hidden" name="id" id="id" value="<?php echo $id;?>" />

            <thead>
                <th>No</th>
                <th>Qtde</th>
                <th>Descrição</th>
                <th>Unitário</th>
                <th>Desc.(%)</th>
                <th>Valor</th>
                <th><input type="button" value="+" id="add" class="btn btn-primary"></th>
            </thead>


            <tbody id="orderdetail" class="detail">
            <?php
                while ($result = mysql_fetch_object($query)){
            ?>
                <tr>
                    <td width="2%" class="no">1</td>
                    <td width="10%"><input type="text" class="form-control quantity" name="quantity[$result->id]" value="<?php echo $result->quantity ?>"></td>
                    <td width="60%"><input type="text" class="form-control productname" name="product_name[$result->id]" value="<?php echo $result->product_name ?>"></td>
                    <td width="8%"><input type="text" class="form-control price" name="price[$result->id]" value="<?php echo $result->price ?>"></td>
                    <td width="4%"><input type="text" class="form-control discount" name="discount[$result->id]" value="<?php echo $result->discount ?>"></td>
                    <td width="10%"><input type="text" class="form-control amount" name="amount[$result->id]" value="<?php echo $result->amount   ?>"></td>
                    <td width="6%"><a href="#"  class="remove">Excluir</td>
                </tr>
            <?php } ?>  
</tbody>

            <tfoot>
                <th></th>
                <th></th>
                <th></th>
                <th></th>
                <th style="text-align:center;" >Total  R$</th>
                <th style="text-align:center;" class="total">0</th>
            </tfoot>

        </table>
        <input type="submit" class="btn btn-primary" name="update" id="update" value="Salvar">
        </form> 

<script type="text/javascript">
    $(function(){
        $('#add').click(function(){
        addnewrow();
        });
        $('body').delegate('.remove','click',function(){
            $(this).parent().parent().remove();
        });
        $('.detail').delegate('.quantity,.price,.discount','keyup',function(){
            var tr = $(this).parent().parent();
            var qty = tr.find('.quantity').val();
            var price = tr.find('.price').val();
            var dis = tr.find('.discount').val();
            var amt = (qty * price) - (qty * price * dis)/100;
            tr.find('.amount').val(amt);
            total();
        });
    });

    function total()
    {
    var t = 0;
    $('.amount').each(function(i,e)
    {
        var amt = $(this).val()-0;
        t += amt;
    });
    $('.total').html(t);
    }

    function addnewrow()
    {
        var n = ($('.detail tr').length-0)+1;
        var tr = '<tr>'+
                    '<td class="no">' + n + '</td>'+
                    '<td><input type="text" class="form-control quantity" name="quantity[]"></td>'+
                    '<td><input type="text" class="form-control productname" name="product_name[]"></td>'+
                    '<td><input type="text" class="form-control price" name="price[]"></td>'+
                    '<td><input type="text" class="form-control discount" name="discount[]"></td>'+
                    '<td><input type="text" class="form-control amount" name="amount[]"></td>'+
                    '<td><a href="#" class="remove">Excluir</td>'+
                '</tr>';
        $('.detail').append(tr);        
    }
</script>

And now the update file that is called from the upper form.

<?php 
@ini_set('display_errors', '1');
error_reporting(E_ALL);

mysql_connect("localhost", "root", "");
mysql_select_db("alpha");


$razao     = $_POST["razao"];
$local      = $_POST["local"];
$condicao     = $_POST["condicao"];
$estado         = $_POST["estado"];
$material       = $_POST["material"];
$obs        = $_POST["obs"];
$id         = $_POST["id"];
mysql_query ("UPDATE orcamen SET razao='$razao' , local='$local' , condicao='$condicao' , estado='$estado' , material='$material' , obs='$obs' WHERE id=$id");


foreach ($_POST['quantity'] as $ord_det_id => $quantity) {
$product_name = $_POST['product_name'][$ord_det_id];
$price = $_POST['price'][$ord_det_id];
$discount = $_POST['discount'][$ord_det_id];
$amount = $_POST['amount'][$ord_det_id];

mysql_query ("UPDATE tbl_orderdetail SET product_name='$product_name',  quantity='$quantity', price='$price', discount='$discount', amount='$amount'    WHERE order_id = $id");
}


mysql_close();
header("Location: consulta_orc.php");

?>

I hope someone can help me solve this.

The new html code:

<?php
    while ($result = mysql_fetch_object($query)){
?>
<tr>
    <td width="2%" class="no">1</td>
    <td width="10%"><input type="text" class="form- control quantity" name="quantity[<?php echo $result->id ?>]" value="<?php echo $result->quantity ?>"></td>
    <td width="60%"><input type="text" class="form-control productname" name="product_name[<?php echo $result->id ?>]" value="<?php echo $result->product_name ?>"></td>
    <td width="8%"><input type="text" class="form-control price" name="price[<?php echo $result->id ?>]" value="<?php echo $result->price ?>"></td>
    <td width="4%"><input type="text" class="form-control discount" name="discount[<?php echo $result->id ?>]" value="<?php echo $result->discount ?>"></td>
    <td width="10%"><input type="text" class="form-control amount" name="amount[<?php echo $result->id ?>]" value="<?php echo $result->amount ?>"></td>
    <td width="6%"><a href="#" class="remove">Excluir</td>
</tr>
<?php } ?>  

And the php code with var_dump:

<?php 
@ini_set('display_errors', '1');
error_reporting(E_ALL);

mysql_connect("localhost", "root", "");
mysql_select_db("alpha");


$razao     = $_POST["razao"];
$local      = $_POST["local"];
$condicao     = $_POST["condicao"];
$estado         = $_POST["estado"];
$material       = $_POST["material"];
$obs        = $_POST["obs"];
$id         = $_POST["id"];
mysql_query ("UPDATE orcamen SET razao='$razao' , local='$local' , condicao='$condicao' , estado='$estado' , material='$material' , obs='$obs' WHERE id=$id");


foreach ($_POST['quantity'] as $ord_det_id => $quantity) {
$order_id = $_POST['order_id'][$ord_det_id];    
$product_name = $_POST['product_name'][$ord_det_id];
$price = $_POST['price'][$ord_det_id];
$discount = $_POST['discount'][$ord_det_id];
$amount = $_POST['amount'][$ord_det_id];



mysql_query ("UPDATE tbl_orderdetail SET product_name='$product_name', quantity='$quantity', price='$price', discount='$discount', amount='$amount' WHERE order_id = $id");



}



header("Location: consulta_orc.php");
?>



via Chebli Mohamed

Laravel query delays and 'session' queries despite database 'file' driver used

I'm currently using Laravel for a project I'm working on, and my web-server has recently started performing very slowly upon page load, whereby each page can take up to eight seconds until loaded.

Thus far, I've determined that the slowness is not caused by the following:

  • DNS issue; issue occurs when I navigate directly to the server's IP
  • Apache issue; a blank PHP file with 'phpinfo()' loads instantly without any delay
  • Load; Server's CPU usage is never above 20%

Following the above steps, the issues only occur on the live environment, where my development environment shows no signs of delay.

After analysing some cachegrind logs, I found that the PDOStatement->execute call appears to take up the largest amount of delay.

I then enabled long_query_time logging in MySQL to further determine the issue. My findings show that most of my queries are being executed quickly, well under one second; however, I've found that any site_session queries executed are taking up to six seconds to be executed.

As a further troubleshooting step, I attempted to temporarily change my sessions drive to file instead of database; however, I'm finding that the following queries are still being executed after each page load:

# Time: 150813 23:37:12
# User@Host: root[root] @ localhost [127.0.0.1]
# Query_time: 3.035622  Lock_time: 0.000022 Rows_sent: 0  Rows_examined: 1
SET timestamp=1439509032;
update `site_sessions` set `payload` = 'YTo1OntzOjY6Il90b2tlbiI7czo0MDoibHk0YVo2MG16c09acTBTSnVnYUlJVTFNM0VrU3B2ekdiRFJyYmRzWiI7czo5OiJfcHJldmlvdXMiO2E6MTp7czozOiJ1cmwiO3M6MjY6Imh0dHA6Ly93d3cuY29ycGxlYWd1ZXMuY29tIjt9czo1OiJmbGFzaCI7YToyOntzOjM6Im9sZCI7YTowOnt9czozOiJuZXciO2E6MDp7fX1zOjM4OiJsb2dpbl84MmU1ZDJjNTZiZGQwODExMzE4ZjBjZjA3OGI3OGJmYyI7czoxOiIxIjtzOjk6Il9zZjJfbWV0YSI7YTozOntzOjE6InUiO2k6MTQzOTUwOTAyODtzOjE6ImMiO2k6MTQzOTQ5Nzc5MjtzOjE6ImwiO3M6MToiMCI7fX0=', `last_activity` = '1439509029' where `id` = 'ba62f70745c5455611c3fe3bf008fa213c22a7f9';
# Time: 150813 23:37:27
# User@Host: root[root] @ localhost [127.0.0.1]
# Query_time: 1.071487  Lock_time: 0.000026 Rows_sent: 0  Rows_examined: 1
SET timestamp=1439509047;
update `site_sessions` set `payload` = 'YTo1OntzOjY6Il90b2tlbiI7czo0MDoiOGhiVVVobTFjTERrU1ZXR25weTdMWHlQRlMzTmtkOWhIZzFSdHQ1QSI7czo5OiJfcHJldmlvdXMiO2E6MTp7czozOiJ1cmwiO3M6MjY6Imh0dHA6Ly93d3cuY29ycGxlYWd1ZXMuY29tIjt9czo1OiJmbGFzaCI7YToyOntzOjM6Im9sZCI7YTowOnt9czozOiJuZXciO2E6MDp7fX1zOjM4OiJsb2dpbl84MmU1ZDJjNTZiZGQwODExMzE4ZjBjZjA3OGI3OGJmYyI7czoxOiIxIjtzOjk6Il9zZjJfbWV0YSI7YTozOntzOjE6InUiO2k6MTQzOTUwOTA0NjtzOjE6ImMiO2k6MTQzOTUwNDQzODtzOjE6ImwiO3M6MToiMCI7fX0=', `last_activity` = '1439509046' where `id` = 'c3e95cf7c317ad340aa28c61bf323e008eaa5ff0';

Can anyone shed some light on this issue, or equally, provide additional troubleshooting steps that will help me determine the root cause?

Any feedback is greatly appreciated!



via Chebli Mohamed

Sequelize.js One-to-Many relationship foreign key

I am creating a survey app using Node.js/Express and MySQL with Sequelize.js ORM.

I am having trouble setting the relationship between the 2 models correctly. I'd like to have the Questions' qId foreign key in the Answers Table.

// define the Questions table
var Questions = sequelize.define('Questions', {
  qId: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true},
  question: Sequelize.STRING
}, {
  timestamps: false
});

// define the Answers table
var Answers = sequelize.define('Answers', {
  aId: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true},
  answer: Sequelize.STRING,
  answer_count: { type: Sequelize.INTEGER, defaultValue: 0}
}, {
  timestamps: false
});

// define one-to-many relationship
Questions.hasMany(Answers, {as: 'Answers', foreignKey: 'qId'});

Questions.sync({force: true}).then(function() {
  // OPTIONAL: create a new question upon instantiating the db using sequelize
  Questions.create({question: 'what is your language?'});
  Questions.create({question: 'what is your drink?'});
  console.log('created Questions table');
  }).catch(function(error) {
    console.log('error creating Questions table');
  });

Answers.sync({force: true}).then(function() {
  Answers.create({answer: 'python', qId: 1});
  Answers.create({answer: 'javascript', qId: 1});
  Answers.create({answer: 'ruby', qId: 1});
  Answers.create({answer: 'c++', qId: 1});
  Answers.create({answer: 'manhattan', qId: 2});
  Answers.create({answer: 'cosmopolitan', qId: 2});
  console.log('created Answers table');
}).catch(function(error) {
  console.log('error creating Answers table');
});

But when I do MySQL queries:

select * from Questions, Answers where Answers.qId=2;

it's showing the following:

mysql> select * from Answers;
+-----+--------------+--------------+------+
| aId | answer       | answer_count | qId  |
+-----+--------------+--------------+------+
|   1 | python       |            0 |    1 |
|   2 | javascript   |            0 |    1 |
|   3 | ruby         |            0 |    1 |
|   4 | c++          |            0 |    1 |
|   5 | manhattan    |            0 |    2 |
|   6 | cosmopolitan |            0 |    2 |
+-----+--------------+--------------+------+
6 rows in set (0.00 sec)

mysql> select * from Questions;
+-----+------------------------+
| qId | question               |
+-----+------------------------+
|   1 | what is your language? |
|   2 | what is your drink?    |
+-----+------------------------+
2 rows in set (0.00 sec)

mysql> select * from Questions, Answers where Answers.qId=2;
+-----+------------------------+-----+--------------+--------------+------+
| qId | question               | aId | answer       | answer_count | qId  |
+-----+------------------------+-----+--------------+--------------+------+
|   1 | what is your language? |   5 | manhattan    |            0 |    2 |
|   1 | what is your language? |   6 | cosmopolitan |            0 |    2 |
|   2 | what is your drink?    |   5 | manhattan    |            0 |    2 |
|   2 | what is your drink?    |   6 | cosmopolitan |            0 |    2 |
+-----+------------------------+-----+--------------+--------------+------+

When I'd like it to show

mysql> select * from Questions, Answers where Answers.qId=2;
+-----+------------------------+-----+--------------+--------------+------+
| qId | question               | aId | answer       | answer_count | qId  |
+-----+------------------------+-----+--------------+--------------+------+ 
|   2 | what is your drink?    |   5 | manhattan    |            0 |    2 |
|   2 | what is your drink?    |   6 | cosmopolitan |            0 |    2 |
+-----+------------------------+-----+--------------+--------------+------+

I've been looking at the documentation for a few hours now and any help would be much appreciated :) Thank you.



via Chebli Mohamed

REPORT TABLE: PHP and MYSQL

I am working on a report table(not a mysql table) where it displays the values of 3 different MySQL Tables. Here are the tables with their columns:

table.SERVICES

  • service_id
  • service_name

table.BILLING_ENTRY

  • billing_id

  • billin_patientname(customer)

  • billing_servicename

  • billing_serviceid

  • biliing_amount

table.BILLING

  • billing_id
  • billing_patientname(customer)

COLUMNS WITH THE SAME VALUE (table -- column)

  • services -- service_id == billing_entry -- billing_serviceid

  • billing_entry -- billing_id == billing -- billing_id

Below is the table that I am referring. The Services(table head) is the items form table.items

TABLE

At this moment, I really don't know how do the right PHP code of what I wanted. I hope anyone can provide a Native Code for this since I will be translating/converting it to CodeIgniter's way.I hope anyone can help me.

Best Regards



via Chebli Mohamed

Scala / Slick, "Timeout after 20000ms of waiting for a connection" error

The block of code below has been throwing an error.

  Timeout after 20000ms of waiting for a connection.","stackTrace":[{"file":"BaseHikariPool.java","line":228,"className":"com.zaxxer.hikari.pool.BaseHikariPool","method":"getConnection"

Also, my database accesses seem too slow, with each element of xs.map() taking about 1 second. Below, getFutureItem() calls db.run().

xs.map{ x => 
    val item: Future[List[Sometype], List(Tables.myRow)] = getFutureItem(x)         
    Await.valueAfter(item, 100.seconds) match {
        case Some(i) => i
        case None => println("Timeout getting items after 100 seconds")
    }
}

Slick logs this with each iteration of an "x" value:

[akka.actor.default-dispatcher-3] [akka://user/IO-HTTP/listener-0/24] Connection was PeerClosed, awaiting TcpConnection termination...
[akka.actor.default-dispatcher-3] [akka://user/IO-HTTP/listener-0/24] TcpConnection terminated, stopping
[akka.actor.default-dispatcher-3] [akka://system/IO-TCP/selectors/$a/0] New connection accepted
[akka.actor.default-dispatcher-7] [akka://user/IO-HTTP/listener-0/25] Dispatching POST request to http://localhost:8080/progress to handler Actor[akka://system/IO-TCP/selectors/$a/26#-934408297]

My configuration:

"com.zaxxer" % "HikariCP" % "2.3.2"

default_db {
  url = ...
  user = ...
  password = ...
  queueSize = -1
  numThreads = 16
  connectionPool = HikariCP
  connectionTimeout = 20000
  maxConnections = 40
}

Is there anything obvious that I'm doing wrong that is causing these database accesses to be so slow and throw this error? I can provide more information if needed.

EDIT: I have received one recommendation that the issue could be a classloader error, and that I could resolve it by deploying the project as a single .jar, rather than running it with sbt.

EDIT2: After further inspection, it appears that many connections were being left open, which eventually led to no connections being available. This can likely be resolved by setting an idleTimeout in the config, or calling db.close() to close the connection at the appropriate time.



via Chebli Mohamed

vendredi 31 juillet 2015

Hash and values

I came across this Ruby script:

frequency = Hash.new(0)
...
...
file.read.downcase.scan(/\b[a-z]{4,20}\b/){|word| frequency[word] =
frequency[word]+1}

The point I couldn't understand is frequency[word] = frequency[word]+1

Wouldn't frequency[word] give me the word matched? How can we add it to 1?

Mongoid, setting custom accessor field in mongoid-history gem

I'm adding mongoid-history gem to my project.

According to guide in github, when I add Userstamp to my tracker it creates created_by field with accessor called creator.

They have written that I can rename it via gem config.

How to rename this field?