Simple = Saving an input value to MySQL DB?

Discussion in 'PHP' started by wvccboy, Jun 12, 2007.

  1. #1
    Sorry I'm not very familiar with MySQL yet and I need some help with a very basic thing.

    I need to create a PHP page that has 2 input boxes in a row, and have up to 100 columns. I need to be able to type the values in there, then click Submit, in which it will save the value to the MySQL database.

    From there I should be able to view the values row by row in PHPMyAdmin.

    Any ideas or tuts on how I can do this?

    Thanks
     
    wvccboy, Jun 12, 2007 IP
  2. krakjoe

    krakjoe Well-Known Member

    Messages:
    1,795
    Likes Received:
    141
    Best Answers:
    0
    Trophy Points:
    135
    #2
    
    <?
    define("MYSQL_HOSTNAME",	'localhost');
    define("MYSQL_USERNAME",	'root');
    define("MYSQL_PASSWORD",	'');
    define("MYSQL_DATABASE",	'simple');
    define("HTML_NUMINPUTS",	100 );
    
    $db = @mysql_connect( MYSQL_HOSTNAME, MYSQL_USERNAME, MYSQL_PASSWORD );
    
    if( !$db )
    {
    	die( sprintf( 'Cannot connect to mysql @ %s with %s and supplied password', MYSQL_HOSTNAME, MYSQL_USERNAME ) );
    }
    elseif( !mysql_select_db( MYSQL_DATABASE, $db ) )
    {
    	die( sprintf( 'Cannot select %s @ %s', MYSQL_DATABASE, MYSQL_HOSTNAME ) );	
    }
    elseif( $_POST )
    {
    	foreach( $_POST as $pcount => $data )
    	{
    		if( is_array( $data ) and trim( $data[1] ) and trim( $data[0] ) )
    		{
    			if( !mysql_query( sprintf( 'INSERT INTO `simple` VALUES("", "%s", "%s")', trim( $data[0] ), trim( $data[1] ) ) ) )
    			{
    				die( sprintf('Failed to execute query at %d', $pcount ) );
    			}	
    			$count++;
    		}
    	}
    	printf("Executed %d queries with success<br />", $count );
    }
    ?>
    <html>
    <head>
    <title></title>
    </head>
    <body>
    	<form action="" method="post">
    		<?
    		for( $i = 0; $i < HTML_NUMINPUTS; $i++ )
    		{
    			printf( "Name : <input type='text' name='%s[]'/>\n".
    					"Value : <input type='text' name='%s[]' \><br />", $i, $i );
    		}
    		?>
    		<input type="submit" value="Enter" />
    	</form>
    </body>
    </html>
    
    PHP:
    Thats an example of such operation, if you need more explanation say so, I'm off to bed....

    
    CREATE TABLE `simple` (
    `id` INT( 255 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
    `name` TEXT NOT NULL ,
    `value` TEXT NOT NULL
    ) ENGINE = MYISAM ;
    
    Code (markup):
    to create simple table
     
    krakjoe, Jun 12, 2007 IP
    wvccboy likes this.
  3. wvccboy

    wvccboy Notable Member

    Messages:
    2,632
    Likes Received:
    81
    Best Answers:
    1
    Trophy Points:
    250
    #3
    Yep this looks great to me, works too!

    Thanks man!
     
    wvccboy, Jun 12, 2007 IP