Jump to content

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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.