Solved

How can I makes this insert statement work?

Posted on 2014-11-12
6
89 Views
Last Modified: 2014-11-13
Here's the challenge:

You've got users uploading a CSV file in order to leverage the utility of an online tool. The tool, however, depends on consistency between the column headings of the CSV file being uploaded and the column headings in the existing database.

Yes, it would be infinitely easier to insist on some naming conventions, but until that day, here's what I came up with:

The user uploads their CSV file. The column headings are read and listed vertically with another field to the right where there's a pulldown featuring all of the possible fields corresponding to the table they're getting ready to upload their data to.

As so...

screenshot
The next page is designed to craft an insert statement based on the user's selection. I got it to work! Here's what I did:

$insert_statement = 'insert into twitter_test (';
	for($i=0; $i<=$_POST['column_count']; $i++)
	{
		if (isset($_POST['select_name_'.$i.'']) && $_POST['select_name_'.$i.'']=="")
		{
		header("location:csv_upload_error.php");
		exit();
		}
		else
		{
			$insert_statement.=$_POST['select_name_'.$i.''];
			if($i<$_POST['column_count'])
			{
				$insert_statement.=',';
			}
			else
			{
				$insert_statement.=')';
			}
		}
	}
	$insert_statement.=' VALUES (';
	for($i=0; $i<=$_POST['column_count']; $i++)
	{
	$insert_statement .='\'';
	$insert_statement .='$row['.$i.']';
	$insert_statement .='\'';
		if($i<$_POST['column_count'])
		{
			$insert_statement.=',';
		}
		else
		{
			$insert_statement.=')';
		}
	}

Open in new window


When you run this, it yields the following:

insert into twitter_test (actor_id,actor_display_name,posted_time,geo_coords_lat,geo_coords_lon,location_name) VALUES ('$row[0]','$row[1]','$row[2]','$row[3]','$row[4]','$row[5]')

Perfect! Except for one thing: The data going into the table isn't the data in the CSV file, rather it's literally "$row[0]" and so on.

So just when I think I'm crafting some clever syntax, I realize I'm not yet there.

So, how do I get line 26 ($insert_statement .='$row['.$i.']';) to be interpreted as data coming from my CSV file rather than, literally, $row[0]?

Bring it!
0
Comment
Question by:brucegust
6 Comments
 
LVL 11

Assisted Solution

by:tel2
tel2 earned 300 total points
ID: 40438746
Hi Bruce,

I barely know PHP, but:
- 'Single' quotes don't allow for interpolation (i.e. the contents of the quotes will be taken literally instead of interpretted).
- "Double" quotes do.
So try this for line 26:
    $insert_statement .= "$row[$i]";

However, in general, I think the ideal way to handle user-provided data (for security and the ability to handle any characters in the data), is to use placeholders:
    http://php.net/manual/en/pdo.prepared-statements.php
In your case, if all users use your form as intended then you may not need placeholders, but if you want to guard against a hacker from doing SQL injection (for example), by posting data without using your form, then I suggest you use placeholders.
0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 200 total points
ID: 40439001
First concept to try - always omit the quotes if you do not know with absolute certainty why you need to use them.  Background understanding is in this article.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_12241-Quotation-Marks-in-PHP.html

If you want to move forward on this with my help, please post the test data set so I can set up the examples that will show you how to write this code.  Nothing here is rocket science, but I'm very busy this week and do not have time to create test data for this problem.  Thanks!
0
 
LVL 9

Expert Comment

by:Brian Tao
ID: 40439071
Change line#26 in you "The next page" php file:
// it was: $insert_statement .='$row['.$i.']';
// change it to the following:
$insert_statement .= $row[$i];

Open in new window

0
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 11

Expert Comment

by:tel2
ID: 40439084
Good point, Ray.

Bruce,
taoyipai seems to have just coded what Ray suggested.

For brevity, I guess you could delete lines 25 and 27 and replace line 26 with:
      $insert_statement .= "'" . $row[$i] . "'";
or even this:
      $insert_statement .= "'$row[$i]'";
since I assume you want quotes to appear around the data in the final SQL string, right?  (Note the mix of single and double quotes in both examples above.)
0
 

Author Comment

by:brucegust
ID: 40440181
Did this:

$insert_statement .="$row[$i]";

...then made sure the code was located in a place where $row was being recognized and we were gold!

Thanks, folks!

And Ray, I did read through the documentation. Thanks!
0
 
LVL 11

Expert Comment

by:tel2
ID: 40440985
Thanks for the points, Bruce.

Although my 1st suggestion (which you seem to be using) should work, the quotes serve no purpose, so should be removed.

Did you try without the quotes, Bruce?

Or you can simplify your code by deleting lines 25 & 27 and using one of the options I gave in my last post.
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now