...

Hi! I’m Starx

experienced Software Developer. And this is my blog
Start Reading About me
Blog Page
March 31, 2012

Entry Of Duplicate Rows in Mysql

Question by dotman14

Please I need your help with my script. I’m trying to insert values into maintable, but before I insert, I have to check if a row have an exact match compared to the one I’m inserting. If there’s a match then it should echo Record Exists, and if not it should go ahead and insert into the table. The problem is that it is returning 0 for $duplicate, when actually there is a row that matches the entries that I’ve entered in the HTML page, thereby it goes ahead and inserts the duplicate.
Please what could the problem be?

{
    $query = mysql_query("SELECT m.matric_no, m.course_code, m semester_name, m.level, m.session 
                          FROM  maintable AS m 
                          WHERE m.matric_no = '".$matric_no."'
                          AND m.course_code = '".$course_code."'
                          AND m.semester_name = '". $semester_name."'
                          AND m.level = '".$level."'
                          AND m.session = '".$session."'") ;

    $duplicate = mysql_num_rows($query);

    if ($duplicate > 0 ) 
        echo "$duplicate" ;
    {
        echo "Record Exists"     
    }
    else
    {

        $query = "INSERT INTO maintable (matric_no, course_code, semester_nam,          session, level) 
                   VALUES ('".$matric_no."', 
                       '".$course_code."',
                       '".$semester_name."',
                       '".$session."', 
                       '".$level."')" ;
        mysql_query($query) or
            die (mysql_error());   

        echo"Record Inserted"; 
    }

Please forgive my formatting, I typed on a mobile, I didn’t mean disrespect to this community.

Answer by Jamie

Your formatting’s a bit all over the place, which is why you’re finding it so hard to spot errors when they occur. Try sticking to a consistent format style. This should do the trick:

$check = mysql_query("SELECT * FROM maintable WHERE matric_no = '$matric_no' AND course_code = '$course_code' AND m.semester_name = '$semester_name' AND m.level = '$level' AND m.session = '$session'");

if(mysql_num_rows($check))
{
   echo 'Record exists!';
}
else
{
   $query = "INSERT INTO maintable (matric_no, course_code, semester_nam, session, level) VALUES ('$matric_no','$course_code','$semester_name','$session','$level')";
   mysql_query($query) or die (mysql_error());
}

Answer by Starx

You are counting rows, which may return 0 if no records matching your query were found. However you are mixing if code block

if ($duplicate > 0 ) 
    echo "$duplicate" ;
{
    echo "Record Exists"     
}

Should be

if ($duplicate > 0 )         
{
    echo "$duplicate" ;
    echo "Record Exists"     
}

I have checked your code, and it seems valid. Try to simplify it

$result = mysql_query("SELECT * FROM maintable WHERE matric_no = '$matric_no' AND course_code = '$course_code' AND m.semester_name = '$semester_name' AND m.level = '$level' AND m.session = '$session'");

if(!mysql_num_rows($result))
{
   $query = "INSERT INTO maintable (matric_no, course_code, semester_nam, session, level) VALUES ('$matric_no','$course_code','$semester_name','$session','$level')";
   mysql_query($query) or die (mysql_error());
}
Read more

How to make a link navigate to another page and also mailto an email?

Question by Doug Firr

I’d like a link where if someone clicks a mailto link they are also shown a different page.

What would the html look like? Currently:

<a href="mailto:someone@mail.com">email</a>

Any ideas?

Answer by Starx

Use Javascript’s window.location on the click event of the link

<a href="mailto:someone@mail.com" onclick="window.location=another.html">email</a>

Update:

If you have to stack up lots of code in the onclick event, create a function instead

function handleClick() { 
   _gaq.push(['_trackEvent', 'emails', 'clicked', 'lead']); //first this
   window.open = 'anotherpage.html'; //or window.location for redirection
}

HTML

<a onclick="handleClick()" href="mailto:someone@mail.com">email.com</a>
Read more

getting the child text from a div in a .each loop

Question by randy

this is just a couple of lines of code that i have in my page.
I am using the jquery ui drag and drop. These are two of the items of many

when the saved button is press i need to get all the IDs and the text in the group_name div

This function gets the ID ok but i can not figure out how to get the $(‘group_name’).text() from the current LI in the each loop.

   function saveChanges(){
        $("li.ui-state-default").each(function() {
            var $divitem = $( this );
            console.log($divitem.attr('id'));
        });
    }

this is the html snippet

<li id="5" class="ui-state-default">
<div class="group_name">Classes</div>
<div class="group_footer">
      <a title="Delete this group" class="mytrash-icon" href="#">
         <img border="0" src="trash.png" class="mytrash-img"></a>
      <a title="Manage Subfolders" class="subfolder" href="#">   
         <img border="0" src="Folder-Icon.png"></a>
    </div>
</li>
<li id="6" class="ui-state-default">
<div class="group_name">Coaching</div>
<div class="group_footer">
        <a title="Delete this group" class="mytrash-icon" href="#">
          <img border="0" src="trash.png" class="mytrash-img"></a>
        <a title="Manage Subfolders" class="subfolder" href="#">
          <img border="0" src="Folder-Icon.png"></a>
    </div>
</li>

Thanks for any help!

Answer by Starx

One way would be to use .find()

$("li.ui-state-default").each(function() {
    var $divitem = $(this);
    console.log($divitem.find(".group_name").text());
});​

Another would be to use .children()

$("li.ui-state-default").each(function() {
    var $divitem = $(this);
    console.log($divitem.children(".group_name").text());
});​

But the one I like is neither

$("li.ui-state-default").each(function() {
    var $divitem = $(this);
    console.log($(".group_name", $divitem).text());
});

Read more

Tools like LESS

Question by noahklein94

I recently started using LESS and I love it. Are there any other useful tools that expand CSS and/or HTML with more functionality?

Answer by Starx

FIRST of all they are not TOOLS

They are extensions to original CSS, they allow you to create style sheets in a very efficient pattern. Give programming like feature in CSS.

Second, SASS is a perfect alternative to LESS and quite popular one to.

Read more

Why doesn't the jQuery script set the width of an element?

Question by JamesCharless

James here. I’m working on a site that I want to have the same number of posts no matter what the screen resolution. I’m trying to use this script, but it’s not working. It SHOULD get the width of the page document, subtract 400px, divide that number by 4, and then set the CSS of the element .entry to that math equation. Can anyone help me figure out what’s wrong? I’m new to jQuery, so it’s surprising I was able to even get this far.

EDIT: I solved my problem using this code in the end:

$(function() {
            var cwidth = $(document).width() - 100;
            var pwidth = cwidth - 150;
            var ewidth = (pwidth - 150)/5;
            $("#container").css("width", cwidth);
                $("#posts").css("width", pwidth);
                $(".entry").css("width", ewidth);
                $(".photo").css("width", ewidth);
});

So thank you all quite a bit for helping. However, I’ve ran into a few more problems. For some reason even though the script divides by 5, there are only 4 posts per row and the posts overflow out of the div they’re in. Example: http://jamescharless.tumblr.com/ – I think this is because the div the entries are in doesn’t have a width set in the CSS since it’s added with jQuery. Does anyone know how to fix this? Also, I tried implementing masonry by David Desandro, and it just messes up the whole page. I think this is also because the div #posts and the div .entry doesn’t get a width via CSS. Can anyone help me with either of these issues?

Answer by Jack Franklin

You need to do:

$(document).width()

Not

$("document").width()

Working JSFiddle: http://jsfiddle.net/WsZry/

$(function() {
    width = ($(document).width()-400)/4;
    $(".entry").css("width", width);
})​;

As document isn’t a HTML element, it’s a JavaScript property.

Answer by Starx

You quoted the document inside double quotes $("document")

$(function() {
    var width = ($(document).width() - 400)/4;
    $(".entry").css("width", width);
});
Read more

jQuery sliding animation not working

Question by Jake Zeitz

I have three divs stacked on each other but offset so that a part of each div is visible. When one of the bottom divs is clicked I want the top div to animate out and back into the stack at the bottom, then the div that is clicked will appear at the top. So far I only have the code for when the middle div is clicked, but I cannot get it to work properly. What am I doing wrong? (I also realize that the code I wrote is probably terrible, this is the first jQuery code I have written.)

The css is very very simple:

    .first {
        z-index: 3;
    }
    .second {
        z-index: 2;
    }
    .third {
        z-index: 1;
    }

The basic html is this:

    <div class="first"></div>
    <div class="second"></div>
    <div class="third"></div>

Here is my code:

    $("div.second").click(function () {
        $("div.first").animate({
            left: "-=200px"},
            {duration: "fast",
            complete: function () {
                $("div.first").removeClass("first").addClass("third").animate({left: "+=350px", top: "+=60px"}, "fast");
            }
        });
        $("div.second").animate({
            left: "-=24px", top: "-=30px"},
            {duration: "fast",
            complete: function () {
                $("div.second").removeClass("second").addClass("first");
            }
        });
        $("div.third").animate({
            left: "-=24px", top: "-=30px"},
            {duration: "fast",
            complete: function () {
                $("div.third").removeClass("third").addClass("second");
            }
        });
    });

I can get the div.first to move to the side and back. But now I can’t get the classes to stay changed. What keeps happening is the div.second will remove it’s class and add .first in the animation, but when the animation is complete, it acts like it still has a class of .second.

Answer by Starx

That coding style is very inefficient.

Use something like this, It applies to every div

$("div").click(function() {
   var first = $(".first");
   var fleft = first.css("left");
   var ftop = first.css("top");           

   var $this = $(this);
   var tLeft = $this.css('left');
   var tTop = $this.css('top');
   var tClass = $this.attr("class");

   first.animate({
      left: tLeft,
      top: tTop
   }).attr("class", tClass);

   $this.animate({
       top: ftop,
       left: fleft
   }).attr("class", "first");        

});

Demo

Read more

Data retrieved from database ignoring line breaks

Question by JimmyBanks

Data that is stored in my mysql database, has the breaks of text input properly, but when retrieved the data no longer has the breaks, and everything is displayed as one string without any <br>. Any idea why this would occur?

The data column is the format text,
for example: in a table there is:

hey
how
do
you
do

After retrieving the data ill echo $mesarray[0][message]; and the result is:

hey how do you do

I want the line breaks to appear, but they dont.

Answer by Starx

The reason is because HTML does not understand line breaks. They need <br /> tags to break lines.

There is a function called nl2br() which can be used to convert new lines to <br>

echo nl2br($mesarray[0][message]);
Read more

How do I change an attribute of an element when someone scroll pass the element (Sticky Element)

Question by Jonathan Shepherd

For example http://twitter.github.com/bootstrap/base-css.html try to scroll up. You will see the bar with

“Typography Code Tables Forms Buttons Icons by Glyphicons”

when you scroll pass the element it will add a class to make the element change. While you are scrolling back up it will remove the attribute to change the element again.

Edit: I found out this is call Sticky Element.

Answer by Cybrix

THat jQUery plugin can do what you want: http://imakewebthings.com/jquery-waypoints/

And here is an exemple taken from the URL:

someElements.waypoint(function(event, direction) {
   if (direction === 'down') {
      // do this on the way down
   }
   else {
      // do this on the way back up through the waypoint
   }
});

Cheers

Answer by Starx

They are using addClass() function for this

$(".subnav").addClass("subnav-fixed");

Here is the function they are using for this

function processScroll() {
    var i, scrollTop = $win.scrollTop() //get the scroll position of the window object
    if (scrollTop >= navTop && !isFixed) { //check if its position is higher that the position of the navigation
    isFixed = 1 //if yes fix it
    $nav.addClass('subnav-fixed')
} else if (scrollTop <= navTop && isFixed) { //if is not higher then
    isFixed = 0
    $nav.removeClass('subnav-fixed') //un fix it
}
}

And they call this function on the scroll event of the document. May be something like

$(document).scroll(function() {
    processScroll();
}); 
Read more

Overriding styles without !important

Question by Hendrik

How is it possible to override styles specified in another style sheet?

I do not want to use the !important tag to override them. I would much rather specify a new style sheet, put styles in there. Could this be achieved by changing the load order of the style sheets?

Answer by minitech

It depends. CSS stands for Cascading Style Sheets, and there’s a specific order that styles are applied in, overwriting previous styles. Without going into too much detail:

  • If your rules have the same specificity, just load your stylesheet second and everything will work fine.
  • If your rules have higher specificity, the order won’t matter.
  • If your rules have lower specificity, you’ll need to modify them to match.

So, what’s specificity? Basically, it’s the sum of each selector in a rule. So this:

a {
    background-color: black;
    color: white;
}

Has less specificity than this:

body a {
    color: orange;
}

. ID selectors have higher specificity than class selectors, which have the same specificity as pseudo-class selectors, which have higher specificity than tag selectors. So if all your content is contained in a <div> with an id of content, you would be able to override a style that looks like this:

body a {
    border: 0;
}

With:

#content a {
    border: 1px solid black;
}

Answer by Starx

If you can increase the specificity of styles, you can do this without the !important.

For example:

HTML

<div id="selector">
  <a>Hello</a>
  <a class="specific">Hi</a>
</div>

CSS

div a {}

Will be ignored, if you give a specific class inside #selector

.specific { }

Here is a demo explaining my point. Basically, the idea is to define the styles as closely as possible.

Read more
...

Please fill the form - I will response as fast as I can!