Jump to content

INSERT INTO Question?


antfuentes87

Recommended Posts

I was trying to have the below function insert the data just into one row, but instead it is doing (see image below). No idea why it is doing that, if anyone knows and could tell me how to fix it. It would be much appreciated.

 

function set($table){
$result = mysql_query("SELECT * FROM $table");
	$i = 0;
	while ($i < mysql_num_fields($result)) {
		$meta = mysql_fetch_field($result, $i);    
	 		$name = $meta->name;
			$nameB = $_POST[$name];
				if($name <> 'id'){
					$q = "INSERT INTO $table($name) VALUES ('".$nameB."')";
						mysql_query($q);
				}
		$i++;
	}
}

post-118421-13482403631746_thumb.jpg

Link to comment
https://forums.phpfreaks.com/topic/266056-insert-into-question/
Share on other sites

Try this: UN-TESTED!

<?php //syntax highlighting.
function set($table) {
$result = mysql_query("SHOW COLUMNS FROM $table"); //no need to select all data, just get the column info.
while ($row = mysql_fetch_assoc($result)) { //loop through the data resource.
	$name = $row['Field']; //pull out the field name.
	$nameB = $_POST[$name]; //get the form data that matches the field name.
	if(strtolower($name) <> 'id'){ //if the field is not 'id', case sensitive here. might want to do a strtolower() on the field name.
		$columns[] = $name; //store the columns in an array.
		$values[] = $nameB; //store the values in an array.  Indexes will match the column name.
	} //close if.	
}	//close while;
$q = "INSERT INTO $table(" . implode(',',$columns) . ") VALUES ('" . implode('\',\'',$values) . "')"; //implode the data into your query string.
		mysql_query($q) or trigger_error('(' . $q . ') has encountered the error: <br />' . mysql_error()); //run the query, trigger an error if it fails.
} //close function.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.