vendredi 8 mai 2015

Recordset that returns an item at a given index?

Okay, so I currently have a school project which is based on making a website. On my main page I have a "last news" section. I want the news in this section to update whenever a new item is added to my database. The news section contains three divs where I want my three newest database items to be added. Normally I would do this by writing the following SQL code:

SELECT carName

FROM cars

ORDER BY carName DESC

LIMIT 3

However the three divs where I want the newest items to go, are separated. And by using this method they wouldn't be separated. I do not have a lot of knowledge on neither PHP or SQL. Our curriculum is based 100% around using dreamweaver to manage our site (I do however know how to use HTML and CSS).

My question is: Is there a way to make three different recordset which only returns the item at f.ex. the second index? If this was possible I could simply place the return values in the three divs.

What I use to make my site: Dreamweaver WAMP (PHPMyAdmin).

Subscribe to mqtt mosquito from PHP

I never used mqtt and I need to subscribe to a mqtt server and save the data from the messages i get, to a MySQL database on a server hosted in hostgator using PHP, javascript or something that runs always on the server (even if i dont load the php or html code on a browser)

i found some libs and wrappers, but don't know how to use them.

http://ift.tt/1k6VVHM

http://ift.tt/1jVJQQ7

How do i install mosquitto-PHP in a hostgator server?

The php with the subscribe code have to be open to be able to listen the publish messages?

Thanks

(Ms-Access-2013) db.OpenRecordset returns nothing; but run as queries they do

I'm trying to generate a bill by route, so I've broken it down by customers belonging to a specific route, and then for each customer totaling their weekly rates to compile a monthly rate.

The problem is, even opening a recordset with a "SELECT * IN [table]" returns nothing, so there must be some glaring error. Here's my code, I'd be very appreciative if someone could set me straight.

Dim rs As DAO.Recordset
Dim rs2 As DAO.Recordset
Dim rs3 As DAO.Recordset
Dim custNo As Integer
Dim month_total_v As Integer
Dim weekTotal As Integer
Dim weekStart As Date
Dim sql As String

'sql = "SELECT cust_no FROM Roster WHERE route = Forms![routeBill]![route]"

Set rs = CurrentDb.OpenRecordset("SELECT CUST_NO FROM Roster WHERE ROUTE = 'Forms![routeBill]![route]'")

month_total_v = 0

MsgBox ("Boop.")

If Not (rs.EOF) Then
    rs.MoveFirst
    Do Until rs.EOF = True
    MsgBox ("Boop.")
        custNo = rs!CUST_NO
        Set rs2 = CurrentDb.OpenRecordset("SELECT wk_rate, wk_strt_dt FROM Roster WHERE wk_strt_dt >= Forms![routeBill]![Text53] AND wk_strt_dt <= Forms![routeBill]![Text4] AND cust_no = custNo")
        If Not (rs2.EOF And rs2.BOF) Then
            rs2.MoveFirst
            Do Until rs2.EOF = True
                MsgBox "Boop."
                weekStart = WK_STRT_DT
                month_total_v = month_total_v + rs2!WK_RATE
                Set rs3 = CurrentDb.OpenRecordset("SELECT * FROM monthTotal where cust_no = custNo and billMonth=month(weekStart) and billYear=year(weekStart)") 'specify date ranges to pick from to shorten query
                If rs3.EOF Then
                    sql = "INSERT INTO monthTotal (cust_no, month_total, billMonth, billYear) VALUES (custNo, month_total_v, month(weekStart), year(weekStart))" 'Append, record does not exist
                    DoCmd.RunSQL sql
                Else
                    sql = "UPDATE monthTotal SET month_total = month_total_v WHERE cust_no = custNo AND billMonth = month(weekStart) AND billYear = year(weekStart)" 'Update, record exists
                    DoCmd.RunSQL sql
                End If
                rs2.MoveNext
            Loop
        Else
            'pass
        End If
    rs.MoveNext
    Loop
End If

if statement in SQL to calculate age

I am very new at SQL and I have been working on my First Query. Now I need your help. I have this report in Excel. I have formula in the AGE column N calculating the AGE. I have been trying to create a SQL query to come up with the same answer. So far I have figured out the columns that I need and pulled all the data to Match Excel. Only thing is I don't know how and where to enter this IF statement so it will calculate the age when i run the query.

Work Order  Location    MISC    Status  Actual Finish   Finish Time Parent WO   Work Type   N   Reported Date   Reported Time   Site    Gen Age Sub Name    Substation Location                         
1234567899  4074        COMP    11/5/14 3:08:49 PM      CM      10/7/14 1:47:42 PM          29.05633102                                 
12348574987 2946        SCHED               CM      10/30/14    10:28:03 AM         188.5638542     

AGE is a formula, pasted below:

=IF ((IF(Status<>"Comp",Today()-Reported date, actual finish-reported date))<0,0, IF(STATUS<>"COMP", TODAY()-REPORTED DATE, ACTUAL FINISH-REPORTED DATE))       

SQL Writen Query

SELECT WO.WONUM,                                                                                        
  LOCOFFDESC.DESCRIPTION AS OFFICE,                                                                                     
  WO.STATUS,                                                                                        
  WO.LOCATION,                                                                                      
  CASE                                                                                      
    WHEN ((INSTR(LOCOFF.EXT_LOC_HIERARCHY_PATH, '/', 2, 3)) = 0)                                                                                        
    THEN SUBSTR(LOCOFF.EXT_LOC_HIERARCHY_PATH, ((INSTR(LOCOFF.EXT_LOC_HIERARCHY_PATH, '/', 1, 2) + 2)), LENGTH(LOCOFF.EXT_LOC_HIERARCHY_PATH))                                                                                      
    WHEN ((INSTR(LOCOFF.EXT_LOC_HIERARCHY_PATH, '/', 2, 3)) IS NOT NULL)                                                                                        
    THEN SUBSTR(LOCOFF.EXT_LOC_HIERARCHY_PATH, ((INSTR(LOCOFF.EXT_LOC_HIERARCHY_PATH, '/', 1, 2) + 2)), (INSTR(LOCOFF.EXT_LOC_HIERARCHY_PATH, '/', 2, 3)) - (INSTR(LOCOFF.EXT_LOC_HIERARCHY_PATH, '/', 1, 2) + 2))                                                                                      
  END AS "SUBSTATION CASE",                                                                                     
  WO.PARENT,                                                                                        
  WO.WORKTYPE,                                                                                      
  WO.REPORTEDBY,                                                                                        
  WO.REPORTDATE,                                                                                        
  WO.ACTFINISH,                                                                                     
  WO.SITEID                                                                                     
FROM LOCATIONS LOCOFF                                                                                       
RIGHT JOIN MAXPRD.WORKORDER WO                                                                                      
ON WO.LOCATION = LOCOFF.LOCATION                                                                                        
INNER JOIN MAXPRD.LOCANCESTOR LOCOFFANC                                                                                     
ON LOCOFFANC.LOCATION = LOCOFF.LOCATION                                                                                     
INNER JOIN MAXPRD.LOCATIONS LOCOFFDESC                                                                                      
ON LOCOFFANC.ANCESTOR = LOCOFFDESC.LOCATION                                                                                     
INNER JOIN MAXPRD.LOCHIERARCHY LOCOFFHIER                                                                                       
ON LOCOFFANC.ANCESTOR = LOCOFFHIER.LOCATION                                                                                     
WHERE LOCOFF.SITEID   = 'SUB'                                                                                       
AND LOCOFFHIER.PARENT = '2000'                                                                                      
GROUP BY WO.WONUM,                                                                                      
  LOCOFFDESC.DESCRIPTION,                                                                                       
  WO.STATUS,                                                                                        
  WO.LOCATION,                                                                                      
  LOCOFF.EXT_LOC_HIERARCHY_PATH,                                                                                        
  LOCOFF.SITEID,                                                                                        
  LOCOFFHIER.PARENT,                                                                                        
  WO.PARENT,                                                                                        
  WO.WORKTYPE,                                                                                      
  WO.REPORTEDBY,                                                                                        
  WO.REPORTDATE,                                                                                        
  WO.ACTFINISH,                                                                                     
  WO.SITEID 

MySQL SELECT email where field contains a value

I would like to do a simple select - but the condition is a bit tricky for me (because I'm a SQL-beginner).

I got this table:

userid | email             | newsletters
     1 | test@example.com  | 1,2
     2 | test2@example.com | 1

Now I would like to get all email-addresses of users, which want to get newsletter "2".

This would be:

email | newsletters
test@example.com | 1,2

And of course: In another query all users, which are subscribing newsletter number 1:

Result:

email | newsletters
test@example.com | 1,2
test2@example.com | 1

What would be the correct sql-query? I think this should be the right beginning, but I don't know which condition I have to use:

SELECT email FROM users WHERE newsletter CONDITION?

Could you please help me out? :-)

PHP Query issue in setting values?

Quick question. I've got a SQL query which works with my database. However, I am to sure how to set parameters in my PHP file so that it works with my query?

Any Ideas? I'm having trouble with the Set parameters in terms of php and making my query work.

<?php

/*
 * Following code will list all the products
 */

// array for JSON response
$response = array();

// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

set $orig_lat=51.42; 
set $orig_long=-0.550; 
set $bounding_distance=1;

// get all products from products table
$result = mysql_query(" SELECT * ,((ACOS(SIN($orig_lat * PI() / 180) * SIN(`latitude` * PI() /
180) + COS($orig_lat * PI() / 180) * COS(`latitude` * PI() / 180) *
COS(($orig_long - `longitude`) * PI() / 180)) * 180 / PI()) * 60 *
1.1515) AS `distance` FROM `Location` WHERE ( `latitude` BETWEEN
($orig_lat - $bounding_distance) AND ($orig_lat + $bounding_distance)
AND `longitude` BETWEEN ($orig_long - $bounding_distance) AND
($orig_long + $bounding_distance) ) ORDER BY `distance` ASC limit 1") or die(mysql_error()); 

// check for empty result
if (mysql_num_rows($result) > 0) {
    // looping through all results
    // products node
    $response["Location"] = array();

    while ($row = mysql_fetch_array($result)) {
        // temp user array
       $Location = array();
       $Location["id"] = $row["id"];
       $Location["latitude"] = $row["latitude"];
       $Location["longitude"] = $row["longitude"];



        // push single product into final response array
        array_push($response["Location"], $Location);
    }
    // success
    $response["success"] = 1;

    // echoing JSON response
    echo json_encode($response);
} else {
    // no products found
    $response["success"] = 0;
    $response["message"] = "No Profiles found";

    // echo no users JSON
    echo json_encode($response);
}
?>

MySQL + PHP - Results different on different computers? Cache?

We have been running a local application for a bit over a year now and this problem has never come up.

We have a section of our application where a user will add a note to an account. Very simple table structure includes an account_id, user_id (who added the note) and a date.

The notes are still being added into the database just fine; however, when viewing the page, it is hit or miss on whether or not the note will actually display using PHP to query the database.

The only way I can get these notes to show up is by clearing the computer cache (again, doesn't always work) or clearing MySQL cache (which doesn't always work, either)

The application is being accessed from outside of our local network, as well, and this issue does not seem to happen from anybody using this method.

I think it is a cache issue, but I am honestly not familiar with this and have not run into this issue with anything before. Server is latest version of CentOS and we are running very simply MySQL queries via PHP.

Thanks, in advance, for any assistance you can provide.

Debugging MySQL connection issues from C# application

I seem to be missing something obvious, and it's been bothering me for last few days.

I use a C# application on Windows Server 2012 to connect to MySQL database to generate a report end of the day. I use Task Scheduler to run this application.

While it seems to be running smoothly when I run manually - When the I run the application at a set time (11pm) - it throws MySQL connection error, i.e. Unable to connect to localhost (I email myself the error).

This has happened a few times, and I am unable to recreate the issue.

How can I troubleshoot/debug this -? I've looked into Windows Events and can't find anything. Where would MySQL connection issues be logged?

Thanks in Advance.

Define two tables in c# with foreign key

I want to make 2 tables : Teams and Projects I want to make a 1 : n relationship between these two. This is my code: //Creare tabela Projects

    public void CreareTabelaProjects() {
        string query = "CREATE TABLE IF NOT EXISTS Projects" + "(" + "id_project MEDIUMINT PRIMARY KEY AUTO_INCREMENT," + "name VARCHAR(30)," +
            "description VARCHAR(30)," + "FOREIGN KEY (team_id) REFERENCES Teams(team_id)" + ");";
        if (this.OpenConnection() == true) {
            MySqlCommand cmd = new MySqlCommand(query, connection);
            cmd.ExecuteNonQuery();
            this.CloseConnection();
        }
    }

   //Creare tabela Teams

    public void CreareTabelaTeams() {
        string query = "CREATE TABLE IF NOT EXISTS Teams" + "(" + "team_id INT AUTO_INCREMENT PRIMARY KEY," + "name VARCHAR(30)" + ");";
        if (this.OpenConnection() == true)
        {
            MySqlCommand cmd = new MySqlCommand(query, connection);
            cmd.ExecuteNonQuery();
            this.CloseConnection();
        }

    }

When i run this, an error occured saying this : Key column 'team_id' doesn't exist in table. The application creates only the Team table. Any help please? Thanks!

When passing an array to Twig, words with special characters are disappearing [duplicate]

This question already has an answer here:

I can query data from the database use mysqli, output to Twig and create a table, and words with characters with accents(À, Í, etc) are not displayed.

The array can be displayed through a var_dump perfectly. So somewhere in Twig is it going awry.

I have:

  • A database with data in Spanish
  • PHP
  • Silex/Twig
  • A table schema in utf8, with text being displayed correctly.

I have tried:

  • mb_convert_encoding before sending it to Twig
  • convert_encoding('iso-8859', 'UTF-8') in Twig

I am at a loss as to what to do next, nor why it is not working.

Template Example:

{% if results %}
<div class="table-container" id="table-container">
    <table class="results-table" id="results-table">
        <thead>
        <tr>
            <th>{{ "First Name"|trans }}</th>
            <th>{{ "Second Name"|trans }}</T></th>
            <th>{{ "First Surname"|trans }}</th>
            <th>{{ "Second Surname"|trans }}</th>
            <th>{{ "Number"|trans }}</th>
            <th>{{ "Type"|trans }}</th>
            <th>{{ "District"|trans }}</th>
            <th>{{ "State"|trans }}</th>
            <th>{{ "City"|trans }}</th>
        </tr>
        </thead>

        <tbody class="results">
        {% for r in results %}
        <tr>
            <td>{{ r.first_name }}</td>
            <td>{{ r.middle_inital }}</td>
            <td>{{ r.surname }}</td>
            <td>{{ r.second_surname}}</td>
            <td>{{ r.number }}</td>
            <td>{{ r.type }}</td>
            <td>{{ r.district }}</td>
            <td>{{ r.state }}</td>
            <td>{{ r.city|capitalize }}</td>
        </tr>
        {% endfor %}
        </tbody>
    </table>
</div>
{% endif %}

Array is passed from a mysqli query to a variable. Text book example.

Write to Joomla database

I have a cool component for joomla that help me register users by creating a url (see the link). joomla extention

What i would like to do is to be able to write on a different table using the same method: This is the code that help with user registration:

//http://ift.tt/1Qt87yo
public function registration()
{
    $name = JRequest::getVar('name');
    $username = JRequest::getVar('username');
    $passwd = JRequest::getString('pass');
    $email = JRequest::getVar('email');


    $data = array(
          "name"=>$name,
          "username"=>$username,
          "password"=>$passwd,
          "password2"=>$passwd,
          "email"=>$email,
          "block"=>1,
          "groups"=>array("2"),
          "sendEmail"=>("1"),
        );

    $user = new JUser;
    //Write to database
    if(!$user->bind($data)) {
        $status = "Could not bind data. Error: " . $user->getError();
    }
    if (!$user->save()) {
      $status = "Could not save user. Error: " . $user->getError();
    }
    else {
      $status = "Success";
    }

    $message = array(
        'message' => $status
        );

    header('Content-Type: application/json');
    echo json_encode ($message);
    jexit();
}

To be more explicit, i would like to be able to write comments in a table called belvw_zoo_comment Is there a way to do that by just modifying the above code? i m thinking of something like this:

     //http://ift.tt/1zRgYWI
   public function comment()
  {
  $author = JRequest::getVar('author');
  $email = JRequest::getVar('email');
  $content = JRequest::getVar('content');


  $data = array(
       "author"=>$author,
       "email"=>$email,
       "content"=>$content,

        );

   $comment = new comment;
   //Write to database
   if(!$comment->bind($data)) {
       $status = "Could not bind data. Error: " . $user->getError();
    }
    if (!$comment->save()) {
      $status = "Could not save user. Error: " . $user->getError();
    }
    else {
     $status = "Success";
    }

    $message = array(
       'message' => $status
       );

    header('Content-Type: application/json');
    echo json_encode ($message);
    jexit();
}

Of course the above code is not working.

Sum query in codeigniter

I need to do sum query and after I must compare this sum with a threshold. This is my code:

$this->db->select("id,SUM(sumColum)");
    $this->db->from('p');
    $this->db->group_by('id');
    $query=$this->db->get();

Now I can compare the sum with a threshold value? Anyone can help me?

Connect to database after creating the PDO object [duplicate]

This question already has an answer here:

If I connect to a mysql database using the following code:

$dbh = new PDO("mysql:host=$host", $root, $root_password);

As you can see the code doesn't provide the database name so I can create one, but can I make a connection to the created database later in the code?

MySQL Merge non empty values from a table to one result row

I have a MYSQL table which has about 350 columns. There are most 'empty' values and I need to merge several rows in one and replace 'empty' values by a non empty value. My table looks like this:

id|col1|col2|col3|cola|col_b|...|col350
1 |12  |4   |3   |-77 |-77  |...|-77 
2 |12  |-77 |-77 |2   |-77  |...|-77 
3 |12  |-77 |-77 |-77 |6    |...|-77 
4 |12  |-77 |-77 |-77 |-77  |...|6
5 |13  |3   |-77 |-77 |-77  |...|-77 
6 |13  |-77 |5   |-77 |-77  |...|-77
...

-77 is a replacement for empty values. In col1 is an id of datasets witch belongs together.

I need a select query to merge non 'empty' values to one result row per col1-id. For col1-id 12 it should looks like this:

1 | 12 | 4 | 3 | 2 | 6 | ... | 6

Does someone have an idea how to do this?

Why is my update query failing

I cannot for the life of me figure out why this code will not update the database table 'products'. I've already had one person look at it for me in house but she doesn't have a clue. Any help would be greatly appreciated.

edit_products.php

<?php
  $product = find_product_by_id($_GET["id"]);

  if (!$product) {
    // admin ID was missing or invalid or 
    // admin couldn't be found in database
    safe_redirect("manage_products.php");
  }

?>
<?php
if (isset($_POST['submit'])) {
  // Process the form

    $id = $product["id"];
    $product_id = mysql_prep($_POST["product_id"]);
    $product_name = mysql_prep($_POST["product_name"]);
    $product_image = mysql_prep($_POST["product_image"]);
    $highres_image = mysql_prep($_POST["highres_image"]);
    $linedraw_image = mysql_prep($_POST["linedraw_image"]);
    $product_video = mysql_prep($_POST["product_video"]);
    $product_pdf = mysql_prep($_POST["product_pdf"]);
    $product_keywords = mysql_prep($_POST["product_keywords"]);
    $product_description = mysql_prep($_POST["product_description"]);
    $product_enabled = mysql_prep($_POST["product_enabled"]);
    $product_weight = mysql_prep($_POST["product_weight"]);
    $product_length = mysql_prep($_POST["product_length"]);
    $product_width = mysql_prep($_POST["product_width"]);
    $product_height = mysql_prep($_POST["product_height"]);
    $product_url = mysql_prep($_POST["product_url"]);

// validations
    $required_fields = array("product_id", "product_name", "product_image", "product_description");
    validate_presences($required_fields);

    $fields_with_max_lengths = array("product_id" => 20);
    validate_max_lengths($fields_with_max_lengths);

    if (empty($errors)) {

    // Perform Update

    $query  = "UPDATE products SET ";
    $query .= "product_id = '{$product_id}', ";
    $query .= "product_name = '{$product_name}', ";
    $query .= "product_image = '{$product_image}', ";
    $query .= "highres_image = '{$highres_image}', ";
    $query .= "linedraw_image = '{$linedraw_image}', ";
    $query .= "product_video = '{$product_video}', ";
    $query .= "product_pdf = '{$product_pdf}', ";
    $query .= "product_keywords = '{$product_keywords}', ";
    $query .= "product_description = '{$product_description}', ";
    $query .= "product_enabled = '{$product_enabled}', ";
    $query .= "product_weight = '{$product_weight}', ";
    $query .= "product_length = '{$product_length}', ";
    $query .= "product_width = '{$product_width}', ";
    $query .= "product_height = '{$product_height}', ";
    $query .= "product_url = '{$product_url}', ";
    $query .= "WHERE id = {$id} ";
    $query .= "LIMIT 1";
    $result = mysqli_query($connection, $query);

    if ($result && mysqli_affected_rows($connection) == 1) {
      // Success
      $_SESSION["message"] = "Product updated.";
      safe_redirect("manage_products.php");
    } else {
      // Failure
      $_SESSION["message"] = "Product update failed.";
    }

  } 
  // This is probably a GET request

} // end: if (isset($_POST['submit']))

?>
<?php $layout_context = "admin"; ?>
<?php include("includes/layouts/header.php"); ?>
  <?php echo message(); ?> <?php echo form_errors($errors); ?>
  <h2>Edit Product: <?php echo htmlentities($product["product_id"]); ?></h2>
  <form action="edit_product.php?id=<?php echo urlencode($product["id"]); ?>" method="post">
    <p>Product ID:
      <input name="product_id" type="text" value="<?php echo htmlentities($product["product_id"]); ?>" size="15" />
    </p>
    <p>Product Name:
      <input name="product_name" type="text" value="<?php echo htmlentities($product["product_name"]); ?>" size="45" />
    </p>
    <p>Product Image:
      <input name="product_image" type="text" value="<?php echo htmlentities($product["product_image"]); ?>" size="45" />
    </p>
    <p>High Res Image:
        <input name="highres_image" type="text" value="<?php echo htmlentities($product["highres_image"]); ?>" size="45" />
    </p>
    <p>Line Drawing:
        <input name="linedraw_image" type="text" value="<?php echo htmlentities($product["linedraw_image"]); ?>" size="45" />
    </p>
    <p>Product Video:
        <input name="product_video" type="text" value="<?php echo htmlentities($product["product_video"]); ?>" size="45" />
    </p>
    <p>Product PDF:
        <input name="product_pdf" type="text" value="<?php echo htmlentities($product["product_pdf"]); ?>" size="45" />
    </p>
    <p>Product Keywords:
        <input name="product_keywords" type="text" value="<?php echo htmlentities($product["product_keywords"]); ?>" size="45" />
    </p>
    <p>Product Description:
        <input name="product_description" type="text" value="<?php echo htmlentities($product["product_description"]); ?>" size="45" />
    </p>
    <p>Product Enabled:
        <input name="product_enabled" type="text" value="<?php echo htmlentities($product["product_enabled"]); ?>" size="5" />
    </p>
    <p>Product Weight:<input name="product_weight" type="text" value="<?php echo htmlentities($product["product_weight"]); ?>" size="5" /> &nbsp; Length: <input name="product_length" type="text" value="<?php echo htmlentities($product["product_length"]); ?>" size="5" /> &nbsp; Width: <input name="product_width" type="text" value="<?php echo htmlentities($product["product_width"]); ?>" size="5" /> &nbsp; Height: <input name="product_height" type="text" value="<?php echo htmlentities($product["product_height"]); ?>" size="5" />
    </p>
    <p>Product URL:
        <input name="product_url" type="text" value="<?php echo htmlentities($product["product_url"]); ?>" size="45" />
    </p>
    <input type="submit" name="submit" value="Edit Product" />
  </form>

This is the function find_product_by_id

function find_product_by_id($product_id) {
    global $connection;

    $safe_product_id = mysqli_real_escape_string($connection, $product_id);

    $query = "SELECT * ";
    $query .= "FROM products ";
    $query .= "WHERE id = {$safe_product_id} ";
    $query .= "LIMIT 1";
    $product_set = mysqli_query($connection, $query);
    confirm_query($product_set);
    if($product = mysqli_fetch_assoc($product_set)) {
        return $product;
    } else {
        return null;
    }
}

Images at Lightswitch v3.0: "Invalid URI: The Uri string is too long."

I got a simple Lightswitch - Silverlight based - web client. Client.csproj and Server.csproj are saying the LightSwitchVersion is v3.0. It runs on

  • Visual Studio 2012 Update 4
  • LightSwitch Extensibility Toolkit for VS11
  • I have 2 extension, both are selected:

    • LightSwitch Cosmopolitan Shell and Theme
    • Microsoft LightSwitch Extensions

And I got a MySQL table

CREATE TABLE `images` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `legend` varchar(200) NOT NULL,
  `preview` blob,
  `createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

And I declared the preview field as an Image Type in the data source before I created a screen for the table. But the running application greets me with this

Lightswitch 3.0 has a problem with images

Using Lightswitch 2.0 everything runs fine. But since I've upgraded to v3.0 this is the only issue spoiling everything :-(

jTable not showing new row content after MySQL INSERT with node.js

I have a little jTable that shows a list of records pulled from my local database using node.js with express-generator and mysql. I can show, create, edit and delete records in/from my database just fine.

My problem is that when I add a new record using my jTable, it creates an empty row in my jTable and doesn't populate it with the newly added data unless I refresh the page. This is weird because it successfully updates the row in the jTable when I edit and delete it using the jTable as well.

Can anyone see why this is happening?
(I excluded the edit and delete code since those work properly)

tbl_bar structure

rowID = INT, PK, AI
rowName = VARCHAR, UQ
rowOrder = INT (for future row organization)

index.js

var express = require('express');
var router = express.Router();

var mysql = require('mysql');
var connection = mysql.createConnection({
    host:     'localhost',
    user:     'root',
    password: 'password'
});

// Select which database to use
connection.query('USE db_foo;');

/*********************/
/***** SHOW ROWS *****/
/*********************/
// Retrieves all rows and sends them to the jTable for display
router.showRows = function (request, response) {
    // Query table and return the ordered result/s
    connection.query('SELECT * FROM tbl_bar ORDER BY rowOrder;', function (error, result) {
        if (error) response.send({ Result: "ERROR", Message: "Error getting rows" });
        else response.send({ Result: "OK", Records: result });
    });
}

/**********************/
/***** CREATE ROW *****/
/**********************/
// Adds a new row to the database
router.createRow = function (request, response) {
    var query = JSON.parse(JSON.stringify(request.body));

    // Get the highest rowCount to determine order of newly added row
    connection.query('SELECT rowOrder FROM tbl_bar ORDER BY rowOrder DESC LIMIT 1;', function (error, result) {
        if (error) response.send({ Result: "ERROR", Message: "Error getting rows" });
        else {
            var data = {
                rowName: query.rowName
            };
            // Increase highest order by 1 then add it to data JSON object, or use 0 if there are no rows
            data['rowOrder'] = (result[0].rowOrder === null) ? 0 : result[0].rowOrder + 1;
            // Query table and return the ordered result/s
            connection.query('INSERT INTO tbl_bar SET ?', data, function (error, result) {
                if (error) response.send({ Result: "ERROR", Message: "Error adding row" });
                else response.send({ Result: "OK", Record: result });
            });
        }
    });
}

/*************************/
/***** GET HOME PAGE *****/
/*************************/
router.get('/', function (request, response, next) {
    response.render('index', { title: 'My jTable' });
});

// Event listeners
router.post('/showRows', router.showRows);
router.post('/createRow', router.createRow);

module.exports = router;

table.js

function populateTable() {
    $('#container').jtable({
        title: 'My jTable',
        paging: false,
        messages: {
            addNewRecord: 'Add a New Row'
        },
        deleteConfirmation: function(data) {
            data.deleteConfirmMessage = 'Delete Row: ' + data.record.rowName + '?';
        },
        actions: {
            listAction:   '/showRows',
            createAction: '/createRow'
        },
        fields: {
            rowID: {
                title:  'ID',
                key:    true,
                list:   false,
                create: false,
                edit:   false,
                delete: false
            },
            rowName: {
                title:  'Name',
                key:    false,
                list:   true,
                create: true,
                edit:   true,
                delete: true
            },
            rowOrder: {
                title:  'Order',
                key:    false,
                list:   false,
                create: false,
                edit:   true,
                delete: true
            }
        }
    });
}

$(document).ready(function () {    
    populateTable();
    $('#container').jtable('load');
});

index.jade

doctype html
html
  head
    meta(charset='utf-8')
    |     
    title My jTable
    |     
    link(rel='stylesheet', type='text/css', href='javascripts/jquery-ui-1.11.4/jquery-ui.min.css')
    |     
    link(rel='stylesheet', type='text/css', href='javascripts/jtable.2.4.0/themes/metro/blue/jtable.min.css')
    |     
    script(type='text/javascript', src='javascripts/jquery-1.11.2.min.js')
    |     
    script(type='text/javascript', src='javascripts/jquery-ui-1.11.4/jquery-ui.min.js')
    |     
    script(type='text/javascript', src='javascripts/jtable.2.4.0/jquery.jtable.min.js')
    |     
    script(type='text/javascript', src='javascripts/table.js')
  |   
  body
    #container

I receive an error when Magento stock is synced from outside source

My Magento store receives stock status from a scrapper source but when sync process is executed it stops before finishing the syncing, and I receive following php error in log.

[06-May-2015 18:00:58] PHP Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000]: General error: 1205 Lock wait timeout exceeded; try restarting transaction' in /home1/darrosme/public_html/store/lib/Zend/Db/Statement/Pdo.php:228 Stack trace:

0 /home1/darrosme/public_html/store/lib/Zend/Db/Statement/Pdo.php(228): PDOStatement->execute(Array)

1 /home1/darrosme/public_html/store/lib/Varien/Db/Statement/Pdo/Mysql.php(110): Zend_Db_Statement_Pdo->_execute(Array)

2 /home1/darrosme/public_html/store/app/code/core/Zend/Db/Statement.php(291): Varien_Db_Statement_Pdo_Mysql->_execute(Array)

3 /home1/darrosme/public_html/store/lib/Zend/Db/Adapter/Abstract.php(480): Zend_Db_Statement->execute(Array)

4 /home1/darrosme/public_html/store/lib/Zend/Db/Adapter/Pdo/Abstract.php(238): Zend_Db_Adapter_Abstract->query('UPDATE `catalog...', Array)

5 /home1/darrosme/public_html/store/lib/Varien/Db/Adapter/Pdo/Mysql.php(428): Zend_Db_Adapter_Pdo_Abstract->query('UPDATE `catalog...', Array)

6 /home1/darrosme/public_html/store/lib/Zend/Db/Adapter in /home1/darrosme/public_html/store/lib/Zend/Db/Statement/Pdo.php on line 234

Django-Filter query by type

I want to show one notification of each notification type and the most recent. My question is how to get each notification type and show the most recent of that notification type.

notifications = Notification.objects.filter(**condition). \
    exclude(notification_user__in=users). \
    order_by('notificationType__priority','-start_date')[:1]

models.py

class Notification(models.Model):
title = models.CharField(max_length=75)
description = models.TextField()
start_date = models.DateTimeField()
end_date = models.DateTimeField()
application = models.ManyToManyField('Products.Application')
notificationType = models.ForeignKey(NotificationType)
url = models.URLField(null=True, blank=True)
region = models.ManyToManyField('Geolocations.Region', null=True, blank=True)
image = models.ImageField(null=True, blank=True)
user = models.ManyToManyField(User, through='Notification_User')

class NotificationType(models.Model):
type = models.CharField(max_length=30)
priority = models.IntegerField(max_length=3)
color = RGBColorField()

This only shows the most recent notification independent of the notification type. Any suggestion?

UPDATE

now i inserted the notifications into a list. but in this ways doesnt work my idea is if the notification_type the priority value (unique int) does not exist, to add into the list

notifications=[]    
if n.objects.filter(notification_type__priority=notifications).exists():
    notifications.append(n)

Using name attribute for Propel joins

I lately started to use Propel (PHP ORM) and I love it but I have one quite annoying issue I can't resolve even with a lot of trying. I use reverse engineering to create my schema.xml, which works great until it comes to joins. Sadly for all my foreign keys the reverse engineering only adds the name and not the phpName attribute. Whatever I try to use this name attribute for a join I fail. After I added the phpName attribute manually (and then rebuilding the models of course) the join works fine as it should.

Here is the snippet of the foreign key in the schema.xml (without the phpName attribute obviously):

<foreign-key foreignTable="users" name="messages_ibfk_1">
  <reference local="creating_user_id" foreign="id"/>
</foreign-key>

And here is the code for my join (which doesn't work):

$messages = MessagesQuery::create()->joinWith('messages_ibfk_1')->findByRecipientId($id);

I tried all kinds of variations for the joinWith value but none worked. On top of the schema this setting is active: defaultPhpNamingMethod="underscore"

The error propel pulls out is: Unknown relation messages_ibfk_1 on the Messages table.

If I add the phpName attribut with the value Author the join works fine like that:

$messages = MessagesQuery::create()->joinWith('Author')->findByRecipientId($id);

As I have a lot of foreign keys and I want minimum/none manual work the question is: How do I resolve this without adding all the phpName attributes manually. Either I find a way to access the foreign keys with their regular name attribute or there is a way to tell propel to set up the phpName attribute while building the models?

I hope someone has an idea, would be a great help! :)

Best way of using GeoIP databases

Can anyone please let me know what's the best way of using the GeoIP databases in order to detect the country of visitors by IP.

I used to have a table populated with IPv4 information ( longstart, longend, country code ) and with an INET_ATON() instruction I would get the relevant country code.

However, we would now want to use the IPv6 database and grab country code for IPv6 IPs as well. But not sure what's the best way to use these databases. I can see they offer various databases now(geolite legacy, or geolite 2, or the APIs).

Any help would be appreciated.

SUM not display correct sum MySQL

I have this query:

SELECT sum(TIMEDIFF(`time_out`, `time_in`)) as `total` FROM `user_log` WHERE `uid` = '1' AND `time_out` <> '0000-00-00 00:00:00'

Then I calculate the seconds to hours:

$total_difference = (($difference->total) / 60 / 60);

But this is showing me 22,352125 hours, which is impossible...

I've been testing and I have 2 records showing up if I don't use SUM:

SELECT TIMEDIFF(`time_out`, `time_in`) as `total` FROM `user_log` WHERE `uid` = '1' AND `time_out` <> '0000-00-00 00:00:00'

  1. 08:00:02
  2. 00:00:11

This result is far below the 22 hours I get when I use SUM in my query. Any help? I don't know what I'm doing wrong.

Thanks!

Is there a name for aggregation queries that record '0' values?

I see questions all the time (and perhaps a Meta post could be made about how to handle them) that follow the lines of:

Get the count of [some field] for [some object].

Where the problem usually lies in:

SELECT myField, COUNT(*)
FROM myTable
GROUP BY myField;

Which will not return rows that have 0 counts, so it typically involves preforming an outer join back to the table to get those counts.

Is there a name for this type of procedure? Is it still just simply Aggregation? The reason I wonder if it's different, is because it involves using a join to aggregate data that doesn't exist in the table.

Also, I have heard of special types of aggregation such as conditional aggregation, so I thought there might be a term [slang, or standard] for this type of operation.

MySQL fetch array not collecting and returning all the rows | PHP | MySQL

I have a function (see below)

public function ReadBets_Open($id) {
    $queryBase = "SELECT * FROM `vr_wp_bets` WHERE `is_open` = 'true' AND `id` = '%s';";
    $queryBase2 = sprintf($queryBase, $id);
    $selectQuery = mysql_query($queryBase2);
    $return = "<div style='max-height: 400px; overflow: scroll;'>";
    while ($result = mysql_fetch_array($selectQuery)) {
        //var_dump($result);
        $return = "<div style='border: 1pt solid black; width: 99%;'>";
        $return .= "<h2>" . $result['title'] . "</h2>";
        $return .= "<table>";

        $return .= "<tr><td style='width:50%;'>Sport: </td><td>" . $result['sport'] . "</td></tr>";
        $return .= "<tr><td style='width:50%'>Participant: </td><td>" . $result['participant'] . "</td></tr>";
        $return .= "<tr><td>Market: </td><td>" . $result['market'] . "</td></tr>";
        $return .= "<tr><td>Time: </td><td>" . date("H:i", strtotime($result['bettilltime'])) . "</td></tr>";
        $return .= "<tr><td>Odds: </td><td>" . $result['odds'] . "</td></tr>";
        $return .= "<tr><td>Stake: </td><td>&pound;" . $result['stake'] . "</td></tr>";

        if ($result['is_ew'] == "true") {
            $return .= "<tr><td>Each Way: </td><td>" . $this->CalculateEachWay($result['odds'], $result['ew_odds']) . "</td></tr>";
            $return .= "<tr><td>Estimated Return:</td><td>" . "N/A" ."</td></tr>";
        }
        else if ($result['odds'] == "SP") {
            $return .= "<tr><td>Estimated Return:</td><td>" . "N/A" ."</td></tr>";
        }
        else {
            $return .= "<tr><td>Estimated Return:</td><td>&pound;" . $result['estimated_return'] ."</td></tr>";
        }

        $return .= "</table>";
        $return .= "</div><br>";
    }
    $return .= "</div>";
    return $return;
}

And I know for a fact that there is 4 results in this that should be selected, however only one is returned by the fetch array, I was wondering if anyone can see an issue with this and if so what is it? This has had me stumped for a few days now and I really need an answer to this.

The way that I call the method is:

$classInstance->ReadBets_Open($current_user->ID);




NOTE
I am aware that I am using depreciated mysql_* functionality, this will be changed in the future, this needs to be made and released.

How to avoid persisting new object when oneToMany connection?

enter image description here

There is a three lines in returnreason-table and I don't want more lines there. User just choose one of the three reasons and I want only id to rma-table. Now it inserts a new line to reason-table every time when inserting new rma. I can take relation off between the tables but I wonder if there is better solution to avoid inserting new lines when persisting rma object? If I take cascadeType off from the class Rma, it is not helping/working. Then I got an error message, that jpa found an object, which is not persisted or something like that.

errormessage if I took cascadetype.ALL off

java.lang.IllegalStateException: During synchronization a new object was found through a relationship that was not marked cascade PERSIST: com.entity.Returnreason[ returnreasonId=null ].

public class Rma implements Serializable {
@ManyToOne(cascade = CascadeType.ALL)
private Returnreason returnreasonReturnreasonId;

public class Returnreason implements Serializable {
@OneToMany(mappedBy = "returnreasonReturnreasonId", cascade = CascadeType.ALL)
private Collection<Rma> rmaCollection;

How to get a specific number of rows from database using JDO?

I want to get 10 rows starting from row 20. Is there any way that I can accomplish this using Data Nucleus JDO? I am using MySql as backend.

All Threads Block on socket IO when using JDBC?

I am experiencing a very frustrating problem.

Basically I have a huge amount of sql update statements to perform on a mysql db using JDBC. To do this in the time required I am using Java's Executor Service with a fixed thread pool like so:

ExecutorService executor =  Executors.newFixedThreadPool(10);

So each thread calls the run method of another class I have and in that class an sql update operation is performed.

But it is running extremely slow and JProfiler has revealed that all the threads block on socket IO. I thought that mysql would be able to handle multiple update statements concurrently.

Any ideas on how to get around this problem?

Note I have 10 available processors on my machine.

Below is a screenshot of the Thread History screen from JProfiler. The Light Blue colour here indicates that the thread is in Net I/O( The thread is waiting to write data to a socket). Any help would be great thanks.enter image description here

struts2 application defaulting to error.jsp

I am creating a struts2 application. I want users to login to their account. If the record is found, it should go to the success.jsp. If the account is not found, it should default to to error.jsp. They can then register. The problem I am having is that whether the records are in the database or not, I get redirected to my error.jsp. I would appreciate some help here with some like explanation to go with it

Here are my files:

StudentInfo

package org.comp.dto;

//import

    public class StudentInfo implements Serializable{
        private int studentId;
        private String userName;
        private String password;
        private String password1;
        private String firstName;
        private String lastName;
        private int age;
        private String dateofBirth;
        private Calendar dateCreated;
        private GregorianCalendar lastLogin;


        public int getStudentId() {
            return studentId;
        }
        public void setStudentId(int studentId) {
            this.studentId = studentId;
        }
        public String getUserName() {
            return userName;
        }
        public void setUserName(String userName) {
            this.userName = userName;
        }
        public String getPassword() {
            return password;
        }
        public void setPassword(String password) {
            this.password = password;
        }
        public String getPassword1() {
            return password1;
        }
        public void setPassword1(String password1) {
            this.password1 = password1;
        }
        public String getFirstName() {
            return firstName;
        }
        public void setFirstName(String firstName) {
            this.firstName = firstName;
        }
        public String getLastName() {
            return lastName;
        }
        public void setLastName(String lastName) {
            this.lastName = lastName;
        }
        public int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }
        public String getDateofBirth() {
            return dateofBirth;
        }
        public void setDateofBirth(String dateofBirth) {
            this.dateofBirth = dateofBirth;
        }

        public GregorianCalendar getLastLogin() {
            return lastLogin;
        }
        public void setLastLogin(GregorianCalendar lastLogin) {
            this.lastLogin = lastLogin;
        }
        public Calendar getDateCreated() {
            return dateCreated;
        }
        public void setDateCreated(Calendar dateCreated) {
            this.dateCreated = dateCreated;
        }

        }

StudentInfo.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://ift.tt/UNuKEd" >
<hibernate-mapping>
 <class mutable="true" name="org.comp.dto.StudentInfo" table="studentinfo">

        <id name="studentId" type="int">
            <column name="studentId"/>
               <generator class="native"/>
        </id>

        <property column="userName" name="userName" type="string" not-null="true"/> 
        <property column="password" name="password" type="string" not-null="true"/>
        <property column="firstName" name="firstName" type="string" not-null="true"/>
        <property column="lastName" name="lastName" type="string" not-null="true"/>
        <property column="age" name="age" type="int" not-null="true"/>
        <property column="dateofBirth" name="dateofBirth" type="string" not-null="true"/>
        <property column="dateCreated" name="dateCreated" type="calendar" not-null="true"/>
        <property column="lastLogin" name="lastLogin" type="timestamp" not-null="true"/>
    </class>
</hibernate-mapping>

struts.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC  
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"  
    "http://ift.tt/18p24sP"> 
<struts>
    <package name="loginpackage" namespace="/" extends="struts-default">
         <action name="login" class="org.action.LoginAction" method="login">
            <result name="success">success.jsp</result>
            <result name="input">login.jsp</result>
            <result name="error">error.jsp</result>

         </action>  

         <action name="accountSetUpAction" class="org.action.LoginAction" method="accountSetUp">
            <result name="success">success.jsp</result>
         </action>
    </package> 
</struts>

success.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@ taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://ift.tt/kTyqzh">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Success page</title>
</head>
<body>
Login successfully! <s:property value="firstName"/>
</body>
</html>

LoginAction class

package org.action;

//import  

public class LoginAction extends ActionSupport implements ModelDriven{
    private int studentId;
    private String userName;
    private String password;
    private String firstName;
    private StudentInfo studentUser = new StudentInfo();
    private Session session;
    private String message;
    PreparedStatement sQry;
    ResultSet rs;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public int getStudentId() {
        return studentId;
    }

    public void setStudentId(int studentId) {
        this.studentId = studentId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public StudentInfo getStudentUser() {
        return studentUser;
    }

    public void setStudentUser(StudentInfo studentUser) {
        this.studentUser = studentUser;
    }

    public LoginAction() {
        this.session = HibernateUtil.getSessionFactory().getCurrentSession();
    }

    public void validate() {
        if (StringUtils.isEmpty(studentUser.getUserName())){
             addFieldError("userName", "Username cannot be blank");
         }
        if (StringUtils.isEmpty(studentUser.getPassword())){
             addFieldError("password", "Password cannot be blank");

        }
     }

    @Override
    public String execute() throws Exception {
            return SUCCESS; 
        }

    public String login(){
        String ret = ERROR;
        Connection conn = null;
        try {

            SessionImplementor impl = (SessionImplementor)session;
            conn = impl.getJdbcConnectionAccess().obtainConnection();
            org.hibernate.Transaction tx = session.beginTransaction();

            String sQry = "SELECT firstName FROM StudentInfo WHERE studentinfo.userName=? AND studentinfo.password=?";
            PreparedStatement q = conn.prepareStatement(sQry);


            q.setInt(1, studentId);
            q.setString(2, userName);
            q.setString(3, password);


            rs = q.executeQuery();

            while (rs.next()){
                rs.getString(2);

                ret = SUCCESS;
            }


        }
                catch(Exception ex){
            ret = ERROR;
        }

        finally
        {
            if (conn !=null){
                try {
                    session.getTransaction().rollback();
                    conn.close();
                }
                catch (Exception ex){

                }
            }

        }
        return ret;

        }


    public String accountSetUp() throws Exception{
        Transaction tx = null;
        try {
        tx = session.beginTransaction();

        Calendar dateCreated = new GregorianCalendar();
        studentUser.setDateCreated(dateCreated);
        session.save(studentUser);
        session.getTransaction().commit();      

        return SUCCESS;
    }
        catch (HibernateException ex){
         if(tx != null) tx.rollback();
         ex.printStackTrace();
         return null; 

        }

        finally
        {
            session.close();

        }
        }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    @Override
    public Object getModel() {
        return studentUser;
    }

    }

The login.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
   <%@ taglib uri="/struts-tags" prefix="s"%> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://ift.tt/kTyqzh">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login Page</title>
</head>
<body>
   <s:form action="login" method="get">
       <s:textfield label="Please StudentID:" key="studentId"/>
       <s:textfield label="Please Enter User Name:" key="userName"/>
       <s:password label="Please Enter Password:" key="password"/>
       <s:submit/>
   </s:form>
</body>
</html>

PHP - return to another page using header

I was trying to update data in database using oop php but after I call function update I should return the user to view all page , so i used header but then whenever i try to view update page, it views view all page. what should i do?

<body>

    <form  method='POST'>
<table>
<tr>
<td>id</td>
<td>
<input type='text' name='id' value='' ></td>
</tr>
<tr>
<td>price</td>
<td>
<input type='text' name='price' value='' ></td>
</tr>
<tr>
<td></td>
<td>
<input type='submit' name='commit' value='Submit'>
</td>
</tr>

</table>
</form> 
</body>
</html>

<?php
require_once ('database.php');
require_once ('admin.php');
$object= new admin();
if (isset($_POST['commit'])) {
$id    = $object->clean($_POST['id']);
$price = $object->clean($_POST['price']);
$object->update_sport($id ,$price);
}
header("C:\wamp\www\omnia\viewsports.php");

this is viewsports.php

<head>
        <title>Sports</title>
    </head>

    <body>
         <h1>Sports</h1>
         <h3>Use ID to update</h3>
        <?php 
        require_once 'database.php';
        $obj=new databaseClass();
        echo '<table>';
        echo '<tr bgcolor="white">';
        echo ' <td>ID</td><td>Name</td><td>Price</td>';
        echo ' </tr>';
        $sql="SELECT sport.id, sport.name, sport.price FROM sport";

        $result=  mysql_query($sql);
        $i=0;
        while($row =  mysql_fetch_assoc($result)){
            echo  '<tr><td>' .$row['id'].'</td><td>'
            .$row['name'].'</td><td>'
            .$row['price'].'</td>'
            .'<td><a href="delete_sport.php?id=' . $row['id'].'">Delete</a></td>'
            .'<td><a href="update_sport.php?id=' . $row['id'].'">Update</a></td></tr>';
            $i++;
        }
        echo'</table>';
        ?>
         <a href="add_sport.php">Add</a>
    </body>
</html>

store order data (to be exact ID) in different rows in mysql

I want to follow the suggestions of this posts, but I have a problem of understanding: How to store complex product/order data in MySQL?

My php code looks like this:

if(isset ($_POST['submit'])) {
$payment = $_POST['payment'];
$shipping = $_POST['shipping'];
$order_person = $_POST['order_person'];
$total = $_POST['total'];
$status = $_POST['status'];
$q = "INSERT INTO orders(payment,shipping, order_person, total, status) VALUE(:payment, :shipping, :order_person, :total, :status)";
$query = $con->prepare($q);
$results = $query->execute(array(
":payment" => $payment,
":total" => $total,
":shipping" => $shipping,
":status" => $status,
":order_person" => $order_person
));
}

In my mysql database I have a row named "orders" where I have the fields:

  • orderID
  • date
  • order_person
  • shipping
  • payment
  • total
  • status

The order ID is generated with AUTO_INCREMENT. I created a second row named "order_details". Here I want to store my product details.

My problem is: I do not understand how exactly do I store the order ID into my row "orders" and also into "order details". I would be grateful about a detailed explanation. I am so confused. Thank you very much!

Some misunderstanding with pagination

I trying to make pagination from one post to next post in the single blog post. But seems I don't understand it very well. The problem is that when I open article with ID-1 and I click on next button I get blank/empty page.

This is the post page which get the ID of the chosen post in blog.php. This is what I have so far. Any suggestions?

<?php
     // include database connection
     require_once 'database.inc.php';
     $pdo = Database::connect();
       if(isset($_GET['post_id']) && is_numeric($_GET['post_id'])){
                $post_id = $_GET['post_id'];
     // page is the current page, if there's nothing set, default is page 1
     $page = isset($_GET['page']) ? $_GET['page'] : 1;

     // set records or rows of data per page
     $recordsPerPage = 1;

     // calculate for the query LIMIT clause
     $fromRecordNum = ($recordsPerPage * $page) - $recordsPerPage;

     // select all data
     $query = "SELECT * FROM posts WHERE post_id = $post_id LIMIT {$fromRecordNum}, {$recordsPerPage}";

     $stmt = $pdo->prepare( $query );
     $stmt->execute();

     //this is how to get number of rows returned
     $num = $stmt->rowCount();

     //check if more than 0 record found
     if($num>0){                           
            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){               

                     echo ' 
                           // post body ';     
                }
    }                                                 

         // *************** <PAGING_SECTION> ***************

             // ***** for 'first' and 'previous' pages
             if($page>1){       
                 // ********** show the previous page
                 $prev_page = $page - 1;
                 echo "
                <a href='" . $_SERVER['PHP_SELF'] . "?page={$prev_page}'>
                    <div class='prev-btn control-nav text-left'>
                        <h5>Previous Post</h5>
                    </div>
                </a>";     
             }
             // find out total pages
             $query = "SELECT COUNT(*) as total_rows FROM posts";
             $stmt = $pdo->prepare( $query );
             $stmt->execute();

             $row = $stmt->fetch(PDO::FETCH_ASSOC);
             $total_rows = $row['total_rows'];

             $total_pages = ceil($total_rows / $recordsPerPage);

             if($page<$total_pages){
                 // ********** show the next page
                 $next_page = $page + 1;
                 echo "<a href='" . $_SERVER['PHP_SELF'] . "?page={$next_page}'>
                    <div class='next-btn control-nav text-right'>
                        <h5>Next Post</h5>
                    </div>
                </a>";
             }
}
?>                       

yahoo hosting mysql server issues

I have uploaded files on yahoo hosting , but when i open its phpmyadmin credentials of mysql work fine but same credentials not work in code . here is super easy code to connect my

   <?php
$conn = mysql_connect('localhost', 'username','password');
if (!$conn) {
            echo "<p>Could not connect to mysql server </p>\n";
            echo mysql_error();
        }
mysql_select_db('..CMS-2', $conn);
?>

some time it says 500 - Internal Server Error and some time it says message print in code , i have also used mysql instead of localhost but no benefit

Could not connect to mysql server Can't connect to local MySQL server through socket '/tmp/mysql.sock' (46)

MySQL dump --where="1 limit 2, 3", 1 means what?

mysqldump -uroot --opt --where="1 limit 2, 3" dbname --no-create-info > bk.sql

I use this command to dump partial data of database or dump large database to multiple files and it works well.

As I tested,

2 means skip first 2 recoreds,

and 3 means dump 3 records,

but I don't understand 1 means what in --where="1 limit 2, 3"?

How can i add Dynamic Json data into a Mysql Database.

How can i add JSON Data into a Database? i have a script there is generating automatic updated JSON Data. i read in a book that i should use a methode called

JSON_decode 

I Think i should have to do something like, put The value into The tables for each value. Then try to use The methode JSON_decode and then make a loop foreach. but i am not sure about this. what is the best way, and can you tell me what to do in my case or maby show a example?

Here is the data located:

http://ift.tt/1H3Ee3g

The current script:

<?php
require_once ('simple_html_dom.php');

$html = @file_get_html('http://csgolounge.com/');
$output = array();

if(!$html) exit(json_encode(array("error" => "Unable to connect to CSGOLounge")));

// Source: http://ift.tt/1cv6y4s
function strip_tags_content($text, $tags = '', $invert = FALSE) {
preg_match_all('/<(.+?)[\s]*\/?[\s]*>/si', trim($tags), $tags);
$tags = array_unique($tags[1]);

if(is_array($tags) AND count($tags) > 0) {
    if($invert == FALSE)
        return preg_replace('@<(?!(?:'. implode('|', $tags) .')\b)(\w+)\b.*?>.*?</\1>@si', '', $text);
    else
        return preg_replace('@<('. implode('|', $tags) .')\b.*?>.*?</\1>@si', '', $text);
} elseif($invert == FALSE) {
    return preg_replace('@<(\w+)\b.*?>.*?</\1>@si', '', $text);
}

return $text;
}

foreach($html->find('.matchmain') as $match) {
$when = $match->find('.whenm')[0];
$status = trim($when->find('span')[0]->plaintext) == "LIVE" ? true : false;
$event = $match->find('.eventm')[0]->plaintext;
$time = trim(strip_tags_content($when->innertext));
$id = substr($match->find('a')[0]->href, 8);
    $additional = substr(trim($when->find('span')[$status ? 1 : 0]->plaintext), 4);
$result;

$output[$id]["live"] = $status;
$output[$id]["time"] = $time;
$output[$id]["event"] = $event;

foreach($match->find('.teamtext') as $key => $team) {
    $output[$id]["teams"][$key] = array(
        "name" => $team->find('b')[0]->plaintext,
        "percent" => $team->find('i')[0]->plaintext
    );

    if(@$team->parent()->find('img')[0])
        $result = array("status" => "won", "team" => $key);
    }

if($additional)
    $result = $additional;

if(isset($result))
    $output[$id]["result"] = $result;
}

echo json_encode($output);

ERROR 1044 (42000): Access denied for user ''@'localhost' to database 'mysql'

I know this question is asked many times, and I read al lot of questions going about this, but I think mine is different.

I use a Mac with version 10.10.3 and a Terminal to do my commands.

I am trying to create a local database (and I did it before), but for some reason the access is constantly denied.

This is how my terminal looks like:

iMac-van:mysql 639$ /usr/local/mysql/bin/mysql -v
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.6.24 MySQL Community Server (GPL)

Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Reading history-file /Users/639/.mysql_history
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> quit;
Writing history-file /Users/639/.mysql_history
Bye
iMac-van:mysql 639$ /usr/local/mysql/bin/mysql -u root
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 3
Server version: 5.6.24 MySQL Community Server (GPL)

Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> create database wordpress_db;
ERROR 1044 (42000): Access denied for user ''@'localhost' to database 'wordpress_db'

As you can see I can login to mysql, but I have no permission to create a database.

I tried to login like:

$ /usr/local/mysql/bin/mysql -u root

And:

$ /usr/local/mysql/bin/mysql -u root -p

I have no password, but I can enter mysql without one, but then I cannot create a database.

Select current_user(); returns this:

mysql> select current_user();
+----------------+
| current_user() |
+----------------+
| @localhost     |
+----------------+
1 row in set (0,00 sec)

Getting string results to INSERT into database from foreach loop

I am creating a checkout system and I am trying to figure out how I am going to insert the string from the results of my foreach loop that displays which products were chosen, the quantity, and and pertinent data about them.

The way I have the shipping information in place is I validate it and if it passes, I allow it to be inserted once the order is placed. Like this:

if(Input::exists()) {
        $validate = new Validate();
        $validation = $validate->check($_POST, array(
            'fullname' => array(
                'required' => true,
                'min' => 2,
                'max' => 50
            )

if($validation->passed()) {
            if(isset($_POST['create'])){ 
                $fullname = trim( $_POST['customer_name'] );

<div class="field">
                                        <label class="paddingleft" for="fullname">Full Name</label>
                                    <div class="center"><input type="text"  class="biginputbarinline" name="fullname" value="<?php echo escape(Input::get('firstname')); ?>" required></div>
                                    </div>

I am wanting to INSERT all of the data on my page at once and not do seperate INSERT submissions. I have the shipping info, payment info and Order confirmation all on the same page. I will not be storing the payment info in my database. So that is irrelevant to this question. The Order confirmation is where the order will be displayed and I want that info to send in to my database with my shipping info.

The part I am really confused with is how to INSERT the actual string this foreach loop displays. This is how I have the Order confirmation section as of now..

<div class="checkoutconfirmationcontainer">
                                            <?php foreach($_SESSION['shopping_cart'] as $id => $product) {
                                                    $product_id = $product['product_id'];
                                        ?>
                                        <span class="tealmedium"><?php echo $product['quantity'] . " - "  . $products[$product_id]['name'] . $message; ?></span><br><br><br>


                                            <div class="floatleft"><div class="smallerimgcontainer">
                                                    <?php
                                                        $result = mysqli_query($con,"SELECT * FROM products");
                                                        if($row = mysqli_fetch_array($result)) {
                                                            $products[$row['product_id']] = $row;

                                                        if($row['image'] == ""){
                                                                echo "<img class='sizedimg' src='/productpics/coming_soon.png' alt='Coming Soon'>";
                                                        } else {
                                                                echo "<img class='sizedimg' src='/productpics/".$row['img']."' alt='Product Picture'>";
                                                        }
                                                        echo "<br><br><br><br>";
                                                        }
                                                    ?>
                                            </div></div>
                                            <div class="checkoutitemsummary">
                                                <?php echo "<a href='./viewProduct.php?view_product=$id'>" . $product['name'];?><?php echo $products[$product_id]['name']; ?> </a>
                                                    <p><span class="redprice"><?php echo '$' . $products[$product_id]['price'] . "<br />"; }?></span></p>
                                            </div>

How could I get the foreach loop produced string to be inserted into my database?

OpenShift: MySQL PDO 'connection refused', works locally

I have an API i want to deploy to OpenShift, everything works locally, but when trying to use it online i get some problems. When trying to connect to the database, using PDO, i get this error:

Failed to connect to the database: SQLSTATE[HY000] [2002] Connection refused

i have the database set up correctly, and i have the correct details for the connection (im pretty sure). heres some code:

$username = "myuser"; 
$password = "lmnop"; 
$host = "127.0.0.1"; 
$dbname = "loginapi"; 
$port = "3306";

$db = new PDO("mysql:host={$host};port={$port};dbname={$dbname};charset=utf8", $username, $password, $options);

what could be wrong that OpenShift is not allowing the connection? considering that this works on my local machine?

thanks!

MySQL set database name dynamically and select db.schematable

I am creating a stored procedure, which takes a number of input parameters. Depending on the conditions as shown below, I would like to select the appropriate database to use.

I know you cannot use "USE" keyword in a stored proc and I have also tried to set @ds in the query but with not much success.

SQL

BEGIN
declare dbName varchar(255); --attempt at using db name passed in
select imemberdbname into dbName;
set @ds = concat(dbName,'.customers'); -- I have also tried this

if LENGTH(icustomername) > 0 THEN
    (Select customerid, customername, postcode, accountnumber from dbName.customers
        WHERE customername = icustomername);
ELSEIF len(ipostcode) > 0 THEN
    (Select customerid, customername, postcode, accountnumber from dbName.customers
        WHERE postcode = ipostcode);
ELSE 
    (Select customerid, customername, postcode, accountnumber from dbName.customers
        WHERE accountnumber = iaccountnumber);
end if;

END

I am unable to select the db.table in order to carry out the selects. Is there a way this is possible? or is there a better solution?

Trying to input a lot of Data into mysqldb

#!/usr/bin/env python

from __future__ import print_function

import pymysql.cursors

Journal=open('J_15April.txt')

jrn=Journal.read()

Zeile=jrn.split('14.04.2015')

conn = pymysql.connect(host='localhost', port=3306, user='root',passwd='',db='daten', cursorclass=pymysql.cursors.DictCursor)


ean = int(row[0])
smr = char(row[1])
uhrzeit = char(row[2])


for line in Zeile:
cur = conn.cursor()
    if 'BOTTLE_ID' in line

        line2 = line.split(';')

        line3 = line2[0].strip(' BOTTLE_UNIQUE: BOTTLE_ID: 0')

        uhrzeit = (line3[:-4])

        if 'EAN' not in line:
            ean = 0

        else:
           ean = line2[7].strip('EAN: ')


        if ' SMR: 1;' in line:
            smr = ('gelesen')

        else:
            smr = ('nicht gelesen')

        cur.execute("INSERT INTO lga (ean, smr, uhrzeit) VALUES  ('%s','%s','%s')%(ean, smr, uhrzeit)")
        cur.fetchall()




cur.close()
conn.commit()
conn.close()

Hi guys,

im currently trying to put a lot of data into a mysqldb. I wrote two seperate programms, one is for filtering the important stuff out of a very long .txt and the other one inserts them in the database.

The actual problem now occured when i tried combine those two programm to automatically read and insert the data. I think the structure of the shown programm my be a little chaotic and thats the main reason why it is not working. Im absolutely new to python and it was quite hard for me two make the two other programms work so please help me out.

If you are interested in the two single functions i can post them as well.

greetings

trbo

How to pass multiple parameters into a mysql stored procedure

I have a stored procedure that I am working on that is returning an invalid return when I try to pass parameters to it compared to when I run it with hard-coded values.

Procedure with hard coded values:

BEGIN
    SELECT COUNT(DISTINCT ItemID) 
    FROM ( 
        SELECT * 
        FROM sandbox_inventoryitempurchase 
        WHERE OrgID = '2781823' 
            AND PurchaseMonth>'2015-03-01'
    ) as DistinctCount;
END

When run, this returns: 16 which is correct.

Procedure with two input parameters:

BEGIN
    SELECT COUNT(DISTINCT ItemID) 
    FROM ( 
        SELECT * 
        FROM sandbox_inventoryitempurchase 
        WHERE OrgID = orgid 
            AND PurchaseMonth>sincedate
    ) as DistinctCount;
END

The input parameters are defined as:

IN userid integer,IN orgid integer,IN sincedate date

When run, this returns: 334 which is not correct.

I am new to stored procedures and would appreciate any assistance offered regarding what I am doing wrong and what I need to do to resolve?

Thanks...

why is Hive giving metaexception when i am trying drop database and i am using mysql as metastore?

hive>> DROP DATABASE IF EXISTS ABC.XYZ;

FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.DDLTask. MetaException(message:One or more instances could not be retrieved)

hive-site.xml:

<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>

<configuration>
<property>
    <name>javax.jdo.option.ConnectionURL</name>
    <value>jdbc:mysql://localhost/metastore?createDatabaseIfNotExist=true://localhost/hive</value>
    <description>JDBC connect string for a JDBC metastore</description>
</property>

<property>
  <name>javax.jdo.option.ConnectionUserName</name>
  <value>hive</value>
</property>

<property>
  <name>javax.jdo.option.ConnectionPassword</name>
  <value>hive</value>
</property>

<property>
  <name>javax.jdo.option.ConnectionDriverName</name>
  <value>com.mysql.jdbc.Driver</value>
</property>
</configuration>

**i am using hadoop 2.6.0 with hive 1.1.0 on RHEL6 and mysql version is mysql-community-release-el6-5.noarch.rpm **

Detailed log:

2015-05-08 02:27:54,644 ERROR [main]: exec.DDLTask (DDLTask.java:failed(512)) - org.apache.hadoop.hive.ql.metadata.HiveExcepti
on: MetaException(message:One or more instances could not be retrieved)
        at org.apache.hadoop.hive.ql.metadata.Hive.dropTable(Hive.java:1003)
        at org.apache.hadoop.hive.ql.metadata.Hive.dropTable(Hive.java:934)
        at org.apache.hadoop.hive.ql.exec.DDLTask.dropTable(DDLTask.java:3719)
        at org.apache.hadoop.hive.ql.exec.DDLTask.dropTableOrPartitions(DDLTask.java:3654)
        at org.apache.hadoop.hive.ql.exec.DDLTask.execute(DDLTask.java:323)
        at org.apache.hadoop.hive.ql.exec.Task.executeTask(Task.java:160)
        at org.apache.hadoop.hive.ql.exec.TaskRunner.runSequential(TaskRunner.java:88)
        at org.apache.hadoop.hive.ql.Driver.launchTask(Driver.java:1638)
        at org.apache.hadoop.hive.ql.Driver.execute(Driver.java:1397)
        at org.apache.hadoop.hive.ql.Driver.runInternal(Driver.java:1183)
        at org.apache.hadoop.hive.ql.Driver.run(Driver.java:1049)
        at org.apache.hadoop.hive.ql.Driver.run(Driver.java:1039)
        at org.apache.hadoop.hive.cli.CliDriver.processLocalCmd(CliDriver.java:207)
        at org.apache.hadoop.hive.cli.CliDriver.processCmd(CliDriver.java:159)
        at org.apache.hadoop.hive.cli.CliDriver.processLine(CliDriver.java:370)
        at org.apache.hadoop.hive.cli.CliDriver.executeDriver(CliDriver.java:754)
        at org.apache.hadoop.hive.cli.CliDriver.run(CliDriver.java:675)
        at org.apache.hadoop.hive.cli.CliDriver.main(CliDriver.java:615)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at org.apache.hadoop.util.RunJar.run(RunJar.java:221)
        at org.apache.hadoop.util.RunJar.main(RunJar.java:136)
Caused by: MetaException(message:One or more instances could not be retrieved)
        at org.apache.hadoop.hive.metastore.ObjectStore$GetHelper.run(ObjectStore.java:2378)
        at org.apache.hadoop.hive.metastore.ObjectStore.getPartitionsInternal(ObjectStore.java:1705)
        at org.apache.hadoop.hive.metastore.ObjectStore.getPartitions(ObjectStore.java:1699)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at org.apache.hadoop.hive.metastore.RawStoreProxy.invoke(RawStoreProxy.java:98)
        at com.sun.proxy.$Proxy9.getPartitions(Unknown Source)
        at org.apache.hadoop.hive.metastore.HiveMetaStore$HMSHandler.dropPartitionsAndGetLocations(HiveMetaStore.java:1632)
        at org.apache.hadoop.hive.metastore.HiveMetaStore$HMSHandler.drop_table_core(HiveMetaStore.java:1505)
        at org.apache.hadoop.hive.metastore.HiveMetaStore$HMSHandler.drop_table_with_environment_context(HiveMetaStore.java:16
76)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at org.apache.hadoop.hive.metastore.RetryingHMSHandler.invoke(RetryingHMSHandler.java:102)
        at com.sun.proxy.$Proxy10.drop_table_with_environment_context(Unknown Source)
        at org.apache.hadoop.hive.metastore.HiveMetaStoreClient.drop_table_with_environment_context(HiveMetaStoreClient.java:1
974)
        at org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient.drop_table_with_environment_context(SessionHiveMetaSt
oreClient.java:118)
        at org.apache.hadoop.hive.metastore.HiveMetaStoreClient.dropTable(HiveMetaStoreClient.java:906)
        at org.apache.hadoop.hive.metastore.HiveMetaStoreClient.dropTable(HiveMetaStoreClient.java:842)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at org.apache.hadoop.hive.metastore.RetryingMetaStoreClient.invoke(RetryingMetaStoreClient.java:91)
        at com.sun.proxy.$Proxy11.dropTable(Unknown Source)
        at org.apache.hadoop.hive.ql.metadata.Hive.dropTable(Hive.java:997)
        ... 23 more

workbench connection to ubuntu with fish shell

I am connecting to a ubuntu server through mysql-workbench, when I want to view option file, I am getting one error

LC_AL cat /etc/mysql/my.cnf fish: Unknown command “LC_AL” Did you mean set $LC_ALL C”? For information on assigning values to variables, see the help section on the set command by ...

I was wondering how the LC_ALL is not available, I spent a lot of time and tried locale options until I understand one of my colleague installed fish shell on the system.

The command that workbench is trying to run is becoming invalid since variables in fish need to start with env .

If I type bash in fish and then type the command that workbench is trying to run, then everything is fine

I tried to change login behavior of workbench but couldn't find any thing in their website about the configuration file.

the only configurable part look like in workbench is mysql.profiles's xml that has nothing useful about this.

Do I have any solution other than disable fish as default shell?

Laravel 4 how to merge database tables and order them by created_at?

I have 4 database tables that I want to merge together, and than I want to order all the data by created_at field. With my code all data is still grouped per database table, the result should be some sort of timeline of all my tables data. What am I doing wrong? It is only showing 4 items...

public function showIndex()
{

    $users = User::orderBy('created_at', 'desc')->get();
    $projects = Project::with('votes')->orderBy('created_at', 'desc')->get();
    $events = Calendar::orderBy('created_at', 'desc')->get();
    $jobs = Job::orderBy('created_at', 'desc')->get();

    $all = $users->merge($projects)->merge($events)->merge($jobs);

    return View::make('users.index')->with('events', $all);

}

using Hibernate numeric restriction for a varchar column

I'm using the Hibernate Criteria in order to build queries dynamically. One of these dynamic queries uses a column stored on MySQL as a varchar. But, is a column storing prices of items (only has numeric values with decimals). So I would like to generate queries using ge le or between.

Is there a way to tell to hibernate something like "hey, this column is of type varchar, but its content is numeric so apply my numeric restrictions (please)"?

browser shows only part of result list (php, mysql) [on hold]

I got a weired one today, not really a programming issue though.

I created this tool for company internal use and it's still growing. One part of it is a list of items who's stock is below some threshold. This list is also capable of showing all items without regard of the threshold, so can have say up to 2000 or so entries. All of those come out of a mysql DB and I'm handling things in php. The mentioned 2000 entries get formatted somewhat by Javascript (showing / hiding stuff etc.) in the browser - nothing really fancy.

It does work nicely... However, I just came across one computer that shows just under 10% of the requested list. I tried on three other computers in the office and all is good there. Just the one machine doesn't show it all. On one occasion I saw that it stopped displaying in the middle of an object, so just half of it was there. I cleaned everything like cookies and cache and everything the browser might save - no success. We're talking about one of those hybrid laptops with detachable screen / touchscreen.. It's a nicely quick and powerful machine, running photoshop and equally demanding apps...

Has anyone any idea???

Select data using PDO and a PHP function

When I try to select one nome from my bd it doesn't show anything

That's the function to select a name:

public function searchName(){
    $db = new Conection();
    $query = $db->prepare("SELECT * FROM dog WHERE id = 1");
    $query->execute();
    $result = $query->fetchAll(PDO::FETCH_OBJ);
    foreach($result as $row)
    {
        return $row['name'];//return to getName

    }
}

here is the code from getName:

    require 'Conection.php';
    require 'model/Dog.php';

    $dog = new Dog;
    $res = $dog->searchName(1);

    echo $res;

The class Connection is ok.

MySQL check case where a date is 0000-00-00 00:00:00?

I have this MySQL query:

SELECT `date_joined`, `date_last_joined` FROM `users` WHERE `name` = "mary"

The date_last_joined column is currently 0000-00-00 00:00:00 for all users. It's then updated to the current date next time they log in.

So my question is, how would I return the date_joined if date_last_joined is 0000-00-00 00:00:00, and date_last_joined if it isn't? Is this possible in a MySQL query?

The reasons for this are that returning 0000-00-00 00:00:00 in a Java prepared MySQL query causes all sorts of issues.

How to delete all the records except the one with the latest date and based on some where condition

I have a table with 20 records. Now I want to delete records with column name as Action "system sent reminder notice to A"(15 records with same message) apart from the one with the latest date (I cant specify the date on or before, as I wanted this to be in general).

How to get output from php to typeahead?

I am using twitter typeahead and php as backend for getting data from mysql.But i am not able to see any suggestions when i start typing on the text box. i think because the php output has to be JSON encoded..

how can i encode the output

output:

echo '<a href="results.html" class="searchres" onclick="navigate()" style="color:#696969;text-decoration:none;"><img src='.$iurl.' class="icons" /><div class="results" style="color:#696969;text-decoration:none;">'."$fname".'</div><span style="color:#696969;text-decoration:none;" class="author">'.$caption.'</span></a>'."\n";

html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example of Twitter Typeahead</title>
<script src="http://ift.tt/13qgtmt"></script>
<script  type="text/javascript" src="../js/typeahead.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    $('input.typeahead').typeahead({
        name: 'countries',
        prefetch: 'getvalues.php',
        limit: 10
    });
});  
</script>
<style type="text/css">
.bs-example{
    font-family: sans-serif;
    position: relative;
    margin: 100px;
}
.typeahead, .tt-query, .tt-hint {
    border: 2px solid #CCCCCC;
    border-radius: 8px;
    font-size: 24px;
    height: 30px;
    line-height: 30px;
    outline: medium none;
    padding: 8px 12px;
    width: 396px;
}
.typeahead {
    background-color: #FFFFFF;
}
.typeahead:focus {
    border: 2px solid #0097CF;
}
.tt-query {
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.075) inset;
}
.tt-hint {
    color: #999999;
}
.tt-dropdown-menu {
    background-color: #FFFFFF;
    border: 1px solid rgba(0, 0, 0, 0.2);
    border-radius: 8px;
    box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
    margin-top: 12px;
    padding: 8px 0;
    width: 422px;
}
.tt-suggestion {
    font-size: 24px;
    line-height: 24px;
    padding: 3px 20px;
}
.tt-suggestion.tt-is-under-cursor {
    background-color: #0097CF;
    color: #FFFFFF;
}
.tt-suggestion p {
    margin: 0;
}
</style>
</head>
<body>
    <div class="bs-example">
        <input type="text" class="typeahead tt-query" autocomplete="off" spellcheck="false">
    </div>
</body>
</html>         

getvalues.php

  <?php
require_once "config.php";
$q = strtolower($_GET["q"]);
if (!$q) return;

$sql = "select file_name,img_url,captions from completer";
$rsd = mysql_query($sql);
while($rs = mysql_fetch_array($rsd)) {
    $fname = $rs['file_name'];
    $iurl = $rs ['img_url'];
    $caption = $rs ['captions'];
    echo '<a href="results.html" class="searchres" onclick="navigate()" style="color:#696969;text-decoration:none;"><img src='.$iurl.' class="icons" /><div class="results" style="color:#696969;text-decoration:none;">'."$fname".'</div><span style="color:#696969;text-decoration:none;" class="author">'.$caption.'</span></a>'."\n";
}
?>

Prepared Statement query in TextBox using C#

I'm using Visual Studio 2013 and doing this for my personal project. What I am trying to do is that I tried to use prepared statement in this query however I still get @fname eventhough I typed first name in textbox. Do you know what is wrong? Sorry, my English is difficult for me but I'm doing my best to explain this.

query = "SELECT pkey.keyword AS \"Keyword\", p.title AS \" Title\", p.abstract AS \"Abstract\", p.citation AS \"Citation\", CONCAT_WS(\" \", f.fname, f.lname) AS \"Name\", f.email AS \"Email\" " +
  " FROM paper_keywords pkey" +
  " INNER JOIN papers p ON pkey.id = p.id" +
  " INNER JOIN authorship a ON p.id = a.paperId" +
  " INNER JOIN faculty f ON a.facultyId = f.id WHERE " +
  " f.fname LIKE \"%@fname%\" ";

Here is my codes at below:

conn = new MySqlConnection(stringConn);
cmd = new MySqlCommand(query, conn);
cmd.Parameters.AddWithValue("@fname", fnametextBox.Text);
conn.Open();

DataTable datatable = new DataTable();
adapter = new MySqlDataAdapter(cmd);
adapter.Fill(datatable);

dataGridView1.DataSource = datatable;
dataGridView1.DataBindings.ToString();
MessageBox.Show(query);