jeudi 30 juin 2016

How to join tables including all ids from left table but only showing information from the right table given certain where clause


I have an attendees table with the following structure:

+--------------+---------+
| attendee_id  | others1 |
+--------------+---------+
|    abcd      | A       |
|    ghij      | B       |
|    defg      | C       |
+--------------+---------+

And also an eventattendees table with the following structure:

+--------------+---------+----------+
| attendee_id  | others2 | event_id |
+--------------+---------+----------+
|    wxyz      | D       |     1    |
|    mlno      | E       |     2    |
|    defg      | F       |     3    |
|    defg      | G       |     2    |
|    abcd      | H       |     1    |
+--------------+---------+----------+

What I want is to create a query that, given some event_id, returns a join of these tables (by attendee_id) that includes all attendee ids from attendee table and also returns the information from the eventattendde tables which a match for that event_id. Say, for event_id 3:

+--------------+---------+---------+----------+
| attendee_id  | others1 | others2 | event_id |
+--------------+---------+--------------------+
|    abcd      | A       |  null   |   null   |
|    ghij      | B       |  null   |   null   |
|    defg      | C       |    F    |     3    |
+--------------+---------+--------------------+

How can I do that for mysql?


MySQL won't start after changin my.cf


I'm working on a website and I'm getting this MySQL error:

"(...) this is incompatible with sql_mode=only_full_group_by (...)"

I've looked for an answer and I realized I had to change the sql_mode of my MySQL. So I've added the following line to /etc/mysql/my.cnf:

sql_mode="STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"

But now when I executed sudo service mysql restart it takes a really long time and then shows this message:

Job for mysql.service failed because the control process exited with error code. See "systemctl status mysql.service" and "journalctl -xe" for details.

So now I removed that line and I have to execute the command by hand everytime I boot my PC.

Can anyone help me?


How do i change CSS elements using javascript and a HTML button [duplicate]


This question already has an answer here:

i'm quite new to HTML, CSS and Javascript, but i would like to know how i could change my CSS elements using javascript and get that to interact with a HTML button. What i mean by this is that if i press a button made with HTML, i could have a shape in CSS which could be hidden and shown by a press of that button.

HTML -

    <button type="button">HIDE THE SQUARE PLEASE :(  </button>
    <div id="red"></div>

CSS -

    #red {
    width: 100px;
    height: 100px;
    background: red;
    }

So how would i get that square to be hidden and appear at the press of a button using javascript?


Very weird behavior when working with background size CSS3


I recently learned about the background-size property thanks to this topic Set size on background image with CSS? As you can guess, I am trying to make a background image take up the full screen and no more/no less. Here is my fiddle https://jsfiddle.net/1x7ytdaa/ document.body.style.backgroundImage = "url('http://www.crystalinks.com/ColosseumNight2.jpg')"; document.body.style.backgroundSize = "contain"; Here is what the contain property does Scale the image to the largest size such that both its width and its height can fit inside the content area It shouldn't matter what size the image is. If it's smaller, it should be scaled to the full size of the screen. If it's larger, it should be scaled down. In the fiddle, you can see that the image is repeated 5 times horizontally and 5 1/2 times vertically. I've tried 100% 100% and while the width stretches the full screen, it still shows the same image 5 1/2 times vertically I can not explain this behavior. Does anyone have any ideas?

MaterializeCss Form input (submit) button


I am asking this question because I was faced we this very problem and found little (unconcise) to none information on the matter, here goes:

Having an html form, how to properly set up a submit button with materializecss?

If you try the conventional way, that is:

<form>
    <div class="file-field input-field">
        ...
        <input type ="submit" class ="btn waves-effect waves-light" value = "Submit"/>
    </div>
</form>

This is what you'll get: enter image description here

As you can see the clickable part is only the middle of the button, and the rest won't trigger the form submition.


What i am looking for are answers (no javascript, just html) that offer alternatives. I'll post my own answer and hope for interesting alternatives.


MySQL Stored Procedure - IF EXISTS ... THEN returning unexpected result


The below is my Stored Procedure(Routine) to check whether or not a user with Username(input) exists in the database. Inside the database, I already have a user with Username - 'dev'. However, when I ran the below routine, it returned me with res = 1, which I expected it to be -1.

I called the routine this way. Please correct me too if I am calling it the wrong way. I am really new to MySQL Routines.

CALL usp_GetUserValidation ('dev', @ErrorCode)

Can any MySQL Routine pros here enlighten me on this? Thank you in advance guys :)

DELIMITER $$
CREATE PROCEDURE usp_GetUserValidation(IN `@Username` VARCHAR(255), OUT `@ErrorCode` INT)
    LANGUAGE SQL
    NOT DETERMINISTIC
    CONTAINS SQL
    SQL SECURITY DEFINER
    COMMENT 'To validate user login'
BEGIN

    IF EXISTS
    (SELECT UserID 
        FROM mt_User
        WHERE UserName = @Username)
    THEN
            SET @ErrorCode = -1;


    ELSE
        SET @ErrorCode =  1;

    END IF;


    SELECT @ErrorCode AS res;

END$$
DELIMITER ;

How to automatically divide a div in two parts


The below elements are coming from a database table.

<div id="some_content">
  <a href="#">Data1</a><br>
  <a href="#">Data2</a><br>
  <a href="#">Data3</a><br>
  <a href="#">Data4</a><br>
  <a href="#">Data5</a><br>
</div>

There might a case when there are more than 50 elements, and if that happens, I don't want my page window to overflow (and scroll).

I only want two columns.

It should adjust the number of rows into one / two columns automatically.

Whenever there are more than 10 elements, I want two columns in the web page. Now there can be n-number of a elements.

If there are 50, then it should automatically adjust 25 in each column, and if 30, then 15 in each.


Responsive 2 Column Divs Not Working


We've tried every Responsive 2 Column Divs we could find, but they're not working. I've included some links below to ones we have tried. Any idea why they're not working? We just want to divs that will stack when the screen is made smaller. Thanks in advance!

http://jsfiddle.net/fkp8d/1/

<div class="group">
<div class="left">
    <p>tates enim officiis. Iste repudiandae illo nulla sed nam a ratione iure?</p>
</div>
  <div class="right">
    <img src="http://lorempixel.com/640/480/" alt="" />
  </div>
 </div>

<style>
.left {
    float: left;
    width: 50%;
}
.right {
    float: right;
    width: 50%;
}
img {
    max-width: 100%;
    height: auto;
}
.group:after {
    content:"";
    display: table;
    clear: both;
}
@media screen and (max-width: 480px) {
    .left, .right {
        float: none;
        width: auto;
    }
  } </style>

Also: http://jsfiddle.net/8YLXy/


Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in. (php mysql) [duplicate]


Please help. I get this errors :

Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in

This is my php file

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

$image = $_POST['image'];
         $name = $_POST['name'];

require_once('dbConnect.php');

$sql ="SELECT id FROM uploads ORDER BY id ASC";

$res = mysqli_query($con,$sql);

$id = 0;

while($row = mysqli_fetch_array($res)){
$id = $row['id'];
}

$path = "uploads/$id.png";

$actualpath = "http://www.fikri.hol.es/$path";

$sql = "INSERT INTO uploads (image,name) VALUES ('$actualpath','$name')";

if(mysqli_query($con,$sql)){
file_put_contents($path,base64_decode($image));
echo "Successfully Uploaded";
}

mysqli_close($con);
}else{
echo "Error";
}

?>

Thanks


add multi columns in many-to-many relation using fk-relation in xcrud


I have three tables :

orders :

id_order PK int
id_client
.
.
.
etc ...

Products :

id_product PK int
product_name  varchar(255)
.
.
.
etc ...

orders_products

id  PK int
id_order  FK int
id_product   FK int
quantity    int
discount    float

and Im using Xcrud as a crud framework based.

this is my code :

    $xcrud = Xcrud::get_instance();
    $xcrud->table('orders');
    $xcrud->fk_relation('Products','id_order','orders_products','id_order','id_product','products', 'id_product','product_name');
  • So each order has multi products
  • And each product has a quantity

When I go to add an order it only shows me a multiselect field of products and it's inserting products find in the orders_products table.

but I want to add for each product a quantity.

How can I do that using xcrud ?


Delete text in input field not working


I have a plus/minus button where you can plug in only numerical values in the input field or click the plus/minus button to select a value. When you go click inside the text field and try to delete or backspace the number it is not working. Here is the html and a link to my fiddle. Update: The delete key works in Chrome but not in Firefox. https://jsfiddle.net/714dxayk/5/

<span class="form-title">Quantity</span>
<form id='myform' method='POST' action='#' class="numbo">
<input type='button' value='-' class='qtyminus' field='quantity' style="font-weight: bold; font-size:18px;" />
<input type='text' name='quantity' value='1' class='qty' style="margin-bottom: 0px !important" onkeypress='return event.charCode >= 48 && event.charCode <= 57'/>
<input type='button' value='+' class='qtyplus' field='quantity' style="font-weight: bold; font-size:18px;" />
</form>

Loading image multiple times VS HTML elements?


I have a loop where a div element is created and inside that div an image gets printed. This loop goes on 14 times. So the same image and div gets printed 14 times. The image is 14KB. I have the ability to transform that image into an HTML element using divs, P tags, and CSS. Which is more efficient loading the same image 14 times or loading multiple HTML elements 14 times? If the browser caches that image, it wouldn't need to be downloaded 14 times because it's already downloaded. Would it still be more efficient to create that image using HTML elements and CSS? I am also working with PHP and MySQL, so if I switch to HTML the P tag that has to be printed out must be retrieved text from my database. So inside that loop that text must be retrieved 14 times as well if I switch to HTML.

Which is more efficient in my situation? Sticking to the image or changing the image into HTML elements with database retrieving?


Javascript window.close() and window.stop() Logical or Technical?


maybe my question is very simple but i am new at HTML and JavaScript.

I want to learn window.close() and window.stop() ,

so i tried it in a simple HTML page. But there is a problem, i'am using my function in a tag. and window.stop() does not stop the operation. I want to stop the redirection if confirm dialog not true. How can i fix this problem?

HTML FILE:

<html>
<head>
    <title> My page </title>    
    <script src="my_javascript_file.js"></script>   
</head>
<body>

    <a href = "http://www.google.com" onclick="whereAreYouGoing()">Go</a>

</body>
</html>

my_javascript_file.js:

function whereAreYouGoing(){

    var exit = confirm("Are You Want to Sure to Leave?");

    if(exit){
        window.close();
    }

    else
        window.stop();

}

Creating an interactive button/text adventure [on hold]


I'm looking to create something to similar to this, where you can select a button and have a dropdown of text. I've noticed a couple things to implement that I'm wondering how to do:

  • Button revealing text: I think jQuery's slideDown() could be used for this.
  • Progress bar on right side: This one I have no idea, some sort of color changer that updates on button click perhaps?
  • Autoscroll down on button click: is this perhaps one of scrollTo() or scrollIntoView()?
  • Fixed Choice: Clicking a button means you can't change your decision. This one I also have no idea, but perhaps a way to disable clicking the previous button after a selection is made?

Any advice or feedback on the approaches I'm taking for any of the four main parts would be helpful. Thanks!


update sql table current row


Complete noob alert! I need to store a largish set of data fields (480) for each of many devices i am measuring. Each field is a Decimal(8,5). First, is this an unreasonably large table? I have no experience really, so if it is unmanageable, I might start thinking of an alternative storage method.

Right now, I am creating a new row using INSERT, then trying to put the 480 data values in to the new row using UPDATE (in a loop). Currently each UPDATE is overwriting the entire column. How do I specify only to modify the last row? For example, with a table ("magnitude") having columns "id", "field1", "field2",...:

sql UPDATE magnitude SET field1 = 3.14; this modifies the entire "field1" column.

Was trying to do something like: sql UPDATE magnitude SET field1 = 3.14 WHERE id = MAX(id)

Obviously I am a complete noob. Just trying to get this one thing working and move on... Did look around a lot but can't find a solution. Any help appreciated.


How to block website from moving to other <section> element and allow it only on menu link click action in jQuery


Ok, so I have a website which looks like that: <ul> <li> <a class="page-scroll" href="#network">Network</a> </li> <li> <a class="page-scroll" href="#mission">Mission</a> </li> <li> <a class="page-scroll" href="#team">Team</a> </li> </ul> <section id="network"> CONTENT </section> <section id="mission"> CONTENT </section> <section id="team"> CONTENT </section> Website uses jQuery and Bootstrap to operate and is an "one-page" site. I want the sections to block moving further and move to the next part (next section element) only when user clicks the link in the menu. I have already had different approaches to the problem using jQuery, but my solution didn't seem to be very dynamic (it worked only for the first section, and wasn't changing the variables' values to allow moving further). Could you help me with any solution?

Jquery Script To collect Distance from a Database after user enters Pickup Point and Dropoff Point in a Form


Hie Guys

I have a form here like this:

<label for="pickup">Pickup Point</label>
<input type="text" name="from" id="from" />

<label for="dropoff">Dropoff Point</label>
<input type="text" name="destination" id="destination" />

<label for="distance">Distance</label>
<input type="text" name="distance" id="distance" disabled="disabled" />

I also have a database table which is called tbl_distances which stores indexed distances between two cities like this:

Pickup_Point     Dropoff_Point       Distance

 Blantyre          Harare             800

So what i want is a script that does a live search in the table to find distance when a user enters pickup point and drop off point in the input fields. For example if one types Blantyre as pickup point and Harare as dropoff point then the distance field should be automatically field with 800.

I am an amateur at jquery. Thanks in advance.


Mysql - The Best Way to Manage and Find Point in Latitude Longitude Inside a Polygon


What is the best way to manage latitude and longitude database in MySQL? I have very big database contain many location of restaurant, and I need to find what are restaurants inside the polygon (the polygon especially rectangle)?

For example I have database:

Row 1: Latitude (-6.8374651) Longitude (107.56283)

Row 2: Latitude (-6.947151) Longitude (108.261528)

Row 3: Latitude (-9.125182) Longitude (115.121831)

etc

I have rectangle with North West Point: (-6.4516,107.19281) and South East Point: (-6.81726,106.19271)

My question is how can I find the list of restaurants inside this rectangle in the most efficient way? I have arround 50 million rows of data and will always increase everyday

PS. I have created an index for latitude and longitude and try to query it like this:

SELECT * FROM location WHERE latitude<=-6.4516 AND latitude>=-6.81726 AND longitude<=107.19281 AND longitude>=106.19271

But the MySQL keep searching it to entire table and makes the query become so slow

Thanks


Why are favicons cached longer?


I would like to know why favicons, unlike images and other resources are stored far longer in cache and seem to be very persistent as well. I'm using Google Chrome, so the question aims this browser, but also browsers in general as I observed this behavior in other browsers, too.

This question (related, not a duplicate) targets the "how to delete them" question. However, I want to understand why favicons seem to be treated so distinctively, whereas my interest in deleting them is rather secondary to irrelevant.

As a web developer, I can simply apply favicon.ico?2 and get a "fresh" one. And the responsibility lies in the provider of an application rather than in the user managing his own cache (or "petting" my application as I like to call it). So this is not my main question.


Why do favicons seem to be more persistent than other resources?


PDO execute() will not accept anything passed to it [on hold]


Thanks in advance. I have tried and tried every option I have searched for and doing this in everyway I know to try. I have a simple execute() that is passed a simple array. It will not accept the parameters. Please help.

Working Example:

$admin->query("INSERT INTO `testtable` (name) VALUES (:name)");
$admin->bind(':name','Alfred');
$admin->execute();

NON Working Example:

$admin->query("INSERT INTO `testtable` (name) VALUES (:name)");
$admin->execute(array("name" => "Alfred"));

Once again, this is an extremely simplified example of what I am trying to do. execute() will not accept any parameter I pass it in any way, array or otherwise.

I had seen something in passing through about a setting that was off that allowed passing of variables through execute(). I am not sure I just don't get why its not working.

Thanks!


I got it. My fault. Once again, overlooking the obvious withing my class....

How to create a table using user input with Javascript/JQuery


I'm trying to create a table using a user input prompt which is saved into a variable. I want to be able to take that variable and make it an even number of rows and columns. So for example if the user input is 5, I want to make a 5x5 table.

I'm able to take the user's input and make the correct amount of rows, but I'm having trouble with the columns.

Could anyone offer some insight on my code? My js fiddle is below:

$(document).ready(function() {
    //cache all jquery objects in variables
    var $button = $('.button');
    var $wrapper = $('.wrapper');
    var $bones = $('.bones');
    var $rows = $('.rows');

    $button.click(function() {

        //prompt user for input on table size
        var inp = prompt("Enter a number");

        for (var i = 0; i < inp; i++) {
            $bones.append("<tr class='rows'></tr>");
            $rows.append("<td class='block'></td>");
        };
    });

});

https://jsfiddle.net/81zv9zjs/


To delete multiple check boxes


I am able to delete only single checkbox at a time, but i need to delete multiple check boxes, below are my controller and html delete button div. controller app.controller('',function(){ $scope.delete = function(type) { //$scope.action = 'delete'; console.log(" inside..delete======="+type) var tab = deleteTab(type); console.log("tab is------------>"+tab); var node = $('#'+tab).find("input[type=checkbox]:checked").eq(0); console.log('node.length'+ node.length) if(node.length){ node = $('#'+tab).find("input[type=checkbox]:checked").eq(0).parents("tr").find("td"); var id = $('#'+tab).find("input[type=checkbox]:checked").eq(0).parents("tr").data("id"); console.log(" inside..delete"+id) myService.delete({action:'delete',type:type, id:id},function() { console.log(" inside.2.delete"); if(id !==undefined){ console.log("please uncheck it..."); $("#"+tab+id).prop("checked", false); //alert(tab.split("#")[1]); $scope.enable_disable(tab); } $scope.get(type); $scope.getMapping(); }); } $scope.flag = true; }; }); template <button id="deleteme1" class="btn btn-primary btn-xs" data-title="Edit" data-toggle="modal" data-target="#" ng-click="deleteOrg('organization')" disabled> <span class="glyphicon glyphicon-trash"></span> </button>

Duplicate values on elements in different media queries


I'm trying to clean up my huge media queries and I've removed every change in element values that are the same as the default element values so that this will show up instead.

My question is what choices I have when the duplicate values are stored in individual media queries?

Here is an example:

@media only screen and (min-width: 480px) and (max-width: 767px) {
.fa.fa-check
{
    font-size: 3em;
    border-radius: 100px;
    height: 100px;
    line-height: 100px;
    width: 100px;
}
.fa.fa-shopping-cart
{
    font-size: 3em;
    border-radius: 100px;
    height: 100px;
    line-height: 100px;
    width: 100px;
}
.fa.fa-user
{
    font-size: 3em;
    border-radius: 100px;
    height: 100px;
    line-height: 100px;
    width: 100px;
}

@media only screen and (max-width: 479px) {
.fa.fa-check
{
    font-size: 3em;
    border-radius: 100px;
    height: 100px;
    line-height: 100px;
    width: 100px;
}
.fa.fa-shopping-cart
{
    font-size: 3em;
    border-radius: 100px;
    height: 100px;
    line-height: 100px;
    width: 100px;
}
.fa.fa-user
{
    font-size: 3em;
    border-radius: 100px;
    height: 100px;
    line-height: 100px;
    width: 100px;
}

I have lots of changes in element values that aren't duplicates inside of the media queries as well, so I can't combine them all together. Are there any other choices?


Div moves when a browser window is rezised


I looked at some other answered questions about this but just none helped.

Here is how I want it too look and when I am in full screen / https://gyazo.com/64ba88bd3b777eb9ac248cba58ad4959

Here is when I minimize/maximize the window - https://gyazo.com/364a876f9ea914ec0601f8df1a1e478a

My index/HTML file - https://www.mediafire.com/?md59u10c20emy21

My CSS file - https://www.mediafire.com/?nhcbp14447sfll9

The files is in another format which is .hbs don't worry about that. Game.hbs is the index layout.hbs is the CSS. The ytpromo CSS is the yt promotion box, you can experiment with that.


How do I do a picture / text upload to go into a bootstrap thumbnail / modal?


Project site: http://www.williambaum.comlu.com/Ermias/index.html

This question might be a bit hard to explain but I'll try my best.

I'm making a bootstrap site for my friend (and learning from it) and trying to make an upload section. This site is for his photoshopped art and my goal is that he could upload a photo and the required text and it be put into the thumbnail and modal. I want it to create a new thumbnail and modal when he uploads and it to appear as a thumbnail (like on the homepage) on the 'pictures' page. How should I go about doing this and could you point me towards some documentation for it.

Thanks in advance - Will

PS: If you need clarification please ask

PPS: Open to constructive criticism on my site

http://www.williambaum.comlu.com/Ermias/index.html


Columns with same height and a background color with Bootstrap


I try to have two columns in bootstrap with the same height. This is ok, it works. But now I try to have background color for these columns. It works, but I can't keep white margins between them. In blue the space I need in white. :/

In blue the space I need in white. :/

I have this code (with bootstrap 3)

@media only screen and (min-width : 768px) {
  .is-table-row {
    display: table;
  }
  .is-table-row [class*="col-"] {
    float: none;
    display: table-cell;
    vertical-align: top;
  }
}
.red {
  background: red;
}
.green {
  background: #343335;
}
<div class="row is-table-row">
  <div class="col-md-8 red"> text </div>
  <div class="col-md-4 green"> text </div>
</div>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

Can you help me please ?


mercredi 29 juin 2016

How to place a text inside the top-left corner border of div


I've been going through lot of articles about placing a label/legend/text on the border of a div. I've a lot of div where I want to show the different labels exactly like the image shown below: As I can see in the w3school they say to have a field set and get declare legend to display the texts, but its not working out for me. I have a set of jquery codes which appends the html with the labels : $('.menu').hover(function () { $(this).css('border', 'solid 2px #8080ff'); $(this).find('.divlabel').show(); }, function () { $(this).css('border', 'none'); $(this).find('.divlabel').hide(); }); .divlabel { float: left; top: 5px; right: 10px; padding: 0px; background: #fff; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="menu"> <div class="divlabel">Menu</div> <ul class="mainmenu"> <li>...</li> <li>...</li> </ul> </div> <div> Its not working as desired, please help out guys with this css.

html - How to dynamic change base64 image


I am try to transmit live video stream to server and show on web page. Well, I successfully show my image on the html page, but my image is freeze. The image will change only when I press refresh button on the browser. How to make it show like a video stream? Following is my snippet:

var socket = io();

socket.on('liveCam', function(url) {

  var old_url = '';
  var diff = strcmp(url , old_url);
  old_url = url;

  console.log('diff =', diff);
  var src_url = 'data:image/jpeg;base64,' + url;	
  setInterval(setimagesrc(src_url), 50);

});

function setimagesrc(uurl){
  $('#image').attr('src', uurl);
}

function strcmp ( str1, str2 ) {
  return str1 == str2 ? 1 : 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>

<h1>streaming</h1>
<p>
  <img src="" id="image">
</p>

Thanks for your patience!


PDO were rows affected during execute statement


I have found many ways to use the exec statement for PDO, but I'm not sure it helps me. My understanding is that I have to use the execute() function for prepared statements. I am updating a row with data from user input, so I would like to use a prepared statement instead of the query() call.

My code is as follows:

$dbh = buildDBConnector(); 
$sql = "UPDATE tb_users 
    SET authState=1
    WHERE id = ? AND authPass = ?";
$q = $dbh->prepare($sql);
$f = $q->execute(array($id,$authPass));
if($f){
    echo '<br />Success<br />';
}else{
    echo '<br />Failure<br />';
}

The issue is that the query itself is error free and executes fine, so there is no failure to store in $f. However, I need to know if it actually found the row to update, then successfully updated it. In other words, I need the affected rows. When googling and such, it keeps coming to the exec statement, but from my understanding, exec isn't for prepared statements? Any suggestions?


How can I force a timestamp update in Laravel 5.1 when performing a raw INSERT ... ON DUPLICATE KEY UPDATE?


I use DB::statement($query, $params) to perform batch inserts into my database with the INSERT ... ON DUPLICATE KEY UPDATE syntax. However, when I do, neither the 'updated_at' or 'created_at' fields are updated. I am wondering if there is a way to force the correct field to be updated in the raw query?

Context: I am using Laravel 5.1 and have created the relevant tables using the $table->timestamps() feature. In addition to doing raw insert/updates, I also query these tables using Eloquent so I cannot implement a solution that would disable Eloquent's auto-updates.

Concerns: I am not clear at the moment how times are generated when Eloquent automatically updates a timestamp field - I assume it triggers an auto-update in the database with reference to the database's reference clock? I would like to mimic however Eloquent is going about it so that I don't end up with times using two different clocks as sources.

I am very new to using raw MySQL queries so appreciate in advance any advice/insight folks are able to offer! Thank you!


how can i call field on sql2 ? with the foreign key $rt? please help me [duplicate]


this code

<?php
            $bulan_sekarang = date("m");
            $tahun_sekarang = date("Y");
            $sql = "SELECT * FROM tbl_rt";
            $count = mysqli_query($con,$sql);
            while($row = mysqli_fetch_array($count,MYSQLI_ASSOC)){
              $rt = $row['rt'];
              $id_rt = $row['id_rt'];
              echo '<tr><th>'.$rt.'</th>';
              $sql2 = "SELECT no_rt,tgl_pemohon,SUM(jumlah) AS jum FROM tbl_dataklg WHERE no_rt=$rt AND jk=1 AND DATE_FORMAT(tgl_pemohon,'%m')=$bulan_sekarang and DATE_FORMAT(tgl_pemohon,'%Y')=$tahun_sekarang";
              $hasil = $con->query($sql2);
              $hitung2 = $hasil->fetch_assoc();
              echo '<th>'.$hitung2['jum'].'</th>';
              echo '</tr>';
            }

Why i couldnt put fetch assoc on while? how can i call field on tbl_dataklg?


Iterate over an array's elements to perfrom queries using Laravel Eloquent advanced WHERE clauses


I have an array (arr) with n elements, n = 1 or 2, and a table in database called employees that contains two fields (name and surname)

I want to perform the following query using Eloquent (and, possibly, some kind of iteration ?), in order to implement an "instant search" functionality:

select * from employees
where (name LIKE '%arr[0]%' AND surname LIKE '%arr[1]%')
OR
where (name LIKE '%arr[1]%' AND surname LIKE '%arr[0]%')

Any help appreciated

Thank you

EDIT: To state my question more clearly, in case there is only one element in the arr I would like to perform the following query:

select * from employees
where (name LIKE '%arr[0]%' AND surname LIKE '%arr[0]%')

that is, to look for the given arr element in either name or surname fields.


laravel database connection returns undefined index error


I am developing a project using laravel 4 framework. In my database.php file I get the following error:

  Undefined index: driver 

And my connection is as following:

    $connections = array(
            'mysql' => array(
                'read' => array(
                    'host'      => 'localhost',
                    'driver'    => 'mysql',
                    'database'  => 'app_system',
                    'username'  => 'root',
                    'password'  => 'root',
                    'charset'   => 'utf8',
                    'collation' => 'utf8_unicode_ci',
                    'prefix'    => '',
                ),
                'write' => array(
                    'host'      => 'localhost',
                    'driver'    => 'mysql',
                    'database'  => 'app_system',
                    'username'  => 'root',
                    'password'  => 'root',
                    'charset'   => 'utf8',
                    'collation' => 'utf8_unicode_ci',
                    'prefix'    => '',
                ),
            ),

            'mysql2' => array(
                'read' => array(
                    'host'  => 'localhost',
                    'driver'    => 'mysql',
                    'database'  => 'app_userdata',
                    'username'  => 'root',
                    'password'  => 'root',
                    'charset'   => 'utf8',
                    'collation' => 'utf8_unicode_ci',
                    'prefix'    => '',                      
                ),
                'write' => array(
                    'host'  => 'localhost',
                    'driver'    => 'mysql',
                    'database'  => 'app_userdata',
                    'username'  => 'root',
                    'password'  => 'root',
                    'charset'   => 'utf8',
                    'collation' => 'utf8_unicode_ci',
                    'prefix'    => '',                      
                ),
            )
        );

I am also using environments in order to set different mysql connections. What is wrong with the code?


How to access mysql database using JSP scriplets?


I am trying to access the database and retrieve a attribute 'sno' from it. I have hidden the value in a input field using the following code. <input type="hidden" value="<%= request.getParameter("well_name") %>" name="well_name" id="well_name"> The above code is put in some other page when the user submits, it is passed to next page and here I am trying to access the database like <sql:setDataSource var="snapshot" driver="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost/kn" user="root" password="password"/> <p><%= request.getParameter("well_name") %></p> <sql:query dataSource="${snapshot}" var="result"> SELECT sno FROM well_name WHERE name = '<%= request.getParameter("well_name") %>' ; </sql:query> <c:forEach var="row" items="${result.rows}"> <p><c:out value="${row.sno}"/></p> </c:forEach> I am able to access the database when I provide a value which is defined like name = 'value'. I am not able to access like these please help me out. Thanks in Advance.

Qt SQL MYSQL Driver not loaded in shipping


I know this question is asked 500 times a day but I cant help myself.

I have a QT Program wich runs really fine in production, but when it comes to shipping It cant find the sql driver.

I read that the libmysql.dll have to be in ./sqldrivers but its not working anyways.

Here are my Files for the project:

21.06.2016  15:00    <DIR>          .
21.06.2016  14:51    <DIR>          ..
21.06.2016  14:51           230.400 bass.dll
21.06.2016  14:51            36.864 basscd.dll
21.06.2016  14:51           203.776 Qt5Sql.dll
21.06.2016  14:51         5.664.256 Qt5Core.dll
21.06.2016  14:51         6.019.072 Qt5Gui.dll
21.06.2016  14:51         5.295.104 libmysql.dll
21.06.2016  14:51         5.472.768 Qt5Widgets.dll
21.06.2016  14:51           420.352 test.exe
21.06.2016  14:51           635.040 msvcp140.dll
21.06.2016  14:51           332.968 concrt140.dll
21.06.2016  14:51         5.624.984 mfc140.dll
21.06.2016  14:51           105.120 mfcm140.dll
21.06.2016  14:51           552.608 vcamp140.dll
21.06.2016  14:51           390.320 vccorlib140.dll
21.06.2016  14:51           205.984 vcomp140.dll
21.06.2016  14:51            88.752 vcruntime140.dll
21.06.2016  14:51           213.680 VSCover140.dll
21.06.2016  14:51           274.600 VSPerf140.dll
21.06.2016  14:51         1.020.928 qwindows.dll
21.06.2016  14:52    <DIR>          platforms
21.06.2016  14:56    <DIR>          sqldrivers
              19 Datei(en),     32.787.576 Bytes
               4 Verzeichnis(se),     45.801.472 Bytes frei

/sqldrivers
21.06.2016  14:56    <DIR>          .
21.06.2016  15:00    <DIR>          ..
26.02.2015  00:27         5.191.680 libmysql.dll
               1 Datei(en),      5.191.680 Bytes
               2 Verzeichnis(se),     45.801.472 Bytes frei

/platforms
21.06.2016  14:52    <DIR>          .
21.06.2016  15:00    <DIR>          ..
21.06.2016  14:52         1.249.280 qwindows.dll
21.06.2016  14:51            35.840 qminimal.dll
21.06.2016  14:51            99.840 qminimald.dll
21.06.2016  14:51         2.920.448 qminimald.pdb
21.06.2016  14:51           664.064 qoffscreen.dll
21.06.2016  14:52         1.304.576 qoffscreend.dll
21.06.2016  14:52         5.386.240 qoffscreend.pdb
21.06.2016  14:52         2.620.416 qwindowsd.dll
21.06.2016  14:52        12.578.816 qwindowsd.pdb
               9 Datei(en),     26.859.520 Bytes
               2 Verzeichnis(se),     45.801.472 Bytes frei

Where is the Problem here?

greetings Dropye


Editor not Replacing Text Area and Not Displaying on Page


I ran sample file (samples/replacebyclass.html) in several browsers on nmy development machine and the result was a large blank space following the label "Editor 1:"

I changed the tag to point to the ckeditor.js in my production website. Then I reran the html page and got the expected and desired result.

I have tried copying the ckeditor.js, config.js, and contents.css doen from my website to my development machine but that had no discernible effect on the results.

There must be something in the ckeditor folder on my development machine that is different, but I cannot seem to identify it.

I sure do not want to move my ckeditor folder from my development machine up to the website (where ckeditor is working fine) until I can get the devel;opment machine to reliably render the editor like it is beinbg rendered on the website.

The environment is IIS and Windows server 2008 on the website and IIS Express on the development machine.

I really would like some suggestions on how to make this work on the development machine *Windows 10).


How to vertically center content of child divs inside parent div in a fluid layout


I have a div which contains two child divs, and they are intended to be part of fluid layout, so I can't set a fixed size for them in px.

There are two goals here:

  1. Align the two child divs horizontally, which I have achieved using float: left and float: right respectively.

  2. Vertically center the text (within the child divs) relative to the parent div. The text is short and takes a single line by design.

What I have now: http://jsfiddle.net/yX3p9/

Apparently, the two child divs do not take the full height of the parent div, and therefore their text are not vertically centered relative to the parent div.

Conceptually, to achieve the goals above, we can either make the child divs vertically centered within the parent div, or we can make the child divs take the full height of the parent div. What is the robust way to do so?

*Browser support: IE 9+ and other usual modern browsers.


Changed MySQL root and now cannot log back in


I am running mysql 5.6 and tried to change the root password following these instructions: https://dev.mysql.com/doc/refman/5.6/en/resetting-permissions.html

I followed the generic instructions at the bottom of the page titled: B.5.3.2.3 Resetting the Root Password: Generic Instructions

I skipped stopping the server and executing the FLUSH PRIVILEGES command. I executed the following command though:mysql> SET PASSWORD FOR 'root'@'localhost' = PASSWORD('MyNewPass');

However, now when I try to log in I receive this error message:ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)

Does anyone know where I went wrong?

Thank-you for reading this.

UPDATE:I found this post helpful - how to log in to mysql and query the database from linux terminal

One of the answers works for me where specifying the password directly after the -p instead of waiting for the password prompt. Something maybe wrong with my operating system.


How to display data count per category mysql subquery


i have table like bellow

tbl=province

id_province | province
----------------------
01      Province1
02      Province2
03      Province3
...
...

tbl=grade
id_grade | grade
-----------------
A      elementary       
B      junior
C      senior

tbl.transaction
-----------------------------
code    | id_province   | id_grade
--------------------------------
t1          01             A
t2          01             A
t3          01             A
t4          02             A
t5          03             C
t6          02             B
t7          03             A

how i can query if i want to display data like bellow

id_province | province  | count of grade A  | count of grade B | count of grade C
---------------------------------------------------------------------------------------------
01             Province1        3                    0              0
02             Province2        1                    1              0
03             Province3        1                    0              1   

I have try to make query using subquery like bellow, but it's not work :

select id_province,(select count(*) from transaction where id_grade='A') as count of grade A,(select count(*) from transaction where id_grade='B') as count of grade B,
    (select count(*) from transaction where id_grade='C') as count of grade C group by id_province

moreover, query above show data like bellow :(

id_province | province  | count of grade A  | count of grade B | count of grade C
---------------------------------------------------------------------------------------------
01             Province1        3                    0              0
02             Province2        3                    0              0
03             Province3        3                    0              0 

Any idea how to solve this ?


SVG not showing in mobile device


I made a svg code for my web. OPZET India this is my website. my problem is that my svg is not showing in mobile device. Please find the mistake. Here is my Snippet. .st0 { font-family:'Chiller' } .st1 { font-size:150px } .st3 { fill:none; stroke:#000; stroke-width:2; stroke-miterlimit:10 } .st0 { stroke-dasharray:800; stroke-dashoffset:0; -webkit-animation:dash 2s linear forwards; -moz-animation:dash 2s linear forwards; animation:dash 2s linear forwards; opacity:0 } @-webkit-keyframes dash { from { stroke-dashoffset:800; } to { stroke-dashoffset:1; opacity:1; } } @-moz-keyframes dash { from { stroke-dashoffset:800; } to { stroke-dashoffset:1; opacity:1; } } @keyframes dash { from { stroke-dashoffset:800; } to { stroke-dashoffset:1; opacity:1; } } .st1 { stroke-dasharray:800; stroke-dashoffset:0; -webkit-animation:dash 2s linear forwards; -moz-animation:dash 2s linear forwards; animation:dash 2s linear forwards; -webkit-animation-delay:1.6s; -moz-animation-delay:1.6s; animation-delay:1.6s; } <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="873px" height="200px" viewBox="0 0 873 220" style="enable-background:new 0 0 873 220; padding-left:180;" xml:space="preserve"> <g id="text" width="100%" style="text-align:center;"> <text transform="matrix(1.0401 0 0 1 17 154.4297)" class="st3 st0 st1" style="font-size: 150px; font-family: 'Mistral', sans-serif;">Opzet India</text> </g> </svg> <embed src="text.svg" width="100%"> this is my html code. Please solve my problem. Also this is not responvie.

How to make my users-friends-groups-messages database design more efficient? [on hold]


I created a database design but the tables messages and gp_messages are redundant.

in single user chat i can store message in message table as there is 1 sender and 1 receiver

but in group chat where there is 1 sender and many receivers it stores data redundantly in message copy table with same message_id

For example in a group chat there will be a common message_id(for each user in group) that will keep on repeating in the message copy table

//UPDATE : i removed the primary key in message copy table cause cannot store redundant messages

also i have 2 tables to store messaged i want only one table to make my DB design more efficient

I want to combine those. Any tips on how I can do that?

This is a screenshot of the scheme:

enter image description here A blue line in the image is a foreign key.


Using PowerPoint, create a DOM Tree that accurately represents JavaScript code


I am very new to JavaScript and I have an assignment I need some directional help on. First we were to create a code:

<html> 
<header> 
<title>Week 2</title> 
</header> 

<body> 
<h1>JavaScript Greeting:</h1> 

<script language="JavaScript"> 
var myDate = new Date(); 


if ( myDate.getHours() < 12 )  
{ 
    document.write("Good Morning!"); 
} 
else  
if ( myDate.getHours() >= 12 && myDate.getHours() <= 17 ) 
{ 
    document.write("Good Afternoon!"); 
} 
else  
if ( myDate.getHours() > 17 && myDate.getHours() <= 24 ) 
{ 
    document.write("Good Evening!"); 
} 

document.write("<br/><br/> The hour is: ") 
document.write( myDate.getHours() ); 

</script> 

</body> 
</html>

Our next assignment is to take the code we created and use PowerPoint to create a DOM Tree that accurately represents the code above. I am confused at how to proceed and cannot find any examples online on how to turn JavaScript into a DOM tree. I found how to inspect my elements in Chrome, however the code is identical to the code above. Can anyone offer any guidance or examples? It would be greatly appreciated.


How can i change `keyword` color on runtime in `textarea` or `textbox`? Javascript


I have a textarea i want that when i type keyword like var and press SPACEbutton then it's color will be blue on runtime.I defind many keyword my self.Not on button click its will be on runtime.How can i do this?Thanks.And i also want this textarea text in codebehind.I'm working in ASP.NET C# environment.Same like SQL-QUERY-EDITOR. Here is my code :

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" runat="server">
var codeInput = document.getElementsByTagName("textarea");
var keywords = new Array("var", "if");
function checkHighlight(){
var codeInput1 = codeInput[0].value;
if(codeInput1 === keywords[0]){
 keywords[0].indexOf(codeInput1).className = "JSfunctions";
}
}
</script>
<style type="text/css" runat="server">
    #JScodeinputbox{font-family:Arial;}
  #JScodeoutputbox{}
    .JSfunctions{color:blue;}
</style>
 </head>
 <body>
 <form id="form1" runat="server">
 <div>
 <textarea id="JScodeinputbox" wrap="logical" rows="30" cols="70" onkeyup="checkHighlight();"></textarea>
</div>
</form>
</body>
</html>

URL repeats itself, leading to a 404 error


My page will redirect the user to another page which will handle all the updating information. I got the redirect in itself working, problem is, the URL isnt what i expect it to be, leading to a 404 error. Let me try to exemplify.

The user clicks a button, redirecting him to "test.com/main/update.php". But my file is in "test.com/test/RazorFinger/update_test.php". so it ends up being something like this:

<FORM name=form id="form" action="test.com/main/update.php?area=<?=$GetArea?>&etc..." method="POST" target='_blank'>

So my main URL is this:

http://test.com/teste/RazorFinger/update_test.php?area=TestArea&proj_id=1234&task_uid=1

And the redirected url is basically:

http://test.com/teste/RazorFinger/test.com/main/update.php?area=TestArea&etc..etc..etc..

The question might be a bit complicated because i'm using fake URLs as example, but basically, i can't get out of "test.com/test" and into "test.com/main", and that leads me to a 404 error. So what's wrong?


No results when executing MySQL query


I'm writing a simple db infrastructure. select function suppose to perform a simple query and returns a result set.

For some reason, I am not getting any results back.

What should I do in order to fix my code?

protected $connection;

public function connect() {    
        // Try and connect to the database
        if(!isset($this -> connection)) {
            // Load configuration as an array. Use the actual location of your configuration file
            $config = parse_ini_file('config.ini');
            $this -> connection = new mysqli('localhost',$config['username'],$config['password'],$config['dbname']);
        }

        // If connection was not successful, handle the error
        if($this -> connection === false) {
            // Handle error - notify administrator, log to a file, show an error screen, etc.                       
            return false;
        }

        return $this -> connection;
    }

public function select($query) {        
    $connection = $this -> connect();       
    $stmt = $connection->prepare($query);       
    $stmt->execute();
    $stmt->store_result();
    $result = $stmt->get_result();      
    $rows = array();

    if($result === false) {                 
        return false;
    }

    while ($row = $result -> fetch_assoc()) {                       
        $rows[] = $row;
    }

    $stmt->free_result();
    $stmt->close();
    $connection->next_result();
    return $rows;
}

Execution:

$result = $db -> select('SELECT 1');
echo $result;

Javascript Radio all placed in same position


I am getting a bunch of questions from Web API and getting the JSON question and answers and i want to dynamically create a list of possible answers with radio buttons.

The problem im having is that all of the radio buttons are being placed in the same position, but the text is all in the correct position and i cant understand why??

Can anyone see anywhere where im going wrong? The buttons are all being displayed just all ontop of each other...

function questionButtons() {
        document.getElementById("quelist").style.visibility = "visible";
        var table = document.getElementById("qtnlist");
        table.style.visibility = "visible";
        table.innerHTML = "";
        for (var i = 0; i < 10; i++) {
            var row = table.insertRow(0);
            var row2 = table.insertRow(1);
            var row3 = table.insertRow(2);
            var row4 = table.insertRow(3);

            var cell2 = row2.insertCell(0);
            var cell3 = row3.insertCell(0);
            var cell4 = row4.insertCell(0);

            var cell1 = row.insertCell(0);
            var cell2 = row.insertCell(1);

            cell1.innerHTML = "<input type='radio' name='" + i + "'  value='" + i + "' >"+"Answer Opt1 JSON";
            cell3.innerHTML = "<input type='radio' name='" + i + "'  value='" + i + "' >" + "Answer Opt2 JSON";
            cell4.innerHTML = "<input type='radio' name='" + i + "'  value='" + i + "' >" + "Answer Opt3 JSON";

        }
    }

Remove class if clicked outside an element


How do I make it so that if I click outside a paragraph element then the background color is removed? Note I want to it to only be able to highlight one 'p' at a time.

$('p').click(function() {
  $('p').removeClass('yellow');
  $(this).addClass('yellow');
});
.yellow {
  background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="row">
    <div class="col-md-12"><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Velit tenetur sequi amet sit dolorem, nulla inventore quo cum ad distinctio aut nesciunt reprehenderit dolorum quidem animi unde aspernatur. Esse, eius!</p>
<p>Deleniti vitae rerum eum saepe eaque tenetur libero, omnis nisi sapiente dicta est repellat, provident placeat quia inventore, at architecto quisquam, pariatur minus quam magni totam praesentium dignissimos. Incidunt, sequi.</p>
<p>Fuga cupiditate consectetur, corporis architecto, doloremque impedit ullam quia praesentium voluptatibus molestiae dolor sint, odio amet atque culpa fugit blanditiis ea nam repellat necessitatibus. Aliquam voluptate fuga quo, omnis mollitia.</p></div>
  </div>
</div>

MySQL and SSL connection failing ERROR 2026 (HY000)


I have a wildcard cert issued from rapidssl, using CN=*.mydomain.com. I have a web server and a mysql db server. The certs are working fine for web site access. Now I want to enable ssl for my app to mysql. I've enabled ssl in the mysql server without issue:

+---------------+---------------------------------+
| Variable_name | Value                           |
+---------------+---------------------------------+
| have_openssl  | YES                             |
| have_ssl      | YES                             |

However, when I try to connect using the client/ssl, I get: ERROR 2026 (HY000): SSL connection error: error:00000001:lib(0):func(0):reason(1)

This appears to be documented here: http://dev.mysql.com/doc/refman/5.5/en/creating-ssl-certs.html

It says I can't use the same CN for the certs. I don't understand how a wildcard cert can be used then. Does that mean I also have to purchase host specific certs just for the mysql connection?

I don't work with SSL very much so I'm finding it difficult figuring out how this is supposed to be set up. Any pointers, even obvious ones, will likely help at this stage.

Running: mysql Ver 15.1 Distrib 5.5.32-MariaDB, for debian-linux-gnu (x86_64) using readline 5.1 ubuntu 12.04


Shape-outside clear both


I am using shape-outside to wrap text around an image. The image floats to the left and the text raps around it perfectly. But when the browser screen gets smaller the text goes over the content that is further down the page.

My goal is to get the text to bump the content below further down the page rather then going over it. I used clear: both; but that did not effect anything. I tried floating the text to the right which solved the initial problem but instead of rapping around the image the text went below the image.

How do I use clear both to have the text rap around the image and not go over the content that is further down on the page? Or is there any other way to achieve this?

Here is my code:

#aboutP {
    position: relative;
    min-height: 300px;
    top: 200px;
    font-size: medium;
    font-family: 'Roboto Mono', sans-serif;
    color: white;
    line-height: 30px;

}

img {
    position: relative;
    width: 300px;
    min-height: 300px;
    float: left;
    top: 200px; 
    margin-right: 20px;
    margin-left: 20px;
    margin-bottom: 20px;
    shape-margin: 15px;
    shape-outside: circle(50%);
    -webkit-shape-outside:
        circle(50%);
    box-sizing: border-box;
}

#title {
    position: relative;
    text-align: center;
    width: 100%;
    height: 1000px;
    top: 200px;
    text-decoration: underline;
    color: white;
    font-family: 'Roboto Mono', sans-serif;
    clear: both;
    }

MySQL query to count 1's occurrence in different columns of feedback table


I want to count all the occurrence of '1' in the columns commskill, abilityskill, interest, presentation, methodology, maintainsclass, punctual, attitude. My table 'Feedback' has following columns:

  • Fid-feedback I'd
  • Tname- teacher name
  • Sname-subject name
  • Studentname- students name
  • Class- class of students
  • Section - section of class
  • commskill- communication skill
  • abilityskill- ability of teaching
  • Presentation - presentation skills of teacher
  • Methodology - method for teaching followed by teacher
  • Interest - interest of students in that teacher's class
  • Punctual - time punctuality of teachers
  • maintainsclass- maintains class discipline
  • attitude - attitude of teacher towards students *tid- teacher 's ID

The values of fid are auto-increment,and grades of all skills are in(1-excellent, 2-good, 3-average,4-below average).

I've already tried this query:

select tname,sname,count(*) as excellent from feedback where commskill=1 or attitude =1 or presentation =1 or abilityskill=1 or interest=1 or punctual =1 or maintainsclass=1 or methodology =1 group by tid;

but the answer showed is unexpected and wrong.


How do I log each users time session on a website where my users are stored in an SQL Database?


Bare with me as I am a noob when it comes to this (in the process of learning :D) I have a basic website made with html/css/php. There is a login page that requires a username and password to access all other areas of the website. The users are stored in a MySQL Database (fields: username, password, store, etc). I need/want to be able to view when the user logged in and how long that particular user was logged in for. I need a simplified way to show this data to someone who would not have access to the cpanel. Sorry for such a vague question, feel free to abuse me and ask for more info and I will reply with what's needed and asked of. EDIT: Sorry I would like to re-phrase what I've asked for as I think having every individual login sessions would make this log quite too much. What I need more accurately would be: How many times they logged in for the month Average duration of logins for the month Example: User A has logged in the website 200 times this month User A session duration each visit on average 5 minutes Sorry for the confusion. The examples above would be the data needed. Thanks in advanced.

mardi 28 juin 2016

vertical text not centering


I have text links vertically on the left/right of my website but they aren't centering on the page. I want the right and left link to vertically center!

CSS

[class*="navigation"] .nav-previous, 
[class*="navigation"] .nav-next { 
  position:fixed;
  top: 50%; bottom: 0;
  transform: translateY(-25%);
  text-align: center;
}
[class*="navigation"] .nav-next { left: 0px; }
[class*="navigation"] .nav-previous { right: 0px;}
[class*="navigation"] .nav-previous a,
[class*="navigation"] .nav-next a {
  position: absolute;
  text-transform: uppercase;
  display: inline-block;
  color: #4d4d4d;
  white-space: nowrap;
  background-color: #fff;
  padding: 15px 15px 10px 15px;
}
[class*="navigation"] .nav-previous a { 
  right: 0;
  transform-origin: top right;
  transform:rotate(-90deg);     
}
[class*="navigation"] .nav-next a { 
  left: 0; 
  transform-origin: top left;
  transform:rotate(90deg); 
}

Output

enter image description here

EDIT: html is generated through Wordpress but the output is

<nav id="nav-BN" class="post-navigation" role="navigation">
   <div class="nav-previous">
      <a rel="prev" href="http://localhost/wordpress/?p=224">
   </div>

   <div class="nav-next">
      <a rel="next" href="http://localhost/wordpress/?p=413">
   </div>
 </nav>

Linking 2 tables in a database


I have a database containing 2 tables - db and details. On clicking a particular field in db column ('Issued to') of any record in the "db" table I want to display the all the fields of the "details" table matching with the particular column "Issued to" in "details" table. In my code the page shows all the matching results of both the tables. I just want the selected (clicked on) record result. The code is as follows- <?php $dbhost = 'localhost'; $dbuser = 'root'; $dbpass = ""; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die('Could not connect: ' . mysql_error()); } $sql = 'SELECT a.`Issued to`, b.Name, b.DOB, b.Discipline, b.Designation, b.PlaceOfPosting, b.PhoneNo, b.Email FROM db a, details b WHERE a.`Issued to` = b.`Issued to`'; mysql_select_db('testdb'); $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not get data: ' . mysql_error()); } while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) { echo "Name:{$row['Name']} <br> ". "Date Of Birth:{$row['DOB']} <br> ". "Discipline:{$row['Discipline']} <br> ". "Designation:{$row['Designation']} <br> ". "Place of Posting:{$row['PlaceOfPosting']} <br> ". "Phone: {$row['PhoneNo']} <br> ". "Email Id: {$row['Email']} <br> ". "--------------------------------<br>"; } mysql_close($conn); ?>

How to create line in the center on scroll with circle in SVG and how to decrease the speed of drawing?


For creating a circle on page scroll with line I am doing like this:

var createShape = document.getElementById("shape");
var length = createShape.getTotalLength();
shape.style.strokeDasharray = length;
shape.style.strokeDashoffset = length;
window.onscroll = function myFunction() {
  var scrollpercent = (document.body.scrollTop) /
      ( document.documentElement.scrollHeight -
       document.documentElement.clientHeight );
  var draw = length * scrollpercent;
  shape.style.strokeDashoffset = length - draw ;
}
.scroll_text {
  font-family: "arial";
  font-size: 25px;
  font-weight: bold;
  color: rgba(241, 71, 71, 1);
  text-align: center;
}
<p class="scroll_text">Please  Scroll</p>
<svg id="mySVG" width="1500px" height="1500px">
  <path d="M 500, 500
           m 20, -190
           a 20,20 0 1,0 1,0
           Q 520 800, 520 800
           a 20,20 0 1,0 1,0
           Q 520 1200, 520 1200
           a 20,20 0 1,0 1,0
           Q 520 1500, 520 1500"
        fill="none" stroke="#000" stroke-width="2px" id="shape"/>           
</svg>

But the problem is my line is intersecting the circle. So, for this i want to fill my circle when my circle finishes up. but for this if I give "fill" then it shows colour. What should I do? I am new to SVG.

Here is the link: http://codepen.io/VishakhaNehe/pen/ezBoGW


Spacing between results PHP Mysql


i have the below code.

im completely new to PHP and mysql

<table align="center" border="0" width="100%">
<tr>
<th>id</th>
    <th>Staff Name</th>
    <th>Date</th>
    <th>Reason</th>
</tr>

<?php

    $startdate = $_SESSION['startdate'];
    $enddate = $_SESSION['enddate'];

    $code = mysql_query("SELECT id, name, UNIX_TIMESTAMP(date) AS date, reason FROM taken WHERE date BETWEEN '$startdate' AND '$enddate' ORDER BY date ASC");


    while($row = mysql_fetch_array($code)) {



 echo "t<tr><td>{$row['id']} ".
"</td><td>{$row['name']}  ".
"</td><td>" . date( "d/m/Y", $row['date'] ) ."".
     "</td><td>{$row['reason']} </td></tr>n";

it produces the below result but i want to put a space between the date change. I.E a space / break between 28/05/2016 & 29/05/26.

Any help would be appreciated.

id  Staff Name  Date    Reason
1296    28/05/2016  Holiday
1832    28/05/2016  Holiday
1330    28/05/2016  Holiday
825 28/05/2016  Holiday
1858    28/05/2016  Holiday
849 28/05/2016  Holiday
1958    28/05/2016  Holiday
2022    28/05/2016  Holiday
1263    28/05/2016  Holiday
1331    29/05/2016  Holiday
826 29/05/2016  Holiday
1959    29/05/2016  Holiday
2023    29/05/2016  Holiday
1264    29/05/2016  Holiday
1332    30/05/2016  Holiday
827 30/05/2016  Holiday
1960    30/05/2016  Holiday
2024    30/05/2016  Holiday
1265    30/05/2016  Holiday
533 31/05/2016  Holiday
1843    31/05/2016  Holiday
52  31/05/2016  Holiday
1420    31/05/2016  Holiday
1679    31/05/2016  Holiday
1938    31/05/2016  Holiday
936 31/05/2016  Holiday
231 31/05/2016  Holiday

Why this code isn't update on db?


When I try update with a form, this code insert a new row in database instead updating it. I can't see where is the error.

Root code:

$app->post('/slides/update/{id}', function (Request $request, Response $response, $args) {

$slide_data['id_slide'] = (int)$args['id'];
$slide_data['title'] = filter_var($data['title'], FILTER_SANITIZE_STRING);
...
$slide_data['text_3'] = filter_var($data['text3'], FILTER_SANITIZE_STRING);

$slide = new SlideEntity($slide_data);
$slide_mapper = new SlideMapper($this->db);
$slide_mapper->update($slide);

$response = $response->withRedirect('/slides');
return $response;
});

SlideMapper code:

public function update(SlideEntity $slide) {
$sql = "UPDATE slide
        SET id_client=:id_client, title=:title ... text_3=:text_3
        WHERE id_slide=:id_slide";

$stmt = $this->db->prepare($sql);
$result = $stmt->execute([
  "id_slide" => $slide->getId(),
  "url" => $slide->getUrl(),
  ...
  "text_3" => $slide->getText_3(),
]);
}

SlideEntity code:

class SlideEntity
{

protected $id;
protected $url;
...
protected $text_3;


public function __construct(array $data) {
    if(isset($data['id_slide'])) {
        $this->id = $data['id_slide'];
    }

    $this->title = $data['title'];
    $this->description = $data['description'];
    ...
    $this->text_3 = $data['text_3'];
}

I will appreciate any help :)


Select records from one table that are not in another table but with specific conditions


I have three tables, let's call them offers, users and demands.

Table users
id | name
1      A
2      B
3      C

Table demands
id | id_user_fk
1         1
2         2
3         3

Table offers
id | id_demand_fk | id_user_fk
1         1             1
2         1             2
3         1             3
4         2             1
5         2             2
6         2             3

Here is my problem. The purpose is to assign users to demands in order to let them post offers. When I assign these users, I've a bootstrapTable that allows me to write in the offers table.

Here is the query I made to get the list of users :

SELECT u.id "
            . "FROM users u "
            . "LEFT JOIN offers o on o.id_user_fk = u.id "
            . "WHERE o.id_demand_fk <> " . $id . " OR u.id is null "
            . "GROUP BY u.id"

The purpose is to ONLY show users that are not already assigned to the offer (which is why I use an $id). Problem is, users 1, 2 and 3 are assigned to both demands 1 and 2, so when I open the view that should show users that can be assigned to demand 2, I do have users 1, 2 and 3 because they're assigned to demand 1. My query doesn't filter that, and I've no clue how to do it.

Thank you in advance


Date stored in varchar format. Result issue


Sorry for my poor technical English. I try to get some data from my db between now with 1 month interval.

This query work perfectly (221 rows returns)

SELECT idEcare,reference 
FROM DEMS
WHERE (((etatSuivant ="Etat_ADM_131276535415392&SURF=Transmis") 
OR (etatSuivant = "Etat_ADM_121276535415390&SURF=Traitement en cours") 
OR (etatSuivant = "Etat_ADM_11276535415374&SURF=A l étude") 
OR (etatSuivant = "Etat_ADM_81276535415384&SURF=Programmé")) 
AND ((categorisation LIKE "%Propreté:Tas sauvage%") 
OR (categorisation LIKE "%Circulation et stationnement:Véhicule gênant%") 
OR (categorisation LIKE "%Circulation et stationnement:Véhicule ventouse_Epave_Brûlé%")
OR (categorisation LIKE "%Propreté:Passage ponctuel%") 
OR (categorisation LIKE "%Propreté:Corbeille pleine%") 
OR (categorisation LIKE "%Propreté:Huile_Verre cassé%") 
OR (categorisation LIKE "%Propreté:Désherbage_Feuilles mortes%") 
OR (categorisation LIKE "%Propreté%") 
OR (categorisation LIKE "%Espace Vert:Entretien des massifs:Nettoyage%") 
OR (categorisation LIKE "%Mobilier urbain:Corbeille:Réparation%")) 
AND (confidentialite = "Non"))

I want return the row from last month only. I have tried BETWEEN fonction but my field "dateModification" is in VARCHAR format ( "06/02/2012 13:55:09") so i have a result : Truncated incorrect date value: "06/06/2016 13:55:09"

How i can modify this query to have a rows from the last 30 days only ?


dojo select widget not parsing arrow correctly


I have found that dojo is not parsing the dropdown arrow to my select list correctly. The issue: Rendering Issue

If I inspect the code I see this:

Bad Select list

<td class="dijitReset dijitRight dijitButtonNode dijitArrowButton dijitDownArrowButton dijitArrowButtonContainer" data-dojo-attach-point="titleNode" role="presentation">

    <input class="dijitReset dijitInputField dijitArrowButtonInner" value="▼ " type="text" tabindex="-1" readonly="readonly" role="presentation">

</td>

You will see in the there is an input. this appears to be the cause of the issue. This is what code from a working list looks like.

Good Select List

<td class="dijitReset dijitRight dijitButtonNode dijitArrowButton dijitDownArrowButton dijitArrowButtonContainer" data-dojo-attach-point="titleNode" role="presentation">

<span class="dijitReset dijitInputField dijitArrowButtonInner"></span>

</td>

Notice in this one it is a span and not a input. If I replace the input in the bade code with span it works.

The issue is I have no clue why dojo is not going this properly during the initial parse. This Good select list code is from a different code base but is the same dojo build.


Giving a query to my database and returning the result


So I put a function in my php function code which was

public function getName($name){
$result = mysql_query("SELECT * FROM 'users' WHERE 'name' = '$name' or trigger_error(mysql_error());

return "$result"; }

Edit: my question is how do I call this code in my android class so that I can put that result in an arraylist which is my ultimate goal.

I am trying to get all the names in that column and put them in an array list. And so in my activity android class i put this code.

 Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(Constants.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    RequestInterface requestInterface = retrofit.create(RequestInterface.class);

    User user = new User();
    user.setName(name);
    user.setEmail(email);
    user.setPassword(password);

    usernames.add(name);
    ServerRequest request = new ServerRequest();
    request.setOperation(Constants.REGISTER_OPERATION);
    request.setUser(user);

    Call<ServerResponse> response = requestInterface.operation(request);

    response.enqueue(new Callback<ServerResponse>() {
        @Override
        public void onResponse(Call<ServerResponse> call, retrofit2.Response<ServerResponse> response) {

            ServerResponse resp = response.body();
            Snackbar.make(getView(), resp.getMessage(), Snackbar.LENGTH_LONG).show();
            progress.setVisibility(View.INVISIBLE);

        }

I am not sure if this is right, any help would be much appreciated!


How to prevent HTML canvas pixel stretching with size [duplicate]


This question already has an answer here:

I am plotting pixels to the HTML canvas:

var styleOpts = {
                  border:'1px solid #d3d3d3',
                  width:'512px',
                  height: '512px'
                };

<canvas width=10
        height=10 
        style={styleOpts} />

I noticed that when the inline style width and height are greater than the canvas width and height (as specified in the canvas tag), the resulting image is stretched and blurred. It's as if I rescaled a jpeg image rather than a vector image. I would have expected the latter. Can anyone help me scale the pixels without blurring? Note that if the widths and heights match, it looks as expected, but it's just too small for my needs.

enter image description here

If I increase the scaling even more: enter image description here


Android Explote trying to handle receiving null json data from my host


I want to handle when my json receive NULL data from my host. But the if conditions never happens when my json is null (I unplugged the internet conection to receive null data). See my code:

        JSONObject json = null;
        JSONObject json2 = null;
        JSONObject json3 = null;
        date= (String.valueOf(anio)) + "-" + (String.valueOf(mes + 1)) + "-" + (String.valueOf(dia));
        try {
            json = JSONParser.readJsonFromUrl(url1.concat(date)));
            json2 = JSONParser.readJsonFromUrl(url2.concat(id));
            json3 = JSONParser.readJsonFromUrl(url3.concat(date));
        } catch (IOException | JSONException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        if(json == null || json2 == null || json3 == null){
            String mensajeAlerta = "Verifique su conexión a internet...";
            Intent intent = new Intent(MyActivity.this, SecondActivity.class);
            intent.putExtra("id", id);
            intent.putExtra("name", name);
            intent.putExtra("mensajeAlerta", mensajeAlerta);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            finish();
        }

EDIT: JSONParser class

public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
    InputStream is = new URL(url).openStream();
    try {
        BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
        String jsonText = readAll(rd);
        return new JSONObject(jsonText);
    } finally {
        is.close();
    }
}

private static String readAll(Reader rd) throws IOException {
    StringBuilder sb = new StringBuilder();
    int cp;
    while ((cp = rd.read()) != -1) {
        sb.append((char) cp);
    }
    return sb.toString();
}

Thanks for helping!


How to manage date and time mismatch for different countries users in php and mysql


Hey I am working on my social network project. So I m so confused with the issue related with date and time of update,comment,messages and anything wherever I am showing date and time.

Suppose I am sorting my updates using date and time. I am storing date and time in mysql using CURDATE() and CURTIME() functions respectively.

Suppose, I just posted something in India on my profile at 6.40 pm. So when it shows on my London friend profile, it will show stored date and time means Indian date and time. But Indian time is ahead of the UK time. So it will show 6.40Pm for that update when current time of London is 2.10PM. So showing 6.40Pm which is not the good thing for them. So I have to show local time for that post means 2.10Pm. Basically I want to show all updates time is less than current date and time of the user but it is impossible for updates posted by ahead time countries. So How to store and convert these date and time according users countries.

I hope you all understand and will save my day by helping me. And you also free to ask questions if you don't understand any part. Thank you all.


Log sequence number in ibdata files does not match


Everytime when I start my Mysql database I see this in the error_log:

131015 12:07:06 [Note] Plugin 'FEDERATED' is disabled. 131015 12:07:06 InnoDB: The InnoDB memory heap is disabled 131015 12:07:06 InnoDB: Mutexes and rw_locks use Windows interlocked functions 131015 12:07:06 InnoDB: Compressed tables use zlib 1.2.3 131015 12:07:06 InnoDB: Initializing buffer pool, size = 16.0M 131015 12:07:06 InnoDB: Completed initialization of buffer pool 131015 12:07:06 InnoDB: highest supported file format is Barracuda. InnoDB: The log sequence number in ibdata files does not match InnoDB: the log sequence number in the ib_logfiles! 131015 12:07:06 InnoDB: Database was not shut down normally! InnoDB: Starting crash recovery. InnoDB: Reading tablespace information from the .ibd files... InnoDB: Restoring possible half-written data pages from the doublewrite InnoDB: buffer... 131015 12:07:07 InnoDB: Waiting for the background threads to start 131015 12:07:08 InnoDB: 5.5.32 started; log sequence number 1595695 131015 12:07:08 [Note] Server hostname (bind-address): '0.0.0.0'; port: 3306 131015 12:07:08 [Note] - '0.0.0.0' resolves to '0.0.0.0'; 131015 12:07:08 [Note] Server socket created on IP: '0.0.0.0'.

I've tried mysqlcheck -u root -p --repair -A in order to repair the database. This reports that all tables are a-ok.

I've also tried setting innodb_force_recovery to 4

I've tried SET GLOBAL innodb_fast_shutdown = 1; and shutdown the DB.

None of these make the errors go away.

How do I repair the InnoDB tables in my database?


No return from sqli_query for login [duplicate]


I have a login page that redirects to this set of PHP code:

<?php
   $mysql_host = "***";
   $mysql_database = "***";
   $mysql_user = "***";
   $mysql_password = "***";

   $conn=mysqli_connect($mysql_host, $mysql_user, $mysql_password, $mysql_database);

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

   $email = $_POST["email"];
   echo $email;
   $password = $_POST["pass"];
   echo $password;

   $stmt = $conn->prepare("SELECT email, password FROM account WHERE email = ?");
   $stmt->bind_param("s", $email);
   $stmt->execute();
   $stmt->bind_result($mail, $pass);
   echo $stmt;
   echo $mail;
   echo $pass

   if ($pass === $password and $password != null)
   {
       echo "Logged in";
   } else {
       echo "Unsuccessfull";
   }
?>

When I run it with the test values in my database I get these messages:

random@sample.com

password

SELECT password FROM account WHERE email = random@sample.com

Warning: mysqli_free_result() expects parameter 1 to be mysqli_result, boolean given in /home/a3996154/public_html/login.php on line 22

Unsuccessfull


Changing a file directory when using socket.io and node.js?


I have created a successful connection and handled events of someone connecting and disconnecting. However I am now trying to clean up my folders to create something that is a bit more clean to work with.

I have looked at some examples of changing directories, however it seems that I am missing something.

I am quite new to using node and socket, so might seem a bit obvious with the problem.

My basic file structure is i have a main app folder, with an index.html file, server folder with all the relevant node and socket code, then a public folder with css, js, image folders.

File Structure

So my index is in the route. I do also find when I try linking stylesheets and js files it returns a 404 error. Not entirely sure. Any help would be greatly appreciated.

// Sets a base path for acessing all files
app.use(express.static('/'));

app.get("/", function(req, res){
    res.sendFile(__dirname + './index.html');
});

EDIT:

Updated file structure: New Structure


checkbox null exception javascript


function goMovies() 
{
    alert("Getting Movies...");
    $.getJSON('NikkiNacksProducts.json', function(nikkitable) 
    {
        var output="<table>";
        for (var i in nikkitable.products) 
        {

            if (nikkitable.products[i].productType == "Movie")
            {
            output+= "<tr><td><input id = '"+i.toString() +"c' type='checkbox'></td><td>" + nikkitable.products[i].productId + "</td><td>" + nikkitable.products[i].productName + "</td><td>" + nikkitable.products[i].productType + "</td><td>" + nikkitable.products[i].newRelease + "</td><td>" + nikkitable.products[i].productPrice+ "<td><input id = '"+i.toString() +"t' type='text' name='Number of copies' > </td></tr>";
            }
        }
         output+="</table> <button onclick="total();">";
        document.getElementById("placeholder").innerHTML=output;
  });}
</script>

<script>
function total()
{
   var totala = 0.0;
$.getJSON('NikkiNacksProducts.json', function(nikkitable)
 {
        for (var i in nikkitable.products)
  {
         var temp ="'"+i.toString() +"c'"
         if(document.getElementById(temp)!="null")
         {
         if(document.getElementById(temp).checked)
         {
           temp ="""+i.toString() +"t""
           totala += parseFloat(document.getElementById(temp).value) * nikkitable.products[i].productPrice;
         }
}
  }     
  });
alert(totala);
}
</script>

The goMovies() creates a checkbox which is accessed by the total(). It's returning => typeError: document.getElementById(...) is null. nikkitable is the json file containing an of arrays of movies and songs


When is GROUP BY required for aggregate functions?


I have a table called myEntity as follows:

- id (PK INT NOT NULL)
- account_id (FK INT NOT NULL)
- key (INT NOT NULL.  UNIQUE for given account_id)
- name (VARCHAR NOT NULL.  UNIQUE FOR given account_id)

I don't wish to expose the primary key id to the user, and added key for this purpose. key kind of acts as an auto-increment column for a given accounts_id which will need to be manually done by the application. I first planned on making the primary key composite id-account_id, however, the table is joined to other tables, and before I knew it, I had four columns in a table which could have been one. While account_id-name does the same as account_id-key, key is smaller and will minimize network traffic when a client requests multiple records. Yes, I know it isn't properly normalized, and while not my direct question, would appreciate any constructive criticism comments.

Sorry for the rambling... When is GROUP BY required for an aggregate function? For instance, what about the following? http://stackoverflow.com/a/1547128/1032531 doesn't show one. Is it needed?

SELECT COALESCE(MAX(key),0)+1 FROM myEntity WHERE accounts_id=123;

How to use mouse event instead of keycode for HTML5 canvas and jquery?


I'd to like to replace the following event management from keycode to mouse. How do I go about doing it?

Supported browser for now = FF 3.6x.

// this block of code needs to be replaced
$(document).keydown(function(e) {
//console.log(e.keyCode);
switch(e.keyCode) {
case 38: // down
draw(x,y--);
break;
case 40: // up
draw(x,y++);
break;
case 37: // left
draw(x--,y);
break;
case 39: // right
draw(x++,y);
break;
default:
draw(x,y);
}
});

// to be replaced with something like the following and add control
// we need to get the x,y coordinates upon mouse click, not onload, how?
$(document).onmousemove = mouseMove;

function mouseMove(ev){
    ev           = ev || window.event;
    var mousePos = mouseCoords(ev); 
    alert( mousePos);
}

function mouseCoords(ev){
    if(ev.pageX || ev.pageY){
        return {x:ev.pageX, y:ev.pageY};
        return {x:ev.pageX};
    }
    return {
        x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
        y:ev.clientY + document.body.scrollTop  - document.body.clientTop
    };  
}


// keep
function draw(x,y) {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var canvas = $("#canvas")[0];
var ctx = canvas.getContext("2d");

ctx.font = "15pt Verdana";
// var ctx.lineWidth = 1;

ctx.clearRect(0,0,500,500);

x1 = x + 50;
y1 = y + 50;
ctx.fillText("Oh my god his pant is falling down",x1,y1);

x2 = x + 100;
y2 = y + 100;
ctx.fillText("shi shi we did not see anything",x2,y2);

x3 = x + 200;
y3 = y + 200;
ctx.fillText("what a happy man!",x3,y3);
}

draw(x,y);

Registration validation doesn't work properly [duplicate]


This question already has an answer here:

I have registration form, with "username" and "password".

 <form  method="post" onSubmit="return check();" name="Reg">    
        <input type="text" name="email" id="email" class="sign-up-input" maxlength="30" placeholder="Username" >
        <input type="password" class="sign-up-input" name="Password" id="Password" maxlength="25" placeholder="Password" >
        <input type="submit" value="Sign up" name="signup"  class="sign-up-button" onClick="time_get()">
 </form>

After I enter values for "password" and "username", I want to check wheter those values are valid. First I want to check if the user entered values for "email" and "password", after the user press the "signup" button.

 if(isset($_POST['signup']))
 {
            $error_text="";
            $check_val=1;
            if(isset($_POST['email']) && isset($_POST['password']))
            {
                //area 1 
                //entered values for email and password
                $email_signup=$_POST['email'];
                $password_signup=$_POST['password'];
                //more code....
            }
            else
            {
                //area 2
                //email or password are empty
                $check_val=0;
                $error_id=1;
            }
  }

For after I enter valid values for "email" and "password", and then press the "sign-up" button, it enter to "area 2", meaning that at least one value(email/password) is empty.

What is the problem with my code?


Automatically reusing existing entity in ManyToMany/ManyToOne relationship (JPA)


JPA and Hibernate are used to retrieve and persist entities. There is a User table and it contains a Country, which is represented in another table.

I would like to insert a new user into User table. This new user is from country that is already inserted in the Country table. To assign the new user the existing country I could retrieve the country object from the database and set it to the User object - it works as expected, a relationship is created between user and the existing country, no new rows are inserted to Country table.

Is it possible to get the same behavior without retrieving Country objects from database, based just on the value that I set to the Country object in the JPA entity in Java?

For example:

User user = new User("test user");
user.setCountry(new Country("USA"));
entityManager.persist(user);

I would like JPA/Hibernate to automatically check if the country, which code is USA (code is saved in a column in Country table and it is unique), already exists in the database. If it does - use the existing Country object so that a new entry in the database would not be created, if it does not exist - insert a new country in the Country table.

Thank you!


How to set form input values inside an ng-repeat?


I have an ng-repeat that's getting songs from Spotify. For each song in the ng-repeat, I want a form where the input value is pre-populated based on the information from the song.

Here is my view:

<div ng-repeat="song in spotifyResults">
    <h1>{{song.name}}<h1>
    <h2>Artist: {{song.artists[0].name}}</h2>      
    <h3>Album: {{song.album.name}}</h3> 
    <h4>{{song.id}}</h4>
    <iframe ng-src="{{getIframeSrc(song.id) | trusted}}" width="100%" height="50%" frameborder="0" allowtransparency="true"></iframe>

    <form class="form" name="form" ng-submit="selection.addSong(songName)" novalidate>
    <div class="form-group">
        <label>Name</label>
        <input type="text" value="{{song.name}}" name="songName" class="form-control" ng-model="songName" required/>
    </div>
    <button class="btn btn-primary">Save Song</button>
   </form>
<hr>
</div>

I can successfuly set the placeholder of the input using the expressions inside the repeat like so:

placeholder="{{song.name}}"

But I can't seem to set the value of the input like this:

value="{{song.name}}"

If i try and submit the form with the value set using an expression, the songName argument passed into the ng-submit function is undefined.

How can I set default form input values inside an ng-repeat?


Interface Error of mysql


I installed mysql connector/python and am using MAMP. When I try to connect to a database,this is what comes up in the terminal :

Traceback (most recent call last):
File "database.py", line 7, in <module>
    raise_on_warnings= True)
File "/Library/Python/2.7/site-packages/mysql/connector/__init__.py", line 179, in connect
        return MySQLConnection(*args, **kwargs)
  File "/Library/Python/2.7/site-packages/mysql/connector/connection.py", line 95, in __init__
    self.connect(**kwargs)
  File "/Library/Python/2.7/site-packages/mysql/connector/abstracts.py", line 719, in connect
    self._open_connection()
  File "/Library/Python/2.7/site-packages/mysql/connector/connection.py", line 206, in _open_connection
    self._socket.open_connection()
  File "/Library/Python/2.7/site-packages/mysql/connector/network.py", line 475, in open_connection
    errno=2003, values=(self.get_address(), _strioerror(err)))
mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on 'localhost:8889:3306' (60 Operation timed out)

I tried going into the connector folder and checked out the network.py script and it seems the error is due to Interface Error. The documentation says:

This exception is raised for errors originating from Connector/Python itself, not related to the MySQL server.

errors.InterfaceError is a subclass of errors.Error

Here's my python script if required:

import mysql.connector

con = mysql.connector.connect(user='root',
                              password ='root',
                              host='localhost',
                              database='testdb',
                              raise_on_warnings= True)

cur = con.cursor()

cur.close()
con.close()

How to get rid of the interface error?


How to crop and upload photo using cropit jquery plugin with php


So I currently found this photo cropping plugin called cropit . Demos are here . So what I want to do is grab the cropped photo and upload the name of the photo to the mysql database and save it to a directory using php.

So far I have this :

HTML :

<form method="POST">
    <div class="image-editor">
        <div class="cropit-image-preview-container">
            <div class="cropit-image-preview"></div>
        </div>
            <div class="image-size-label">
            Resize image
        </div>
        <input type="range" class="cropit-image-zoom-input">
        <input type="hidden" name="image-data" class="hidden-image-data" />
        <button type="submit">Submit</button>
    </div>
</form>

jQUERY :

    $('form').submit(function() {
        // Move cropped image data to hidden input
        var imageData = $('.image-editor').cropit('export');
        $('.hidden-image-data').val(imageData);

        // Print HTTP request params
        var formValue = $(this).serialize();
        $('#result-data').text(formValue);

        // Prevent the form from actually submitting
        return false;
    });

All I need help is with the php set up code because when I crop the photo and select submit, jquery returns the serialize code, and all this code that I'm usually not familiar with appears. Here is a few characters of the serialized code jquery returns:

image-data=data%3Aimage%2Fpng%3Bbase64%2CiVBORw0KGgoAAAANSUhE...

How to model Friendship relationships


I have been trying to figure out how to do this, and even with looking at other examples, I can't get it figured out, so maybe I can get some personalized help.

I've got two tables, users_status and friendships.

In the users_status table I have a field userid, and several others. In the friendships table, I have the fields request_to,request_from, and friendship_status.

Basically what I want to do is get all of the status posts by the current user AND those who are friends of the current user (which I can specify in my PHP using a $userid variable).

Here's an example of the friendships table structure. When a friend request is sent, the userid of the sender and receiver are placed in the table, with a friendship_status of 0. When the request is accepted, the friendship_status is set to 1 and those two are now friends.

friendship_id   request_from    request_to  friendship_status
1               111248          111249      1
2               111209          111249      1
3               111209          111248      0
11              111209          111259      1
5               111252          111209      1
12              111261          111209      1

I realize this may not even be the best structure for determining friendships, especially since the site is relationship based and having to check for friendship connections will be a frequently used thing.

Would it perhaps be better to have two separate tables for friend_requests and friendships? If so, how would I structure/manage the friendships table?