...

Hi! I’m Starx

experienced Software Developer. And this is my blog
Start Reading About me
Blog Page
June 18, 2013

Fetching result isn't working after prepared statement

Jskidd3’s Question:

I’m struggling to write this myself so I will say what I know I need to do and what I have already.

Based on two $_GET[] variables I need to query a database. The values provide me with the table name and the name of the location. From this location field name, I need to extrapolate the whole row.

So, I query the database with this data, however when I try and fetch and print it nothing happens. I need the whole row’s data (in an array?).

I understand my code is ugly. And probably vulnerable to MySQL injection, but I would rather get my PHP right in terms of getting the row into an array before I worry about that.

Rough code I have so far:

$company = strtolower($_GET['company'] . '_a_in_m2f');
$company = mysqli_real_escape_string($mysqli, $company);

$stmt = $mysqli->prepare("SELECT * FROM " . $company ." WHERE `name` = '?'");
$stmt->bind_param('s', $stop);

$stop = $_GET['stop'];

$stmt->execute();

$stmt->bind_result($therow);

while ($stmt->fetch()) {
    printf("%s %s n", $therow);
}

Thanks

There are a few problems here:

  1. You don’t quote the variable you are going to bind (as mentioned before…);
  2. You don’t escape the table name, instead you should check it against a white-list and quote it in backticks if necessary;
  3. You don’t bind the results to an array but to individual variables. You would be better of just fetching rows from the result using fetch_row() in this case.

You do not need to bind the ? with quotes. Remove quotes from '?' to simply ?

Read more

Apache is not executing PHP scripts

User2495173’s Question:

I changed the httpd.conf as follows:

  • Replaced

    DocumentRoot "C:/Program Files (x86)/Apache Software Foundation/Apache2.2/htdocs"
    

    with

    DocumentRoot "C:/Temp/WebServerCore/Binaries/html"
    
  • Replaced

    <Directory "C:/Program Files (x86)/Apache Software Foundation/Apache2.2/htdocs">
    

    with

    <Directory "C:/Temp/WebServerCore/Binaries/html">
    

However Apache does not recognize the php code in my .html file. What other changes do I need to make for Apache to execute PHP?

It is by design. Apache will not parse PHP code inside a HTML file by default. You can include HTML codes in a PHP file as you would code them in a HTML document.

Renames your files and add extension .php at the end they will parsed as you want.

Or you can configure your apache configuration (httpd.conf) to parse PHP code inside HTML too.

AddHandler application/x-httpd-php5 .html .htm

Or you can match extension and set their handlers like

<FilesMatch ".(htm|html|php)$">
     SetHandler application/x-httpd-php
</FilesMatch>
Read more

why i cant empty textarea when i enter

HiDd3N’s Question:

i just setup a jsfiddle in this link and the problem is where i empty textarea one line break stay and i cant see placeholder again and i always one break line is there see this fiddle

http://jsfiddle.net/W5WE8/

my html

<script src="http//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<textarea id="mytextarea" rows="15" cols="80" placeholder="write something and press enter"></textarea>

and here is my js

$('#mytextarea').keydown(function(e) {
        if (e.keyCode == 13) {
            $('#mytextarea').val('').focus();
        }
    });

You need to prevent the default behaviour of the keydown. As seen here: http://jsfiddle.net/lnrb0b/W5WE8/2/

$('#mytextarea').keydown(function (e) {
    if (e.keyCode == 13) {
        e.preventDefault();
        $('#mytextarea').val('').focus();
    }
});

Hope that helps 🙂

The main reason why this is happening is because of the enter key. This will add one break line before doing what you need.

Prevent the event propagation as suggested in other answers.

Read more

How to hide Partial Data in PHP

Sameer007860’s Question:

Eperimenting PHP just for fun, But As being newbie, I’m unable to understand curcial parts of PHP….Please help me to sort out this problem which I’m explaining by example :

Suppose

$sql = "SELECT id, text,uid FROM feeds WHERE uid='".$ud."' LIMIT 10";
$items = mysql_query($sql);
echo mysql_error();

if (@mysql_num_rows($items) > 0)
{
    while ($item = mysql_fetch_array($items))
    {
        $feed = $item[1];
        $nick = getnick($item[2]);
    }
}

So I want to display like this :

3 Records with uid details…

jay,vicky, sumair and 17 others like this.

Please help me to get output of something like this !!

Thanks !!

I can’t stretch this enougth,

DO NOT USE MYSQL_* API anymore. [Read this]

It is VULNERABLE, mysqli_* functions are just as similar very little difference.

And You already are doing the things required for that output mysql_num_rows() already gives the number of total result. So:

if (@mysql_num_rows($items) > 0)
{
    $count = mysql_num_rows($items);
    echo $count." Records with uid details..."; //Display the count of records

    $threeNameHolder = array; // Hold the first three names on this

    while ($item = mysql_fetch_array($items))
    {
        $feed = $item[1];
        $nick = getnick($item[2]);
        if(count($threeNameHolder) < 3) {
            $threeNameHolder[] = $nick;
        } else break; // End the loop here
    }

    //Now display the name
    echo implode(",", $threeNameHolder). " and ".($count - 3)." others like this.";
}

Safer and MYSQLi Version

if (@mysqli_num_rows($items) > 0)
{
    $count = mysqli_num_rows($items);
    echo $count." Records with uid details..."; //Display the count of records

    $threeNameHolder = array; // Hold the first three names on this

    while ($item = mysqli_fetch_array($items))
    {
        $feed = $item[1];
        $nick = getnick($item[2]);
        if(count($threeNameHolder) < 3) {
            $threeNameHolder[] = $nick;
        } else break; // End the loop here
    }

    //Now display the name
    echo implode(",", $threeNameHolder). " and ".($count - 3)." others like this.";
}
Read more
June 17, 2013

Javascript method is not working on Firefox

Merand’s Question:

My stylesheet is working on ie, however it isnt working on firefox. It gives an error such as:

InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable @
TypeError: document.getElementById(…) is null.

Here is my code:

<script style="javascript">
    function displayRevision2() {
        for (i = 1; i & lt; j; i++) {
            foo = document.getElementById('row' + i).innerHTML;
            substring = foo.substr(0, foo.search("n") - 1);
            //displayRevision(substring);   
            if (flag == 1) document.getElementById(substring).style.display = "";
            else document.getElementById(substring).style.display = "none";
        }
        if (flag == 1) flag = 0;
        else flag = 1;
    }
</script>
<script style="javascript">
    function dispTD(num) {
        rowtxt = '&lt;TD class="br" align="middle" id="row' + num + '">';
        document.write(rowtxt);
    }
</script>
<script style="javascript">
    function dispEndTD() {
        document.write("&lt;/TD>");
    }
</script>

It may be because the element the script is searching for does not exist on the document. Try to check if the scripts finds the element first before directly accessing its attributes.

fooElement = document.getElementById('row' + i);
if(fooElement) foo = fooElement.innerHTML;
Read more

&lt;h1&gt; Header (vs h2, h3, etc)

User1994136’s Question:

I have 3 header tags.
My setup:

h1

h2

h3

QUESTION: My h3 tag is the most important (for SEO). All 3 have the same indent so I don’t want those changed in any way. If you can help me, what I need to know is:

Since h1 is seen by SEs as most important, am I allowed to rename my current h3 into h1 and vice versa, so that they are in this

order? …

h3

h2

h1

…OR does h1 always have to be “first” in the crawl? Basically I want to tell Google etc that my current h3 is far more important than my current h1 & h2.

Thanks for your help, and also for your valuable time.

NO

You cannot tell google to do invalid scrape.

Heading tags represent a block of content. As contents end up having more and more levels, we divide the content using sub headings like <h2> and <h3> and so on.

Another similar example is in word processing applications like
Microsoft Word, Heading 1 repesents the most important block where are
other headings represent a sub portion of the main block.

Based on your details Your problem seems to be styling not the heading tags, you can control the display of whatever elements using CSS.

Read more

Insert value to MySQL table safely using PDO

FriedBitz’s Question:

Would this protect my INSERT from SQL Injections? and can I somehow shorten this code to make it look neater?

$db = new PDO('mysql:host=XXXXXXXXXX;dbname=XXXXXXXXX', 'XXXXXXXXX', 'XXXXXXXXXX');

// query MySQL to verify login
$query = $db->prepare("INSERT INTO login (username,password,name,email_add,age,country) VALUES (:username,:password,:name,:email_add,:age,:country)");
$query->execute(array(
':username' => $username, 
':password' => $password,
':name' => $name,
':email_add' => $email,
':age' => $age,
':country' => $country));

YES, PDO Extension already removes all the injection vulnerabilities like that. Since you are binding params afters ward, you are doing it correctly too.

However, just to make the query at it safest state, specify the data type of the variable while binding them.

$query = $db->prepare('INSERT INTO login (username,password,name,email_add,age,country) VALUES (:username,:password,:name,:email_add,:age,:country)');

$query->bindParam(':username', $username, PDO::PARAM_STR, 20);
// and so on
$query -> execute();

More Details

Read more

how to remove script tag such {audio}{/audio} or {youtube}{/youtube}

User1999818’s Question:

in my old data it store joomla tags such “{audio}{/audio}” or “{youtube}{/youtube}”, and I want to strip these tag.

how I do in php code? if I want leave it content or remove it content.

Please help me, thank you.

Compared to regular expression replace function str_replace() is a lot faster.

$text = str_replace("{audio}", "", $text);
$text = str_replace("{/audio}", "", $text);
Read more

Assign multiple DB field entries to a single variable

User1615837’s Question:

I have a PHP question, which I was hoping someone might be able to answer quite easily…
Basically the code exports database fields into an excel file, but I need two database fields to be added to a single excel field:

Normal working single db field:

$worksheet->writeString( $i, $j++, $row['date_added'] );

Not working (in this case I would like both ‘shipping_firstname’ and ‘shipping_lastname’ to be added to a single excel cell):

$worksheet->writeString( $i, $j++, $row['shipping_firstname'] && $row['shipping_lastname'] );

Any help would be greatly appreciated!

Concatenations are using a dot(.) on PHP

$worksheet->writeString( $i, $j++, $row['shipping_firstname'] . " " . $row['shipping_lastname'] );

&& is used to combined boolean value and is mostly used in conditional statement like if

Read more
...

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