jeudi 13 août 2015

Amazon Aurora RDS unable to use import file . Access denied for user in Mysql Workbench

I have created an amazon aurora rds database instance and successfully connected with Mysql Workbench with master user.Queries are also working fine, But i do not have all the privileges necessary to perform file import operations. I have read many documentations and threads related to this but am not able to GRANT privileges to Master user. Step by step guidance will be highly appreciated. Thank You.



via Chebli Mohamed

Real Time Notification

I want to show notification into admin panel if any user insert a new ticket. that means if a new row inserted into ticket table then on admin panel show a notification and ticket count will be increased.

I cant understand How to do it. if any example available of laravel or CI or PHP then please share.

I am using laravel 4.2



via Chebli Mohamed

Arduino to MySQL via phpmyadmin

I'm trying to record arduino readings to a MySQL DB on a NetSol hosted MySQL DB via a WiFi shield. I'm using phpmyadmin (NetSol's interface) to manage the DB.

I'm using a variation of this Sketch to make it all happen: http://ift.tt/1TyQ1Qx

Everything is great until it gets to the "void postData{" piece. I know the IP of the phpmyadmin MySQL DB but it is not connecting. How can I get the arduino to connect to the DB?

I've been working on this for weeks and I'm three seconds from throwing my computer against a wall! This is very frustrating! I'm at the end of my rope and I hope you appreciate that I've exhausted just about every other learning option...help!

I'm using modified PHP files that the Sketch author recommended as well. I can see the empty table on my site. I just can't get the data into the DB.



via Chebli Mohamed

Getting rows of a day by timestamp, Day/Minute of certain pattern

id   name     quantity    timestamp
1    item1     2         2015-06-01 20:00:00
2    item2     5         2015-06-01 22:30:00
3    item3     2         2015-06-02 20:00:00
4    item4     7         2015-06-02 20:30:00
5    item5     9         2015-06-02 21:30:00

This is an example database, 'timestamp' is in datetime format and contains varying values. Note that the table contains various date and time data. How do i get all the rows of one day and of certain minute(above eg: 30) only, eg how can i select all the rows with timestamp 2015-06-01 **:30:00, here ** = hour any help, thanks.



via Chebli Mohamed

How to install MySQL Http Plugin on Windows 7?

I have MySQL 5.7 installed on my Windows 7 system. Can anyone help me with the instructions to install the experimental Http Plugin?



via Chebli Mohamed

HttpURLConnection to use connect to php Error:Server returned HTTP response code: 500 for URL:

I'm using java to read from an excel file and put that data into variables, then send those variables to php where it will get processed and inserted into a mysql database. The database wont allow me to directly insert into the database, so I'm doing a work-around. I get this error when I run my program. "Server returned HTTP response code: 500 for URL:" This happens when it gets to the conn.getOutputStream(); If someone knows how i can fix this on the server side please let me know so that I can try to fix it

String link="http://website/directory/file.php";
            String data  = URLEncoder.encode("fName", "UTF-8")
                    + "=" + URLEncoder.encode(fName, "UTF-8");
            data += "&" + URLEncoder.encode("lName", "UTF-8")
                    + "=" + URLEncoder.encode(lName, "UTF-8");
            data += "&" + URLEncoder.encode("SID", "UTF-8")
                    + "=" + URLEncoder.encode(SID+"", "UTF-8");
            data += "&" + URLEncoder.encode("email", "UTF-8")
                    + "=" + URLEncoder.encode(email, "UTF-8");
            data += "&" + URLEncoder.encode("major", "UTF-8")
                    + "=" + URLEncoder.encode(major, "UTF-8");
            data += "&" + URLEncoder.encode("year", "UTF-8")
                    + "=" + URLEncoder.encode(year, "UTF-8");
            data += "&" + URLEncoder.encode("isPaid", "UTF-8")
                    + "=" + URLEncoder.encode(isPaid+"", "UTF-8");
            data += "&" + URLEncoder.encode("isNational", "UTF-8")
                    + "=" + URLEncoder.encode(isNational+"", "UTF-8");
            URL url = new URL(link);
            //Did the CookieHandler just in case the server wants them
            CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);

            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write( data );
            System.out.println("data was passed");
            wr.flush();
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line = null;

            // Read Server Response I'm using echo . ie: echo "yes";
            while((line = reader.readLine()) != null)
            {
                sb.append(line);
                break;
            }
            System.out.println(sb.toString());
        }
            if(sb.toString().equals("yes"))
            {
                ttlAffected++;
            }
            else if(sb.toString().equals("no"))
            {
                System.out.println("Student ID: "+array.get(rowOn).getSID()+" already exists");
                fail.add(array.get(rowOn).getSID());
            }
            else if(sb.toString().equals("error"))
            {
                System.out.println("An unknown error occured");
                fail.add(array.get(rowOn).getSID());
            }
            else
            {
                System.out.println("IDk what happened        "+  sb.toString());
            }

Also, here is the php side

    <?php
    $con=mysqli_connect("host","username","password","database");
    if (mysqli_connect_errno($con))
{
   echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$_SESSION['fName']=$_POST['fName'];
$_SESSION['lName']=$_POST['lName'];
$_SESSION['SID']=$_POST['SID'];
$SID=$_SESSION['SID']
$_SESSION['email']=$_POST['email'];
$_SESSION['major']=$_POST['major'];
$_SESSION['year']=$_POST['year'];
$_SESSION['isNational']=$_POST['isNational'];
$_SESSION['isPaid']=$_POST['isPaid'];


$sql ="SELECT * FROM Registered_Members15 WHERE SID='$SID'";
$result = mysqli_query($com,$sql);
if(mysqli_num_rows($result)==0)
{
                                        $query_member = "INSERT INTO Events15(id,SID) VALUES (?, ?)";
                                        $stmt_member = mysqli_prepare($con,$query_member);
                                        mysqli_stmt_bind_param($stmt_member, "si" , $_SESSION['email'], $_SESSION['SID']);
                                        mysqli_stmt_execute($stmt_member);
                                        $affected_rows_mem = mysqli_stmt_affected_rows($stmt_member);
                                        mysqli_stmt_close($stmt_member);

                                        $query = "INSERT INTO Registered_Members15(ID,first_name,last_name,SID,email,paid_chapter,paid_national,major,year)  VALUES (NULL,?, ?, ?, ?, ?, ?, ?, ?)";
                                        $stmt = mysqli_prepare($con, $query);
                                        mysqli_stmt_bind_param($stmt, "ssisiiss", $_SESSION['fName'], $_SESSION['lName'], $_SESSION['SID'], $_SESSION['email'], $_SESSION['isPaid'], $_SESSION['isNational'], $_SESSION['major'], $_SESSION['year']);
                                        mysqli_stmt_execute($stmt);

                                         $affected_rows = mysqli_stmt_affected_rows($stmt);
                                        if($affected_rows == 1 && $affected_rows_mem == 1)
                                        {
                                                echo "yes";
                                        }
                                        else
                                        {
                                            echo "error";
                                        }
}else{
    echo "no";
}

mysqli_close($con);

?>

I believe this is all right but I do want to ask if someone could check if i did something wrong.



via Chebli Mohamed

My sql , join tables with dynamic fields

i want to use @mm as global scope var and use it value in second and 3rd tables.(even dummy field to join ) anyone has idea? thanks

select a.totalL,b.totalR, @mm:=c.plac from users as c inner join (SELECT SUM(amnt) as totalL ,type,@mm as MN FROM gb WHERE amnt> 0 AND plac_id LIKE concat(@mm,'1%')

AND (DATE(date1) BETWEEN DATE('2015-06-23 00:00:00') AND DATE('2015-08-13 23:59:59') ) AND type=10 ) as a on c.plac = a.MN inner join (SELECT SUM(amnt) as totalR ,type,@mm as MN FROM gb WHERE amnt> 0 AND plac_id LIKE concat(@mm,'2%') AND (DATE(date1) BETWEEN DATE('2015-06-23 00:00:00') AND DATE('2015-08-13 23:59:59') ) AND type=10 )as b on a.type = b.type



via Chebli Mohamed

How can I implement my own interface for OpenID that uses a MySQL Database instead of In memory storage

So I'm trying to use the OpenID package for Golang, located here: http://ift.tt/1DOG62f

In the _example it says that it uses in memory storage for storing the nonce/discoverycache information and that it will not free the memory and that I should implement my own version of them using some sort of database.

My database of choice is MySQL, I have tried to implement what I thought was correct (but is not, does not give me any compile errors, but crashes on runtime)

My DiscoveryCache.go is as such:

package openid

import (
    "database/sql"
    "log"
    //"time"

    _ "http://ift.tt/1kNPaoi"
    "http://ift.tt/1DOG62i"
)

type SimpleDiscoveredInfo struct {
    opEndpoint, opLocalID, claimedID string
}

func (s *SimpleDiscoveredInfo) OpEndpoint() string { return s.opEndpoint }
func (s *SimpleDiscoveredInfo) OpLocalID() string  { return s.opLocalID }
func (s *SimpleDiscoveredInfo) ClaimedID() string  { return s.claimedID }

type SimpleDiscoveryCache struct{}

func (s SimpleDiscoveryCache) Put(id string, info openid.DiscoveredInfo) {
    /*
       db, err := sql.Query("mysql", "db:connectinfo")
         errCheck(err)
         rows, err := db.Query("SELECT opendpoint, oplocalid, claimedid FROM discovery_cache")
         errCheck(err)

       was unsure what to do here because I'm not sure how to 
       return the info properly 
    */

    log.Println(info)
}

func (s SimpleDiscoveryCache) Get(id string) openid.DiscoveredInfo {
    db, err := sql.Query("mysql", "db:connectinfo")
    errCheck(err)

    var sdi = new(SimpleDiscoveredInfo)
    err = db.QueryRow("SELECT opendpoint, oplocalid, claimedid FROM discovery_cache WHERE id=?", id).Scan(&sdi)
    errCheck(err)

    return sdi

}

And my Noncestore.go package openid

import (
    "database/sql"
    "errors"
    "flag"
    "fmt"
    "time"

    _ "http://ift.tt/1kNPaoi"
)

var maxNonceAge = flag.Duration("openid-max-nonce-age",
    60*time.Second,
    "Maximum accepted age for openid nonces. The bigger, the more"+
        "memory is needed to store used nonces.")

type SimpleNonceStore struct{}

func (s *SimpleNonceStore) Accept(endpoint, nonce string) error {

    db, err := sql.Open("mysql", "dbconnectinfo")
    errCheck(err)

    if len(nonce) < 20 || len(nonce) > 256 {
        return errors.New("Invalid nonce")
    }

    ts, err := time.Parse(time.RFC3339, nonce[0:20])
    errCheck(err)

    rows, err := db.Query("SELECT * FROM noncestore")
    defer rows.Close()

    now := time.Now()
    diff := now.Sub(ts)

    if diff > *maxNonceAge {
        return fmt.Errorf("Nonce too old: %ds", diff.Seconds())
    }

    d := nonce[20:]

    for rows.Next() {
        var timeDB, nonce string
        err := rows.Scan(&nonce, &timeDB)
        errCheck(err)

        dbTime, err := time.Parse(time.RFC3339, timeDB)
        errCheck(err)

        if dbTime == ts && nonce == d {
            return errors.New("Nonce is already used")
        }
        if now.Sub(dbTime) < *maxNonceAge {
            _, err := db.Query("INSERT INTO noncestore SET nonce=?, time=?", &nonce, dbTime)
            errCheck(err)
        }
    }

    return nil

}

func errCheck(err error) {
    if err != nil {
        panic("We had an error!" + err.Error())
    }
}

Then I try to use them in my main file as:

import _"http://ift.tt/1HKaaqv"

var nonceStore = &openid.SimpleNonceStore{}
var discoveryCache = &openid.SimpleDiscoveryCache{}

I get no compile errors but it crashes

I'm sure you'll look at my code and go what the hell (I'm fairly new and only have a week or so experience with Golang so please feel free to correct anything)

Obviously I have done something wrong, I basically looked at the NonceStore.go and DiscoveryCache.go on the github for OpenId, replicated it, but replaced the map with database insert and select functions

IF anybody can point me in the right direction on how to implement this properly that would be much appreciated, thanks! If you need anymore information please ask.



via Chebli Mohamed

How to make my index page load images without reloading page, every time user logs out, whose locations are stored in database?

My index page, that is login and signup page has 3 images, whose locations are stored in database, loads those images automatically if the page is refreshed. For example, when I open the index page as a user for login, the images are loaded and shown without any problem. But when I logout, the images disappear, which actually should have been there. Further if I refresh the page, they are shown again.

So the only problem that I can see is related with REFRESH/RELOAD. I have used session functions for logging out. When a user logs out, the session is destroyed and index page appears, because I used the header(""); function, which contains the address of index page. So when user clicks log out, it opens the index page, without refreshing it (I assume so). So images are not shown. They need a page relaod/refresh for appearing.

How to solve this problem?



via Chebli Mohamed

Xampp Mysql and Apache not Working - How to backup database

I'm having trouble with my Mysql and Apache server here for a week already. Tried to look for every possible solutions in the internet like changing ports and everything. Still no luck. I would like to reinstall Xampp, the problem is, I have important databases which do not have any backups yet. Is there a way to backup these databases without having my apache and mysql started?



via Chebli Mohamed

Update row with minimum value sql

I have this table:

-----------------------
summonerId | timestamp
-----------------------
253222     | 14395235091096
929112     | 14395235091056
(...)

I want to update the row with the lower timestamp but I can't, when I do this

UPDATE summoners_shell 
SET 
summonerId = ".$s.",
timestamp = ".$time." 
WHERE timestamp = (SELECT MIN(timestamp))

It updates all rows! Why? How do I do what I want?



via Chebli Mohamed

send email to user register using php

I'm building a registration form using MySQL to store data and work perfectly. when users register will be sent a verification email to activate user accounts. the problem is not the verification email sent to the email users but user data and the activation code can get into mysql.

Here code for insert.php

<?php

//panggil file config.php untuk menghubung ke server
include('config.php');

//tangkap data dari form
$nama = $_POST['nama'];
$username = mysql_real_escape_string($_POST['username']);
$email = mysql_real_escape_string($_POST['email']);
$alamat = $_POST['alamat'];
$telp = $_POST['telp'];
$password = mysql_real_escape_string($_POST['password']);

// regular expression for email check
$regex = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/';
if(preg_match($regex, $email))
{ 
$password=md5($password); // encrypted password
$activation=md5($email.time()); // encrypted email+timestamp
$count=mysql_query("SELECT id_user FROM user WHERE email='$email'");
// email check
if(mysql_num_rows($count) < 1)
{
$query = mysql_query("insert into user (nama,email,telp,password,alamat,username,activation) VALUES('$nama', '$email', '$telp', '$password', '$alamat', '$username', '$activation')") or die(mysql_error());

if ($query) {
    header('location:index.php');
}
// sending email
include ('sendEmail.php');
$to=$email;
$subject="Email verification";
$body='Hi, <br/> <br/> Silakan verifikasi dengan klik link di bawah ini. <br/> <br/> <a href="http://localhost/LAPAN-Project/verify.php?code=' . $activation . '">Verifikasi</a>';

sendEmail($to,$subject,$body);
$msg= "Registration successful, please activate email."; 
}
else
{
$msg= 'The email is already taken, please try new.'; 
}

}
else
{
$msg = 'The email you have entered is invalid, please try again.'; 
}

// HTML Part
//}
?>

and here the code sendEmail.php

<?php
function sendEmail($to,$subject,$body)
{
   require ('class.phpmailer.php');
$from       = "me@kumistebal.web.id";
$mail       = new PHPMailer();
$mail->IsSMTP(true);            // use SMTP
$mail->IsHTML(true);
$mail->SMTPAuth   = true;                  // enable SMTP authentication
$mail->Host       = "ssl://smtp.gmail.com"; // SMTP host
$mail->Port       =  465;                    // set the SMTP port
$mail->Username   = "*********@gmail.com";  // SMTP  username
$mail->Password   = "*********";  // SMTP password
$mail->SetFrom($from, 'From Name');
$mail->AddReplyTo($from,'From Name');
$mail->Subject    = $subject;
$mail->MsgHTML($body);
$address = $to;
$mail->AddAddress($email, $to);
if(!$mail->Send())
        echo "Mailer Error: " . $mail->ErrorInfo;
    else
        echo "Message has been sent";
}    

?>

Does anyone have any idea how to do?



via Chebli Mohamed

Raw mysql queries with all the clause without writing every attribute in play framework (java)

So In Java (play framework) I want to write a raw MySQL query to get all attributes from myTable with a WHERE clause (and possibly other clauses)

I am using RawSqlBuilder. If I use unparsed, then I Cannot have any conditional clause (such as where). See example below

String sql = "SELECT * FROM myTable"; // here i CANNOT add a WHERE atOne = 5 since I am using unparsed. It doesn't work

RawSql rawSql =   
                 RawSqlBuilder  
                    .unparsed(sql)
                    .columnMapping("attOne", "attOne")
                    .columnMapping("attTwo", "attTwo")
                    .create();  

Query<myTableModel> query = Ebean.find(myTableModel.class);
query.setRawSql(rawSql);

List<myTableModel> list = query.findList();

However, if I use parsed, then I CAN use my WHERE clause but I Cannot use * after my Select. Instead of * I must write ALL the attributes names that I want to get. But this is VERY inconvenient. What if I have 25 attributes? example below

String sql = "SELECT attOne, attTwo FROM myTable WHERE attOne = 5"; // as you can see here, I MUST put attOne, attTwo else it won't work

RawSql rawSql =   
                 RawSqlBuilder  
                    .parsed(sql)
                    .columnMapping("attOne", "attOne")
                    .columnMapping("attTwo", "attTwo")
                    .create();  

Query<myTableModel> query = Ebean.find(myTableModel.class);
query.setRawSql(rawSql);

List<myTableModel> list = query.findList();

My question is, how can I use * along with WHERE clause and map it to my myTableModel

If I can't, is there a way to access sql db with raw queries in java?



via Chebli Mohamed

Multiple markers at this line help meeee

helpm me :(

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //Menemukan lokasi tombol di activity_main.xml
    Button tombol = (Button) findViewById(R.id.button1);

    //Menangkap Klik pada Tombol
    tombol.setOnClickListener(new OnClickListener() {

 @Override
 public void onClick(View arg0) {
     //TODO Auto-generated method stub
 Intent Intentku = new Intent(MainActivity.this,AktivitasBaru.class);
 startActivity(Intentku);

 } <<<<<<<<<< eror    

    }
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}

Multiple markers at this line - Syntax error, insert ")" to complete Expression - Syntax error, insert ";" to complete Statement - Syntax error, insert "}" to complete ClassBody



via Chebli Mohamed

Syntax error in MySQL 5.5

I did this simple SQL Query succesfuly from PHP Admin 4 years ago with SQL 5.1. Now I try the same in SQL 5.5 for my new project and getting a syntax error. Mayby somebody can help me to get in the game again.Thanks

SQL query:

CREATE TABLE `mfl` (
`id` INT NOT NULL,
`rank` MEDIUMINT NOT NULL ,
PRIMARY KEY ( `id` )
) TYPE = MYISAM 

MySQL said: Documentation

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'TYPE = MYISAM' at line 5



via Chebli Mohamed

subtract 1 month from a DB column symfony2

I am trying to write a query in order to get all the data whose date is greater than 11 months and less than 12 month. I have tried the query below which returns date difference in days. Is there any way I can check on months ??

$qb ->select("pj,DATE_DIFF(CURRENT_TIME(), pj.date) as dt)
    ->from("PrevJbs", "pj");



via Chebli Mohamed

PHP Script is connecting to database but will not return a table value despite being connected.

        <!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="http://ift.tt/1P3hXG4">
        <script src="http://ift.tt/1JJRCNi"></script>
        <link rel="stylesheet" href="http://ift.tt/1I7E37E">
    </head>
    <body>
        <!-- Always shows a header, even in smaller screens. -->
        <div class="mdl-layout mdl-js-layout mdl-layout--fixed-header">
          <header class="mdl-layout__header">
            <div class="mdl-layout__header-row">
              <!-- Title -->
              <span class="mdl-layout-title">Forum</span>
              <!-- Add spacer, to align navigation to the right -->
              <div class="mdl-layout-spacer"></div>
              <!-- Navigation. We hide it in small screens. -->
              <nav class="mdl-navigation mdl-layout--large-screen-only">
                <a class="mdl-navigation__link" href="">Default Subforum2</a>
              </nav>
            </div>
          </header>
          <div class="mdl-layout__drawer">
            <span class="mdl-layout-title">Forum</span>
            <nav class="mdl-navigation">
              <a class="mdl-navigation__link" href="">Browse Subforums</a>
              <a class="mdl-navigation__link" href="">Search For Post</a>
            </nav>
          </div>
          <main class="mdl-layout__content">
            <div class="page-content">
                <!-- Your content goes here -->
                <?php
                    include("dbforforum.php");
                    $subForum = "";
                    $results = $mysqli->query("SELECT * FROM `SubForumList`");
                    echo $results;
                    for ($i = 0; $i < $results->num_rows; $i++)
                    {
                        $results->data_seek($i);
                        $row = $results->fetch_assoc();
                        $subForum = $row['Name'];
                        echo $subForum;
                        echo $subForum;
                    }
                ?>
            </div>
          </main>
        </div>
    </body>
</html>

I'm trying to echo HTML within PHP the row 'subForum' of my SQL table $row['subForum'] every time this loop goes through, however, for some reason it is not connecting.

Even in dbforforum.php, my database config file, it is showing that it connected successfully:

<?php

$mysqli = new mysqli("localhost", "root", "", "Forum");
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
echo "Connected successfully";

?>

I am very, very confused by this. Any help is appreciated.

Note: I recently switched to Mac from Windows (not my choice), and have therefore gone from WAMP to MAMP. Not sure if this has to do with anything.



via Chebli Mohamed

Rails: Autocreate associated records as soon as parent record is saved

I'm trying to automatically create records in a child table as soon as a parent record is saved but I'm stuck and need a help how to do this.

So my table hierarchy of the Orgs is like Org->Brand->Restaurant (eg. Americana(Org) -> KFC(Brand) ->San Francisco(Restaurant)).

A Brand has many menus and Menu belongs to a Brand. Now I want to cascade menu for each Restaurant from the Brand's menu because I want to be manage price by the Restaurant. In order to do that, I created a 'local_menus' table which contains restaurant_id and menu_id so that I don't have to duplicate some data and changes in the local_menus will not be affected to its parent.

The question is how do I auto create records in 'local_menus' as soon as a parent menu is created. To be more specific, when I create a menuA, the same menu needs to be created automatically for all the restaurants under the brand. Appreciate your support.

MODELS:

class LocalMenu < ActiveRecord::Base
  belongs_to :restaurant
  belongs_to :menu
end

class Menu < ActiveRecord::Base
    has_many :local_menus
    belongs_to :brand
end

class Restaurant < ActiveRecord::Base
    has_many :menus, through: :local_menus
end

TABLES:

local_menus
    t.integer  "restaurant_id",  limit: 4
    t.integer  "menu_id",        limit: 4
    t.boolean  "active_status",    limit: 1
    t.boolean  "instock_status", limit: 1
    t.integer  "price",          limit: 4


menus
    t.integer  "restaurant_id",      limit: 4
    t.string   "name",               limit: 255
    t.integer  "price",              limit: 4
    t.integer  "brand_id",           limit: 4
    t.integer  "category_id",        limit: 4
    t.text     "description",        limit: 65535
    t.boolean  "active_status",      limit: 1
    t.date     "start_date"
    t.date     "end_date"

restaurants
    t.string   "name",          limit: 255
    t.string   "name_kana",     limit: 255
    t.integer  "price",         limit: 4
    t.boolean  "active_status", limit: 1
    t.integer  "brand_id",      limit: 4



via Chebli Mohamed

How can I use query in router.php of codeigniter?

I have a list of router such as:

$route['mobile'] = 'parrent_list';
$route['tables'] = 'parrent_list';
$route['laptop'] = 'parrent_list';
$route['gamer'] = 'parrent_list';

My router.php have about 100 row. I dont't want set it manual. So i want know how can I use query in router to get my categories in database. Example:

require_once( BASEPATH .'database/DB'. EXT );
$db =& DB();
$query = $db->get( 'categories' )->where( 'parrent_id', 0 );
$result = $query->result();
foreach( $result as $row )
{
    $route[ $row->slug ]                 = 'parrent_list;
    $route[ $row->slug.'/:any' ]         = 'parrent_list;

}

I try but it don't work. Thanks all.



via Chebli Mohamed

Laravel 5 successful seed but nothing return from database

I successfully seeded data in mysql table but nothing return from the database in view. I've tried to drop and re-migrate tables multiply times and it did not work.

I also tried to enrolled on my website and it worked! The view could return me the user information I enrolled on the web but not those I seeded. Meanwhile, when I checked in mysql, the database returned me those data I seeded but not the data I enrolled.

I am really confused about this problem and wish someone could enlighten me on this problem, thanks.



via Chebli Mohamed

Using "&" character in MySQL Query

Anyway to get around using "&" in a query? When I try this query, an undefined variable error is returned.

"SELECT DISTINCT model FROM carval_data WHERE make = 'A&W' ORDER BY CAST(model AS CHAR)"



via Chebli Mohamed

PHP string variable in MySQL Like query

so I'm attempting to take in a PHP variable and do insert it into a simple sql query, but it's not working and I can't seem to figure out the issue.

NOTE: I know this code has security issues

staff_model.php file:

function getSearches($searchterm) {
        $sql = "SELECT * 
                FROM people 
                WHERE name 
                LIKE '%{$searchterm}%'";
        $query = $this->db->query($sql);
        return $query;
    }

My table has several columns but it has columns like id, name, subject, type. The way I get $searchterm is something like

var searchText = document.getElementById('custom-search-text').value; 

in my javascript file and I'll pass it to users.php through

$.get(url+"/api/users/staff", {id: id, name: name, type: type, subject: subject, search: searchText})

Just to make sure everything else was working correctly, I hardcoded something for searchTerm (so something like $sql = "SELECT * FROM people WHERE name LIKE 'Matt'") and I did get the correct results.

Something else I tried was $sql = "SELECT * FROM people WHERE name LIKE $searchTerm" and this didn't work.

Any ideas on how I can get it to work with wildcards?



via Chebli Mohamed

mysql data exports in one column only in excel file

Whenever I click the button to export the data to an excel file, all the data is showing only in one column in excel. How can I make each columns separated? Please help. Thank you

Here is my code:

<?php

require_once("db.php");

$contents="ITEM CODE,ITEM DESC,UNIT CODE,UNIT DESC,PRODUCT CODE,DEPARTMENT,SUB DEPARTMENT,CLASS,SUB CLASS,COST,MARK UP,PRICE,ITEM TYPE\n";

$user_query = ibase_query('SELECT ITEM_CODE,ITEM_DESC,UNIT_CODE,UNIT_DESC,PRODUCT_CODE,DEPARTMENT,SUB_DEPARTMENT,CLASS,SUB_CLASS,COST,MARKUP,PRICE,ITEM_TYPE FROM ITEM_MASTER');

while($row = ibase_fetch_assoc($user_query))
{
$contents.=$row["ITEM_CODE"]."/t";
$contents.=$row["ITEM_DESC"]."/t";
$contents.=$row["UNIT_CODE"]."/t";
$contents.=$row["UNIT_DESC"]."/t";
$contents.=$row["PRODUCT_CODE"]."/t";
$contents.=$row["DEPARTMENT"]."/t";
$contents.=$row["SUB_DEPARTMENT"]."/t";
$contents.=$row["CLASS"]."/t";
$contents.=$row["SUB_CLASS"]."/t";
$contents.=$row["COST"]."/t";
$contents.=$row["MARKUP"]."/t";
$contents.=$row["PRICE"]."/t";
$contents.=$row["ITEM_TYPE"]."\n";
}

$contents = strip_tags($contents); 

header("Content-Disposition: attachment; filename=Sample Report ".date("d-m-Y").".xls");
print $contents;

?>



via Chebli Mohamed

Index was outside the bounds of the array . But All arrays are correct

Hello i'm getting "Index was outside the bounds of the array" if i'm putting value (i) in itemsWS.getItemInfo(itemLis[i].ToString())

object[] itemDetails;
object[] itemLis = itemsWS.searchItem("", "bread", "all");
int xs = 35;
int clefts = 0;

for (int i = 0; i < itemLis.Length; i++)

{
    itemDetails = itemsWS.getItemInfo(itemLis[i].ToString());
    Button myButtons = new Button();
    myButtons.Click += delegate
    {

        dataGridView1.ColumnCount = 11;

        dataGridView1.Columns[0].Name = "Item Code";
        dataGridView1.Columns[1].Name = "Description";
        dataGridView1.Columns[2].Name = "Sale Price";
        dataGridView1.Columns[3].Name = "Category";
        dataGridView1.Columns[4].Name = "Type";
        dataGridView1.Columns[5].Name = "Status";
        dataGridView1.Columns[6].Name = "Low Count";
        dataGridView1.Columns[7].Name = "Medium Count";
        dataGridView1.Columns[8].Name = "High Count";
        dataGridView1.Columns[9].Name = "Item Picture";
        dataGridView1.Columns[10].Name = "TEST";

        //here is where i'm getting error if i put i on the []

        itemDetails = itemsWS.getItemInfo(itemLis[i].ToString());

        //

        dataGridView1.Rows.Add(itemDetails);
        MessageBox.Show("data grid displayed!");

    };


    myButtons.Text = itemDetails[1].ToString() + "\n  " + itemDetails[2].ToString();
    myButtons.Top = cleft * 180;
    myButtons.Left = 70;
    myButtons.Location = new Point(xs, clefts);
    myButtons.Size = new Size(100, 60);
    tabPage1.Controls.Add(myButtons);
    xs += 135;

    if (xs >= 537)
    {
        xs = 35;
        clefts += 80;
    }

(this is the database)

enter image description here

The problem is if I replace [i] with [0]. It will only display the first value item in the database

(here is the GUI if i replaced [i] with [0]) Any button clicked would repeat the same output

enter image description here

Please any help would be greatly appreciated. I'm trying to display items from MySQL using new buttons which was generated that would be displayed on the datagridview. Thanks

Note : that itemsWS is a web service coming from

private KPWSItems itemsWS = new KPWSItems();



via Chebli Mohamed

Get data from database if the input has one or more question marks.

I'm tying to get inputs from a database if they have question marks on the inside. For example:

GET FROM table 
WHERE input = (As long as the input as a question mark inside)

For example, if the input is something like, "What's your name?", it'll get it from the database. But if it only says, "What's your name.", it won't get it from the database. How do I do that?



via Chebli Mohamed

Laravel 5 two-way table login

I am trying to configure a laravel 5 app that will login users based on their username with password, if the username and password method fails the app will try to check the other table if the data in the username variable is available in my case their employee_id. So here is my code for logging users in with the conventional laravel method:

 $authdetails = array(
            'email' => $request->input('email'),
            'password' => $request->input('password')
         );
         if (Auth::attempt($authdetails)) {
             // Authentication passed...
             return redirect()->to('/home');
         }
        else {
              return back()->with('error', 'Invalid username or password')->withInput();
          }
     }

How do I login users with a different table if the first method fails?



via Chebli Mohamed

mysql query using alias throws error

Running the following query

SELECT p.id as pid,p.name as pname, p.email,p.phone,p.created as pcreated,
p.updated as pupdated, GROUP_CONCAT(g.name) AS groups FROM ft_smsender_persons p 
JOIN ft_smsender_persons2groups AS p2g ON p.id = p2g.person_id JOIN ft_smsender_groups AS g ON g.id = p2g.group_id 
WHERE 1=1 AND deleted = 0 AND p.id as pid LIKE '%7%' OR pname LIKE '%7%' OR 
email LIKE '%7%' OR phone LIKE '%7%' OR pcreated LIKE '%7%' 
OR pupdated LIKE '%7%' OR groups LIKE '%7%' group by pname, email ORDER BY pid asc

gives me an error on p.id as pid LIKE '%7%'

If I use it like pid like %7%, it gives me an error saying pid is unknown column

The query is generated dynamically so I have very less scope how to fix it through my code; is there any way in mysql?



via Chebli Mohamed

MySQL Join 2 tables with duplicate rows but prioritise rows from left table

I have 2 tables. One is a generic price list for all customers, the other is a special price list for selected customers.

An example of them:

Special List

ID | STOCK_CODE | PRICING_REF | PRICE
1  | 1234       | CUST001     | 1.00
2  | 1235       | CUST001     | 2.00

Generic List

ID | STOCK_CODE | PRICE
1  | 1234       | 4.99
2  | 1241       | 4.99
3  | 1249       | 5.99

I would like to joint the 2, which I am currently doing. However, rather than have just one list displayed I'd like to merge the 2 but only show the price from the special list, if the stock code matches and there is a price available in that row.

My statement so far is:

SELECT * FROM stock s LEFT JOIN price p ON p.stock_code = s.stock_code WHERE PRICING_REF = '$pricing_ref' AND s.stock_code = '$ref'

This only returns the price of items from the special list, missing the remaining items from the generic list.

Currently, if I do a search for items : '%1%' it will return stock_code 1234 and 1235, but not 1241 and 1249 which I'd also like included. However, the price for 1234 must come from the Special List, not the Generic List.



via Chebli Mohamed

Query SQL runs slow with group by in MySQL

I have a sql below, it runs about 30 mins, which is too long for me.

SELECT LPP.learning_project_pupilID, SL.serviceID, MAX(LPPO.start_date), SUM(LPPOT.license_mode_value) totalAssignedLicenses
      FROM t_services_licenses SL 
      INNER JOIN t_pupils_offers_services POS ON POS.service_licenseID = SL.service_licenseID 
      INNER JOIN j_learning_projects_pupils_offers LPPO ON LPPO.learning_project_pupil_offerID = POS.learning_project_pupil_offerID
      INNER JOIN j_learning_projects_pupils LPP ON LPPO.learning_project_pupilID = LPP.learning_project_pupilID
      INNER JOIN j_learning_projects_pupils_offers_tracking LPPOT ON LPPOT.pupil_offer_serviceID = POS.pupil_offer_serviceID
      INNER JOIN t_filters_items FI ON FI.itemID = LPP.learning_project_pupilID_for_filter_join  
      WHERE FI.filterID = '4dce2235-aafd-4ba2-b248-c137ad6ce8ca' 
      AND SL.serviceID IN ('OnlineConversationClasses', 'TwentyFourSeven')
      GROUP BY LPP.learning_project_pupilID, SL.serviceID

I have viewed the profile result, "copying temp data " wasted almost all the time. I know the reason is caused by "group by" functionality, So I did some changes below to verify it: I removed the MAX, SUM functions as well as the Group By sql and ran it, the time is only cost about 40 seconds, which is ok for us. So here , I want to know, if there are some other methods to make above sql execute much more faster?

more info, you can find here: http://ift.tt/1IMaMjk



via Chebli Mohamed

Golang set a maps key as a variable for its value

I need to go through an html forms input values and place them into an mysql datbase. Which I'm currently using r.Form to get a map. So that i don't have to use r.Form.Get("date") for each which works but when i try to put the values into a database. It compiles just fine but i get sql: converting argument #0's type: unsupported type []string, a slice after i click submit in the browser. I can get around this by doing

`date := strings.Join(m["date"], "")`

but doing that for 30+ values especially since some of the submited values will be created from previous database entries using html templates. If i have to change or add more later seems like there must be a more efficient way I've seen for key, val := range m {} but unfortunately I've only been doing this for about a week and i can't figure out how to keep the values and change the variable they get set to after each iteration. So that after

for key, val := range m {
x := m[key]
}

so that it will put out the equivalent

keyname := keyvalue

changing the keyname each time to be the same as the keyname in the map ie

date := 2015-8-13
time := 18:56:11

or if there's an easier way around this error then to create a varible for each one.



via Chebli Mohamed

MYSQL Order By after GROUP by not working

mysql> select manga_source_id,manga_episode_name,manga_episode_number from manga_chapter;
+-----------------+--------------------------------------+----------------------+
| manga_source_id | manga_episode_name                   | manga_episode_number |
+-----------------+--------------------------------------+----------------------+
|               5 | A Method to Make the World Gentle 1  |                    1 |
|               5 | A Method to Make the World Gentle 2  |                    2 |
|               5 | A Method to Make the World Gentle 3  |                    3 |
|               5 | A Method to Make the World Gentle 5  |                    5 |
|               5 | A Method to Make the World Gentle 6  |                    6 |
|               5 | A Method to Make the World Gentle 7  |                    7 |
|               5 | A Method to Make the World Gentle 8  |                    8 |
|               5 | A Method to Make the World Gentle 9  |                    9 |
|               5 | A Method to Make the World Gentle 10 |                   10 |
|               5 | A Method to Make the World Gentle 11 |                   11 |
|               5 | A Method to Make the World Gentle 12 |                   12 |
|               5 | A Method to Make the World Gentle 13 |                   13 |
|               5 | A Method to Make the World Gentle 14 |                   14 |
|               5 | A Method to Make the World Gentle 15 |                   15 |
|               5 | A Method to Make the World Gentle 16 |                   16 |
|               5 | A Method to Make the World Gentle 17 |                   17 |
|               5 | A Method to Make the World Gentle 18 |                   18 |
|               5 | A Method to Make the World Gentle 19 |                   19 |
|               5 | A Method to Make the World Gentle 20 |                   20 |
|               5 | A Method to Make the World Gentle 21 |                   21 |
|               5 | A Method to Make the World Gentle 22 |                   22 |
|               5 | A Method to Make the World Gentle 23 |                   23 |
|               5 | A Method to Make the World Gentle 24 |                   24 |
|               5 | A Method to Make the World Gentle 25 |                   25 |
|               5 | A Method to Make the World Gentle 26 |                   26 |
+-----------------+--------------------------------------+----------------------+
25 rows in set (0.00 sec)

mysql> select manga_source_id,manga_episode_name,manga_episode_number from manga_chapter GROUP by manga_source_id ORDER BY manga_episode_number DESC;
+-----------------+-------------------------------------+----------------------+
| manga_source_id | manga_episode_name                  | manga_episode_number |
+-----------------+-------------------------------------+----------------------+
|               5 | A Method to Make the World Gentle 1 |                    1 |
+-----------------+-------------------------------------+----------------------+

I tried to get the last manga_episode_number which is A Method to make the world gentle 26 however it doesn't work, even I specify ORDER by manga_episode_number DESC

How can I achieve drawing that last record, with GROUP by

thanks!



via Chebli Mohamed

Anyone solution me to collect Data from mysql Database

My Mysql Data collect code is below:

    $date = date("Y-m-d");

    public function ip2_exists() {

        global $db,$date;

        $code = $db->select("imp","id",array("date"=>$date,"ip"=>$this->ip()));
        if($code->num_rows<1){
            return false;
        }
        else {
            return true;
        }
    }

It collect the current day datas. But I want to collect the last 5 days date.I am new in php. Please help someone. Thank you



via Chebli Mohamed

PHP MySQL ORDER BY level DESC LIMIT 1 not working on all searchs

I have searched for an answer to this problem all over the web and here at Stackoverflow. Nothing seems to help. This should be a very simple function. I have multiple records with the same content EXCEPT a field called level. I want to find the record with the highest int value in level. An example would be that I have multiple records with the same userid and email but the first record starts at level 1, the next may be level 2 and then the next may be level 1 again. I want to find the record with level = 2. My code is very simple.

  $LoginRS__query=sprintf("SELECT userid, email, level FROM orders WHERE userid=%s AND email=%s ORDER BY level DESC LIMIT 1", GetSQLValueString($loginUsername, "text"), GetSQLValueString($password, "text"));

For some this works correctly, returning the record with level = 2, 3, 8, 9, whatever. For others it will only return the record with level = 1. The field level is int length 1. I'm running php Version 5.3.28 and MySQL 5.5.36

Any ideas anyone? Like most, I'm in a rush. Thanks...



via Chebli Mohamed

JSONException: End of input at character 0 of , i dont find the error in my code

i am searching for hours in the Internet and i dont know how i can handle this Error. I get empty content from my Inputstream. Maybe some one of you can look at my code where my error is.

public class SigninActivity  extends AsyncTask<String,Void,String> {
private TextView  testtext;
private Context context;
int code = 0;
View view;
String json = " ";
JSONObject jsonObj;


//flag 0 means get and 1 means post.(By default it is get.)
public SigninActivity(Context context,View view, TextView testtext) {
    this.context = context;

    this.testtext = testtext;

    this.view = view;

}

protected void onPreExecute() {


}

@Override
protected String doInBackground(String... arg0) {

        try {
            String username = (String) arg0[0];
            String password = (String) arg0[1];



            String link = "http://ift.tt/1L9RGYe";
            String data = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8");
            data += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");

            URL url = new URL(link);
            URLConnection conn = url.openConnection();

            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());

            wr.write(data);
            wr.flush();
            Log.d("JSON Input stream", json.toString());


            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            Log.d("my JSON BufferedReader", json);
            StringBuilder sb = new StringBuilder();
            String line = null;

            // Read Server Response
            while ((line = reader.readLine()) != null) {
                sb.append(line);
                Log.d("my JSON Server Response", json.toString());
                break;
            }


            this.json = sb.toString();


            return json;

        } catch (Exception e) {
            Log.e("Login Fail", e.toString());
            return new String("Exception: " + e.getMessage());
        }
    }


//@Override
protected void onPostExecute(String flag) {

    this.testtext.setText(flag);

    try
    {

        JSONObject json_data = new JSONObject(flag);
        Log.d("my", " JSON Object Parser" );
        int code= (json_data.getInt("code"));
        Log.d("my", " JSON get code");
        Log.d("my", String.valueOf(code));





        //int code =1 ;
        if(code==1)
        {
            Toast.makeText(context, "Login Successfully",
                    Toast.LENGTH_LONG).show();

            //Start des Hauptdingens
            Intent myIntent = new Intent(view.getContext(), MainActivity.class);
            // Start der Register Acitivty;
            //startActivityForResult(myIntent, 0);
            //startActivity(myIntent);
            //ActivityCompat.startActivityForResult(myIntent, 0);
            //finish();

        }
        else
        {
            Toast.makeText(context, "Sorry, Try Again",
                    Toast.LENGTH_LONG).show();
        }
    }
    catch(Exception e)
    {
        Log.e("my JSON Fail", e.toString());
    }
}

}

here i have my php file, i am not an expert at php maybe someone of you can help me :

<?php
$con=mysqli_connect("localhost","root","","my_db");
//echo "Welcome, I am connecting Android to PHP, MySQL";

if (mysqli_connect_errno($con))
{
//echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$username = $_POST['username'];
$password = $_POST['password'];



$result = mysqli_query($con,"SELECT Username FROM user where         Username='$username' and Password='$password'");



$flag['code'] =0;

if($result)
{
    $flag['code']=1;


} else {

    $flag['code'] = 0;

}

//print(json_encode($flag));
//echo json_encode($flag)


mysqli_close($con);
?>

i commented the echo lines out, because i read that this could make some errors, but this didnt help. the login with the post methode, but the resonse with flag doesnt work.

thanks for your help



via Chebli Mohamed

Why is "update foo ... where bar is null" letting multiple callers claim the same row?

I have a fairly basic query:

UPDATE the_table SET col1=[something], col2=[something else] WHERE col1 IS NULL AND col2 IS NULL;

Immediately after issuing the query, the caller does:

SELECT col3 FROM the_table where col1=[something], col2=[something else];

Unfortunately, concurrent callers are claiming the same row.

I'd rather not do a SELECT FOR UPDATE, because the [select, update, select] would involve three rpcs to the database instead of two (which is bad enough.)

I gather that some dialects of sql allow UPDATE the_table WITH(UPDLOCK), but mine (galera/MySQL) does not. I find it appalling that I'd have to go through this many DB hits to execute such a basic concept. I find that most of my searching efforts end on pages that discuss dialects that DO support UPDLOCK.

Where does it go from here?



via Chebli Mohamed

Increasing INSERT Performance in Django For Many Records of HUGE Data

So I've been trying to solve this for a while now and can't seem to find a way to speed up performance of inserts with Django despite the many suggestions and tips found on StackOverflow and many Google searches.

So basically I need to insert a LOT of data records (~2 million) through Django into my MySQL DB, each record entry being a whopping 180KB. I've scaled my testing down to 2,000 inserts yet still cant get the running time down to a reasonable amount. 2,000 inserts currently takes approximately 120 seconds.

So I've tried ALL of the following (and many combinations of each) to no avail:

  • "Classic" Django ORM create model and .save()
  • Single transaction (transaction.atomic())
  • Bulk_create
  • Raw SQL INSERT in for loop
  • Raw SQL "executemany" (multiple value inserts in one query)
  • Setting SQL attributes like "SET FOREIGN_KEY_CHECKS=0"
  • SQL BEGIN ... COMMIT
  • Dividing the mass insert into smaller batches

Apologizes if I forgot to list something, but I've just tried so many different things at this point, I can't even keep track ahah.

Would greatly appreciate a little help here in speeding up performance from someone who maybe had to perform a similar task with Django database insertions.

Please let me know if I've left out any necessary information!



via Chebli Mohamed

Getting Next and Previous from MySQL When Dates Are the Same

Right now I have a problem because importing rows to my database from an external source happens so quickly.

If more than one row is created with the exact same publish date, it is impossible to sort by date and scroll through posts sequentially.

Let's say five rows are all generated at exactly 11:22:04 AM:

  • Row 1 - 11:22:04 AM
  • Row 2 - 11:22:04 AM
  • Row 3 - 11:22:04 AM
  • Row 4 - 11:22:04 AM
  • Row 5 - 11:22:04 AM

If a visitor is viewing Row 3 and wants "the next row" I am going to ask the database to give me the next row published later than or equal to 11:22:04 AM, which is going to be Row 1 no matter what I do.

  • If I don't say "or equal to" that would just mean that the visitor would never get to see Row 4 or Row 5, which is just as bad as always getting Row 1.
  • Adding the row ID to the order by clause doesn't help because -- again -- it's just going to always give me Row 1 (if I'm currently looking at Row 3).
  • Adding a greater than or less than to the where clause doesn't help because -- for example -- if I'm looking at Row 3 and I want "the next" row but say the ID needs to be greater than 3, I'm then never going to get Row 1.

I can cheat the system by updating every row in the database published at the exact same time with the row's ID as the seconds, which would turn the above records into:

  • Row 1 - 11:22:01 AM
  • Row 2 - 11:22:02 AM
  • Row 3 - 11:22:03 AM
  • Row 4 - 11:22:04 AM
  • Row 5 - 11:22:05 AM

That actually works very well. The problem is that new rows are added every time an administrator imports data, and I can't be constantly updating the database to correct this.

My queries to get next and previous look like this:

// next row
select  t.*
from    table t
where   t.postdate  >= '{$current_date}'
and     t.postdate  < now()
and     t.id        <> {$current_id}
order   by t.postdate
limit   1

// previous row
select  t.*
from    table t
where   t.postdate  <= '{$current_date}'
and     t.postdate  < now()
and     t.id        <> {$current_id}
order   by t.postdate desc
limit   1

(Yes, I have googled this extensively and reviewed several similar questions on Stackoverflow!)



via Chebli Mohamed

Database Listener (Node.js + Socket.io)

I'm trying to learn Node.js and Socket.io

I'm trying to create a page that will display the values of a database table whenever changes are detected.

For simplicity, I would only be changing the values of the database table via PHPMyAdmin manually.

Would this be possible? If so, could you point me in the right direction so that I can try it out.



via Chebli Mohamed

Codeigniter Update using Join

I try to update my table using join in Codeigniter but I get error

Unknown column 'filter.ID_AREA' in 'where clause

$this->db->join('filter', 'filter.ID_AREA = area.ID_AREA', 'left');
$this->db->set('ID_VERIFIKASI', '3');
$this->db->where('pelayanan.ID_AREA', $ID_AREA);
$this->db->where('filter.ID_AREA', $ID_AREA);
$this->db->where('filter.ID_RAYON', $ID_RAYON);
$this->db->where('pelayanan.ID_RAYON = filter.F1_RAYON');
$this->db->where('SUBSTR(TGLRUBAH, 3, 6) = filter.F1_BULANTAHUN');
$this->db->where('ID_VERIFIKASI', '2');
$this->db->where('ID_KENDALA is not null');
$this->db->update('pelayanan');
if ($this->db->affected_rows() > 0) {
        return true;
        } 
        else {
            return false;
        }

How can I update table using join in Codeigniter?



via Chebli Mohamed

Creating a database schema that allows the admin to set 1 or many access to user

I am planning to create a database that allows many vehicles of the user to access different gates depending on their privileges.

For example, I have 5 gates namely Gate 1, Gate 2, Gate 3, Gate 4, Gate 5 and I have 3 users namely User 1, User 2 and user 3.

Scenario 1: User 1 is the owner of the city so this user should have access to all 5 gates.

Scenario 2: User 2 is just a visitor so this user shouldn't have access to all 5 gates.

Scenario 3: User 3 is one of the residents of this city, but gates 4 and 5 only allows the owners of the city, this user should only access gates 1-3 since this user is not the owner.

Scenario 4: User 3 is one the residents of this city and since user 1 is the owner he allows user 3 to access also gate 4 for them have a dinner this evening and ask the administrator that tomorrow he should remove the gate 4 privilege of this user

Based on my planning this database schema should be something like this

vehicle_info table         access_type table

  1. vehicle_id                 1. access_id
  2. plate_num                 2. name
  3. access_type
  4. validity - the validity of the access type (date only)

Then I will connect vehicle_info.access_type to access_type.name. But what if the city builds another gate namely gate 6 and also want it to add to the access_type?



via Chebli Mohamed

How do I verify that a update message is successful in MySQL with PHP?

I am having no issue running a select statement but I keep having issues running this update statement, even without where criteria being specified. I have tried everything from defining the sql statement with single quotes, concatenation, calling the sql statement via mysqli and etc but I don't get any error messages that let me know what the actual problem is. The login user has privileges to select, update, and insert so as to separate from the root user and autocommit has been turned off via mysqlworkbench. The html of course is a one page app that submits the form to itself with a select element named p_game, with one of the options being Game A.

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    echo 'Posted.';
    if ( !empty($_POST['p_game'])) {
        echo 'Got here';
        $p_game = $conn->real_escape_string(trim($_POST['p_game']));
        $sql = "UPDATE db_name.football_games set home_score = 50, away_score = 100 where name = ''$p_game''";

        try{
            $result = $conn->query($sql);
            echo $sql;
            $conn->commit();
            echo 'Commit worked.';
        }

        catch(Exception $e) {
            echo $e->getMessage();
        }

    }
    else {
        echo 'Game name not found';
    }
}



via Chebli Mohamed

Amazon RDS - max_connections

My simple question: How can I increase the possible number of connections of my Amazon RDS Database? I used a parameter group where I set

max_connections = 30000

which seems to work on the first hand, as

SHOW VARIABLES LIKE 'max_connections';

returns the expected. But when I run a stress test the monitoring metrics always show a maximum number of 1200 connections. So obviously there have to be other limiting factors, I just don't know. Any help would be highly appreciated.

My test setup: 1 Load Balancer 8 fat EC2 instances (m4.4xlarge) (which is a bit overdimensioned, but I'm still testing) 1 DB: r3.4xlarge with 140 GB memory, 1 TB storage and 10.000 provisioned IOPS

Test: 30.000 virtual users in 10 minutes making 4 requests each (2 reading the DB, 1 writing it, 1 not using the DB). Fails after about two minutes because of too many errors (caused by DB timeouts).

Concerning the hardware this setup should be able to handle the test requests, shouldn't it? So I hope I'm just missing the obvious and there's a parameter which has to be adapted to make everything working.



via Chebli Mohamed

How to delete all but most recent row where other columns are equal

I have a MySQL table, an excerpt of which is here:

http://ift.tt/1WnpK6F

I need to keep the most recent row for each row where the assoc_case, document, and participant are the same. For example, I only want to keep row 136 out of rows 133-136.

I'm working from this, but can't seem to adapt it for my needs:

SELECT id, assoc_case, participant, document, MAX(created) FROM `table` GROUP BY created, assoc_case, participant, document



via Chebli Mohamed

PyMySQL3 and SQLAlchemy

I have a simple script I'd like to run

connection_string = 'mysql+pymysql://example@example.com'
engine = sa.create_engine(connection_string)
connection = engine.connect()

query = """
    select distinct n.listname, n.notes
    from notes n 
    join run r on n.start = r.start
    where r.branch = 'B_HEAD' 
    and r.start > '2015-08-01' 
    and n.notes like '%ug%';"""
result = connection.execute(query)
for row in result:
    print("listname: {} | notes: {}".format(row['listname'], row["notes"]))

The problem is that PyMySQL isn't Python3 compatible. There is, however, a PyMySQL3.

but if I try to use that module as my connector I get

sqlalchemy.exc.NoSuchModuleError: Can't load plugin: sqlalchemy.dialects:mysql.pymysql3

Is there a simple way to make SQLAlchemy and PyMySQL3 play nice? Baring that is there a way to create custom connectors for SQLAlchemy?



via Chebli Mohamed

My php contact form does not send

It is a simple mailing list. I added various emails to the list for testing and it does not send to any of them. It used to work at one stage. It is really old code as you can see. Any ideas how to get this working. Thanks in advance.

    <?
require_once("../conn.php");
require_once("access.php");

include_once("LeftStyles.php");

if(isset($_POST[s1]))
{
    //get the subscribers info
    $q1 = "select * from re2_agents where news = 'y' ";
    $r1 = mysql_query($q1) or die(mysql_error());

    while($a1 = mysql_fetch_array($r1))
    {
        $to = $a1[email];
        $subject = $_POST[subject];

        $headers = "MIME-Version: 1.0\n"; 
        $headers .= "Content-type: text/$a1[NewsletterType]; charset=iso-8859-1\n";
        $headers .= "Content-Transfer-Encoding: 8bit\n"; 
        $headers .= "From: $_SERVER[HTTP_HOST] <$aset[ContactEmail]>\n"; 
        $headers .= "X-Priority: 1\n"; 
        $headers .= "X-MSMail-Priority: High\n"; 
        $headers .= "X-Mailer: PHP/" . phpversion()."\n"; 

        if($a1[NewsletterType] == "plain")
        {
            $message = strip_tags($_POST[message]);
            $message .= "\n\n========================\nTo unsubscribe, use this link:\n";
            $message .= "$site_url/u.php?id=$a1[AgentID]";
        }
        else
        {
            $message = $_POST[message];
            $message .= "<br><hr width=\"100%\" size=1 color=black>Click <a href=\"$site_url/u.php?id=$a1[AgentID]\">here</a> to unsubscribe.";
        }

        $message = stripslashes($message);

        mail($to, $subject, $message, $headers);

        $i++;
    }

    //add the message to the mail archive
    $t = time();
    $q1 = "insert into re2_mail_archive set 
                    subject = '$_POST[subject]',
                    message = '$_POST[message]',
                    MailDate = '$t' ";
    mysql_query($q1) or die(mysql_error());

    echo "<center><b>$i emails was sent!</b></center><br>";
}


//get the subscribers number
$q1 = "select count(*) from re2_agents where news = 'y' ";
$r1 = mysql_query($q1) or die(mysql_error());
$a1 = mysql_fetch_array($r1);

if($a1[0] == '0')
{
    echo "<br><center><font face=verdana size=2 color=red><b>You have no subscribers at your mailing list!";
    exit();
}

?>



via Chebli Mohamed

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?

Rails_admin show child models fields in parents show page

I have Item model and I have ItemImage child model which is embedded inside of its parent.

When I open single Items page in rails_admin, it shows all of its children like this:

ItemImage #55b766556c656e12d0ac0000, ItemImage #55b766556c656e12d0ad0000, and ItemImage #55b766566c656e12d0ae0000

How to make rails_admin to show all of its children fields inside parents page? Is it possible to show them as table?

I'm using Mongoid.

How best to represent roles in the DB of a rails app?

I'm building authorization in my app and have three roles:

  • User
  • Moderator
  • Admin

What's the best way to represent this in Rails? I've thought about adding the following boolean fields to my user's table:

  • is_user
  • is_moderator
  • is_admin

And then creating is_user?, etc functions in the User model.

A user can have multiple roles (can be all three).

Can't Compile LESS to CSS with LESS2CSS Plugin on Sublime Text 3 Mac

I am using Sublime Text 3 on Mac OS Yosemite. I want to use LESS2CSS package but it not working. Here are the errors it gives:

WARNING] Please install gem 'therubyracer' to use Less.
/Library/Ruby/Site/2.0.0/rubygems/core_ext/kernel_require.rb:54:in `require': cannot load such file -- v8 (LoadError)
    from /Library/Ruby/Site/2.0.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    from /Library/Ruby/Gems/2.0.0/gems/less-2.6.0/lib/less/java_script/v8_context.rb:2:in `<top (required)>'
    from /Library/Ruby/Site/2.0.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    from /Library/Ruby/Site/2.0.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    from /Library/Ruby/Gems/2.0.0/gems/less-2.6.0/lib/less/java_script.rb:9:in `default_context_wrapper'
    from /Library/Ruby/Gems/2.0.0/gems/less-2.6.0/lib/less/java_script.rb:17:in `context_wrapper'
    from /Library/Ruby/Gems/2.0.0/gems/less-2.6.0/lib/less/loader.rb:13:in `initialize'
    from /Library/Ruby/Gems/2.0.0/gems/less-2.6.0/lib/less.rb:14:in `new'
    from /Library/Ruby/Gems/2.0.0/gems/less-2.6.0/lib/less.rb:14:in `<module:Less>'
    from /Library/Ruby/Gems/2.0.0/gems/less-2.6.0/lib/less.rb:9:in `<top (required)>'
    from /Library/Ruby/Site/2.0.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    from /Library/Ruby/Site/2.0.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    from /Library/Ruby/Gems/2.0.0/gems/less-2.6.0/bin/lessc:3:in `<top (required)>'
    from /usr/bin/lessc:23:in `load'
    from /usr/bin/lessc:23:in `<main>'

I've installed Node.js and installed less, but it is still not working.

Cannot find my mistake with jQuery autocomplete and Rails 4

router

  resources :pcps  do
    collection do
      get 'autocomplete'
    end
  end

controller

def autocomplete
    @pcps = Pcp.order(:last).where("last like ?", "%#{params[:term]}%")
    render json: @pcps.map(&:full_name)
end

View

= f.text_field :pcp, data: {autocomplete_source:  '/pcps/autocomplete'}

Coffee script

This code works

jQuery ->
  $('#sched_pcp').autocomplete
    source: ["Atest", "Btest","Ctest","Dtest","Btest1","Btest2"]

This code does not work.

jQuery ->
  $('#sched_pcp').autocomplete
    source: $('#sched_pcp').data('autocomplete-source')

I am using ruby 2.2 and rails 4.2 The url '/pcps/autocomplete' returns the correct data. Can someone help me see my mistake please? or maybe give me an idea how to debug it.

How do I seed a unique record ONLY via my seeds.db?

I have the following code in my seeds.rb used to create a record in my basic Rails app via seeding.

Post.create( title: "Unique Title!", body: "this is the most amazingly unique post body ever!" )

When running the rake db:seed command, it obviously seeds the db with this data. My question is how do I add a check or safeguard in the code so that it only enters that once, i.e. as a unique? If I rerun rake db:seed, I don't want add that same entry again.

Thanks

Ruby HTTPS Post issue

I have two codes (variable info masked intentionally), the first one I receive the response with 200 code return, but second one I get 403 forbidden, any idea?

def get_token()
    http = Net::HTTP.new(server, 443)
    http.use_ssl = true
    http.verify_mode = OpenSSL::SSL::VERIFY_NONE if http.use_ssl?

    #path(a.k.a) ->http://ift.tt/1DXPdIx'
    path = '/rest/fastlogin/v1.0?app_key=' + app_key + '&username=%2B' + username + '&format=json'
    puts path

    headers = {'Content-Type'=> 'application/x-www-form-urlencoded', 'Authorization' => password }

    resp, data = http.post(path, data, headers)

    puts 'Code = ' + resp.code
    puts 'Message = ' + resp.message

    resp.each {|key, val| puts key + ' = ' + val}
    puts data
    puts JSON.parse(resp.body)["access_token"]

    result = {}

    result["code"] = resp.code
    result["token"] = JSON.parse(resp.body)["access_token"]

    print  result

    return result
end



def get_token1()
    path = '/rest/fastlogin/v1.0?app_key=' + app_key + '&username=%2B' + username + '&format=json'

    uri = URI.parse('https://' + server + path)
    http = Net::HTTP.new(uri.host, uri.port)
    http.use_ssl = true
    http.verify_mode = OpenSSL::SSL::VERIFY_NONE if http.use_ssl?

    req = Net::HTTP::Post.new(uri.path)
    req["Authorization"] = password

    puts uri.host
    puts uri.path
    puts uri.port
    resp,data = http.request(req)
    print resp 
end

No route matches [POST] - Rails destroy

I'm new to RoR and still don't have enough experience on solving the different errors that may appear to me. In this case I'm designing a blog where I can post articles. More specifically, my problem is related to deleting these articles.

As far as I know, writing:

resources :articles

in the routes file is an alternative for writing:

get "/articles"            #index
post "/articles"           #create
delete "/articles/:id"     #delete
get "/articles/:id"        #show
get "/articles/new"        #new
get "/articles/:id/edit"   #edit
patch "/articles/:id"      #update
put "/articles/:id"        #update

When I try to delete an article I get the following error:

No route matches [POST] "/articles/1"

The code I wrote was:

View

<% @articles.each do |art| %>
    <%= art.title %>
    <div>
        <%= art.body %> - <%= link_to "Delete", art, method: :delete %>
    </div>
<% end %>

Controller

def destroy
    @article = Article.find(params[:id])
    @article.destroy
    redirect_to articles_path       
end

I can't see what am I missing. Thanks in advanced.

Merit doesn't add points to user after create action

I've used this instructions for simply add score when a user creates a "solucion" (which is a kind of "answer" to a micropost). I have added the has_merit line to user.rb (user model).

I want to display the user points earned for that action at the show view. show.html.erb (for solucion):

<h2><span class="red"><%= current_user.points %></span><br>Points</br></h2>

It displays 0 points...

point_rules.rb:

module Merit
  class PointRules
   include Merit::PointRulesMethods

   def initialize
    score 5, on: 'solucions#create'
   end
  end
end

When I create a solucion with the current_user (already saving the user_id index and identifier to solucion), This is what my rails server output shows...

Direct link to github gist:

http://ift.tt/1DXPevP

Embed:

<script src="http://ift.tt/1SquLMf"></script>

Illformed requirement error when installing gems

I'm getting the following error whenever I try to install any gem (sass as an example)

ERROR:  While executing gem ... (Gem::Requirement::BadRequirementError)
    Illformed requirement ["sass"]

I'm running Windows 10 Pro (not activated yet) so I was wondering if this could be a reason as to why this is happening? I've tried using the 32 bit version of Ruby 2.2.2 as well and it gives the same error. How do I fix this and what could be the reason I get it? Any help is appreciated, thanks!

Kill process launched via thread

I have a headless application that uses sockets for communication. When launched, it remains active until sent a message telling it to quit (or it crashes, or is killed).

When unit testing this application using Ruby, I need to launch the process, interact with it (via sockets), and then kill it.

I thought I could do this using this pattern:

class TestServer < MiniTest::Unit::TestCase
  def setup
    @thread = Thread.new{ `#{MY_COMMAND}` }
  end

  def test_aaa
    # my test code
  end

  def teardown
    @thread.kill if @thread
  end
end

However, that teardown code kills the thread but does not kill the process launched by it.

How can I launch the process in a way that:

  1. Allows it to run in the background (immediately returns control to my Ruby test harness)
  2. Allows me to force kill the process later on, if need be.

I happen to be developing on OS X, but if possible I'd appreciate a generic solution that works across all OS where Ruby runs.

Connecting to background EventMachine application for unit testing

I am writing a headless Ruby application using EventMachine that communicates over sockets. I want to write some unit tests for this app. This means that my Ruby test script needs to launch that app in the background, perform socket communication with it, and then close that process.

This code fails. The socket connection is refused.

require 'socket'
PORT = 7331
CMD = File.expand_path("../../bin/rb3jay",__FILE__)
@thread = Thread.new{ `#{CMD} -D --port #{PORT}` }
@socket = TCPSocket.open('localhost', PORT)
#=> Errno::ECONNREFUSED: Connection refused - connect(2) for "localhost" port 7331

If I inject a 2 second delay before attempting the socket connection, it works as desired:

@thread = Thread.new{ `#{CMD} -D --port #{PORT}` }
sleep 2
@socket = TCPSocket.open('localhost', PORT)

This seems a gross hack. Maybe 2 seconds is long enough for my machine, but too short somewhere else. How should I correctly:

  • Launch my EventMachine application in the background
  • Create a socket connection to it as soon as it is ready
  • After my tests are done, ensure that the socket is closed and that I kill the background application

Recursive SQL using Rails 4 (modeling)

I read a tutorial, but I did not understand properly. I will quote it here and present the problem that seek to solve.

Tutorial

My problem: I'm doing a forum that can have various categories and subcategories. Then decide to use SQL Recursive PostgreSQL to facilitate me and not pollute my db with unnecessary tables. Suppose I have a table categories, and it has the categories_id field. Then the model would look something like this:

  attr_accessible :parent

  belongs_to :parent, :class_name => "Category"
  has_many :children, :class_name => "Category", :foreign_key => 'categories_id'

  scope :top_level, where(:categories_id => nil)

1- I did not understand fully if parent and children are a field in the table or not. 2- Why did he have to create a attr_accessible :parent? 3- Why the creation of scope?

Thanks,

Command "rails s" not working?

 C:\Users\Sprache\Sites\simple_cms>rails -v
Rails 4.2.3

C:\Users\Sprache\Sites\simple_cms>bundle list
Gems included by the bundle:
* actionmailer (4.2.3)
* actionpack (4.2.3)
* actionview (4.2.3)
* activejob (4.2.3)
* activemodel (4.2.3)
* activerecord (4.2.3)
* activesupport (4.2.3)
* arel (6.0.2)
* binding_of_caller (0.7.2)
* builder (3.2.2)
* bundler (1.10.6)
* byebug (5.0.0)
* coffee-rails (4.1.0)
* coffee-script (2.4.1)
* coffee-script-source (1.9.1.1)
* columnize (0.9.0)
* debug_inspector (0.0.2)
* erubis (2.7.0)
* execjs (2.5.2)
* globalid (0.3.5)
* i18n (0.7.0)
* jbuilder (2.3.1)
* jquery-rails (4.0.4)
* json (1.8.3)
* loofah (2.0.2)
* mail (2.6.3)
* mime-types (2.6.1)
* mini_portile (0.6.2)
* minitest (5.7.0)
* multi_json (1.11.2)
* mysql2 (0.3.19)
* nokogiri (1.6.6.2)
* rack (1.6.4)
* rack-test (0.6.3)
* rails (4.2.3)
* rails-deprecated_sanitizer (1.0.3)
* rails-dom-testing (1.0.6)
* rails-html-sanitizer (1.0.2)
* railties (4.2.3)
* rake (10.4.2)
* rdoc (4.2.0)
* sass (3.4.16)
* sass-rails (5.0.3)
* sdoc (0.4.1)
* sprockets (3.2.0)
* sprockets-rails (2.3.2)
* thor (0.19.1)
* thread_safe (0.3.5)
* tilt (1.4.1)
* turbolinks (2.5.3)
* tzinfo (1.2.2)
* tzinfo-data (1.2015.5)
* uglifier (2.7.1)
* web-console (2.2.1)

Hey all! Following this course here on lynda, and I'm having a wee issue.

So I've got my new project setup and I'm in the root folder.

I try to run

rails s

and

rails server

and

bundle exec rails server

and I keep getting the response


C:\Users\Sprache\Sites\simple_cms>rails s C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/nokogiri-1.6.6.2-x64-mingw32/lib/nokogiri .rb:29:in require': cannot load such file -- nokogiri/nokogiri (LoadError) from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/nokogiri-1.6.6.2-x64-mingw32 /lib/nokogiri.rb:29:inrescue in ' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/nokogiri-1.6.6.2-x64-mingw32 /lib/nokogiri.rb:25:in <top (required)>' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/loofah-2.0.2/lib/loofah.rb:3 :inrequire' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/loofah-2.0.2/lib/loofah.rb:3 :in <top (required)>' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/rails-html-sanitizer-1.0.2/l ib/rails-html-sanitizer.rb:2:inrequire' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/rails-html-sanitizer-1.0.2/l ib/rails-html-sanitizer.rb:2:in <top (required)>' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.3/lib/action_ view/helpers/sanitize_helper.rb:3:inrequire' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.3/lib/action_ view/helpers/sanitize_helper.rb:3:in <top (required)>' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.3/lib/action_ view/helpers/text_helper.rb:32:in' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.3/lib/action_ view/helpers/text_helper.rb:29:in <module:Helpers>' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.3/lib/action_ view/helpers/text_helper.rb:6:in' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.3/lib/action_ view/helpers/text_helper.rb:4:in <top (required)>' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.3/lib/action_ view/helpers/form_tag_helper.rb:18:in' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.3/lib/action_ view/helpers/form_tag_helper.rb:14:in <module:Helpers>' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.3/lib/action_ view/helpers/form_tag_helper.rb:8:in' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.3/lib/action_ view/helpers/form_tag_helper.rb:6:in <top (required)>' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.3/lib/action_ view/helpers/form_helper.rb:4:inrequire' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.3/lib/action_ view/helpers/form_helper.rb:4:in <top (required)>' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.3/lib/action_ view/helpers.rb:50:in' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.3/lib/action_ view/helpers.rb:4:in <module:ActionView>' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.3/lib/action_ view/helpers.rb:3:in' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.3.2/lib/sp rockets/rails/legacy_asset_tag_helper.rb:7:in <module:LegacyAssetTagHelper>' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.3.2/lib/sp rockets/rails/legacy_asset_tag_helper.rb:6:in' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.3.2/lib/sp rockets/rails/legacy_asset_tag_helper.rb:4:in <module:Sprockets>' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.3.2/lib/sp rockets/rails/legacy_asset_tag_helper.rb:3:in' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.3.2/lib/sp rockets/rails/helper.rb:45:in require' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.3.2/lib/sp rockets/rails/helper.rb:45:in' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.3.2/lib/sp rockets/rails/helper.rb:7:in <module:Rails>' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.3.2/lib/sp rockets/rails/helper.rb:6:in' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.3.2/lib/sp rockets/rails/helper.rb:5:in <top (required)>' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.3.2/lib/sp rockets/railtie.rb:6:inrequire' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.3.2/lib/sp rockets/railtie.rb:6:in <top (required)>' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sass-rails-5.0.3/lib/sass/ra ils/railtie.rb:3:inrequire' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sass-rails-5.0.3/lib/sass/ra ils/railtie.rb:3:in <top (required)>' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sass-rails-5.0.3/lib/sass/ra ils.rb:11:inrequire' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sass-rails-5.0.3/lib/sass/ra ils.rb:11:in <top (required)>' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sass-rails-5.0.3/lib/sass-ra ils.rb:1:inrequire' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sass-rails-5.0.3/lib/sass-ra ils.rb:1:in <top (required)>' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.10.6/lib/bundler/r untime.rb:76:inrequire' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.10.6/lib/bundler/r untime.rb:76:in block (2 levels) in require' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.10.6/lib/bundler/r untime.rb:72:ineach' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.10.6/lib/bundler/r untime.rb:72:in block in require' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.10.6/lib/bundler/r untime.rb:61:ineach' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.10.6/lib/bundler/r untime.rb:61:in require' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.10.6/lib/bundler.r b:134:inrequire' from C:/Users/Sprache/Sites/simple_cms/config/application.rb:7:in <top (required)>' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/railties-4.2.3/lib/rails/com mands/commands_tasks.rb:78:inrequire' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/railties-4.2.3/lib/rails/com mands/commands_tasks.rb:78:in block in server' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/railties-4.2.3/lib/rails/com mands/commands_tasks.rb:75:intap' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/railties-4.2.3/lib/rails/com mands/commands_tasks.rb:75:in server' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/railties-4.2.3/lib/rails/com mands/commands_tasks.rb:39:inrun_command!' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/railties-4.2.3/lib/rails/com mands.rb:17:in <top (required)>' from bin/rails:4:inrequire' from bin/rails:4:in `'


What do these things mean and what do I do?

Grazie a tutti!