[SOLVED] Linking php code to a form & mysql database

This is a discussion on "[SOLVED] Linking php code to a form & mysql database" within the PHP Forum section. This forum, and the thread "[SOLVED] Linking php code to a form & mysql database are both part of the Program Your Website category.



Go Back   Webforumz.com > Main Forums > Program Your Website > PHP Forum

Notices


Reply
 
LinkBack Thread Tools
  #1 (permalink)  
Old Oct 8th, 2007, 14:32
Reputable Member
Join Date: Oct 2007
Location: Liverpool UK
Age: 29
Posts: 216
Thanks: 0
Thanked 0 Times in 0 Posts
[SOLVED] Linking php code to a form & mysql database

Hello.

I have a mysql database in the form of a sql file that i have created, i also have a php web page with a form, i need the details input by the form to go into my mysql database. The problem is i cannot seem to get the php code right. Below is a more detailed list of what i have managed and what i am having trouble with.

I have created the database and it works fine.

I have created the php web page with the relevant forms & it works fine.

I have successfully linked the database to my webpage with no problems (Dreamweaver regesters that the database is there)

I have designed the page in dreamweaver sc-3.

Basically i am utter rubbish at php code (But learning slowley).

Can anyone finnish the gaps i have in my code so it links to my database?? This way i will have a working example to look back on while i learn. The second problem i have is my page will no longer show when previed in a browser, the page apperars blank, its only this page that appears blank all my outher php pages relevant to the site still show in a browser no problem.

Some one please help me solve this problem, as its causing stress levels to raise.... Any help from you guys would be great.... Cheers

I can send the sql file & php file on request of help
Reply With Quote

  #2 (permalink)  
Old Oct 8th, 2007, 15:22
Rakuli's Avatar
SuperMember

SuperMember
Join Date: Sep 2007
Location: Australia
Age: 24
Posts: 956
Blog Entries: 2
Thanks: 0
Thanked 0 Times in 0 Posts
Re: Linking php code to a form & mysql database

Hi again longstand,

One thing i will say is that it will be a very good idea to start previewing your site by going to the url of your site rather then testing in dreamweaver. Say, you make some changes to file, go to http://www.example.com/index.php to test rather than preview in browser, as the testing can get a little messy in dreamweaver.

Can you post the code you have so far?
Last Blog Entry: The wannabe juggler's quest (Oct 27th, 2007)
Reply With Quote
  #3 (permalink)  
Old Oct 8th, 2007, 15:44
Reputable Member
Join Date: Oct 2007
Location: Liverpool UK
Age: 29
Posts: 216
Thanks: 0
Thanked 0 Times in 0 Posts
Re: Linking php code to a form & mysql database

Hey Rakuli!!!

PHP: Select all

<?php require_once('Connections/dbprofile.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function 
GetSQLValueString($theValue$theType$theDefinedValue ""$theNotDefinedValue ""
{
  
$theValue get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  
$theValue function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
  switch (
$theType) {
    case 
"text":
      
$theValue = ($theValue != "") ? "'" $theValue "'" "NULL";
      break;    
    case 
"long":
    case 
"int":
      
$theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case 
"double":
      
$theValue = ($theValue != "") ? "'" doubleval($theValue) . "'" "NULL";
      break;
    case 
"date":
      
$theValue = ($theValue != "") ? "'" $theValue "'" "NULL";
      break;
    case 
"defined":
      
$theValue = ($theValue != "") ? $theDefinedValue $theNotDefinedValue;
      break;
  }
  return 
$theValue;
}
}
$editFormAction $_SERVER['PHP_SELF'];
if (isset(
$_SERVER['QUERY_STRING'])) {
  
$editFormAction .= "?" htmlentities($_SERVER['QUERY_STRING']);
}

if (isset(
$_POST['select4'])) {
 
$month $_POST['select4'];
}
if (isset(
$_POST['select5'])) {
 
$day $_POST['select5'];
}
if (isset(
$_POST['select6'])) {
 
$year $_POST['select6'];
}
$dob $day."/".$month."/".$year;
if ((isset(
$_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
  
$insertSQL sprintf("INSERT INTO tbl_signup (sigiam, siginterested, sigfor, sigdob, sigpostcode, sigarea, sigemail, sigusername, sigpassword, siphonenumber, sisexmalefemale, signame, sigwhatturnsmeon, sigtellwhatlooklike) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, )",
                       
GetSQLValueString($_POST['sigiam'], "int"),
                       
GetSQLValueString($_POST['siginterested'], "int"),
                       
GetSQLValueString($_POST['sigfor'], "int"),
                       
GetSQLValueString($dob"text"), 
                       
GetSQLValueString($_POST['sigpostcode'], "text"),
                       
GetSQLValueString($_POST['sigarea'], "int"),
                       
GetSQLValueString($_POST['sigemail'], "text"),
                       
GetSQLValueString($_POST['sigusername'], "text"),
                       
GetSQLValueString($_POST['sigpassword'], "text"));
        
GetSQLValueString($_POST['siphonenumber'], "text"));
        
GetSQLValueString($_POST['sisexmalefemale'], "text"));
        
GetSQLValueString($_POST['signame'], "text"));
        
GetSQLValueString($_POST['sigwhatturnsmeon'], "text"));
        
GetSQLValueString($_POST['sigtellwhatlooklike'], "text"));
mysql_select_db($database_dbprofile$dbprofile);
  
$Result1 mysql_query($insertSQL$conndb) or die(mysql_error());
  
$insertGoTo "profile.php";
  if (isset(
$_SERVER['QUERY_STRING'])) {
    
$insertGoTo .= (strpos($insertGoTo'?')) ? "&" "?";
    
$insertGoTo .= $_SERVER['QUERY_STRING'];
  }
  
header(sprintf("Location: %s"$insertGoTo));
}
        
mysql_select_db($database_dbprofile$dbprofile);
$query_rsIam "SELECT * FROM tbl_iam ORDER BY imid ASC";
$rsIam mysql_query($query_rsIam$dbprofile) or die(mysql_error());
$row_rsIam mysql_fetch_assoc($rsIam);
$totalRows_rsIam mysql_num_rows($rsIam);
mysql_select_db($database_dbprofile$dbprofile);
$query_rsInterested "SELECT * FROM tbl_interested ORDER BY intid ASC";
$rsInterested mysql_query($query_rsInterested$dbprofile) or die(mysql_error());
$row_rsInterested mysql_fetch_assoc($rsInterested);
$totalRows_rsInterested mysql_num_rows($rsInterested);
mysql_select_db($database_dbprofile$dbprofile);
$query_rsFor "SELECT * FROM tbl_for ORDER BY forid ASC";
$rsFor mysql_query($query_rsFor$dbprofile) or die(mysql_error());
$row_rsFor mysql_fetch_assoc($rsFor);
$totalRows_rsFor mysql_num_rows($rsFor);
mysql_select_db($database_dbprofile$dbprofile);
$query_rsArea "SELECT * FROM tbl_area ORDER BY areaname ASC";
$rsArea mysql_query($query_rsArea$dbprofile) or die(mysql_error());
$row_rsArea mysql_fetch_assoc($rsArea);
$totalRows_rsArea mysql_num_rows($rsArea);        
        
<!
DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<
html xmlns="http://www.w3.org/1999/xhtmlxml:lang="en">
<
head>
<
title>Create Your profile</title>
<
meta http-equiv="content-type" content="text/html; charset=utf-8" />
<
link rel="stylesheet" href="css/1.csstype="text/cssmedia="screen,projection" />
<
style type="text/css">
<!--
.
style1 {color#FF00FF}
.style2 {color#FF3399}
.style3 {color#0474F1; }
.style4 {font-familyTahoma}
.
style5 {font-familyVerdanaArialHelveticasans-serif}
-->
</
style>
<
script src="file:///C|/webserver/Apache2/htdocs/Scripts/AC_RunActiveContent.jstype="text/javascript"></script> 
</head>
 
<body bgcolor="white">
  <div id="header">
 
   <h1 class="right">&nbsp;</h1>
   <h1>&nbsp;</h1>
 
</div>
 
 <ul id="nav">
   
   <li class="right"><input value="Search..." type="text" /></li>
   
   <li><a href="MainPage.php">MainPage</a></li>
   
   <li><a href="Login.php">LogIn</a></li>
   
   <li><a href="admin/Sign Up.php">SignUp</a></li>
   
   <li><a href="Chat.php">Chat</a></li>
 
</ul>
 
 <div class="clear" />
 
 <div id="content">
   <p>
        <?php
// Connect to database
$errmsg "";
if (! @
mysql_connect("localhost","trainee","abc123")) {
        
$errmsg "Cannot connect to database";
        }
@
mysql_select_db("test");
// First run ONLY - need to create table by uncommenting this
// Or with silent @ we can let it fail every sunsequent time ;-)
$q = <<<CREATE
create table pix (
    pid int primary key not null auto_increment,
    title text,
    imgdata longblob)
CREATE;
@
mysql_query($q);
// Insert any new image into database
if ($_REQUEST[completed] == 1) {
        
// Need to add - check for large upload. Otherwise the code
        // will just duplicate old file ;-)
        // ALSO - note that latest.img must be public write and in a
        // live appliaction should be in another (safe!) directory.
        
move_uploaded_file($_FILES['imagefile']['tmp_name'],"latest.img");
        
$instr fopen("latest.img","rb");
        
$image addslashes(fread($instr,filesize("latest.img")));
        if (
strlen($instr) < 149000) {
                
mysql_query ("insert into pix (title, imgdata) values (\"".
                
$_REQUEST[whatsit].
                
"\", \"".
                
$image.
                
"\")");
        } else {
                
$errmsg "Too large!";
        }
}
// Find out about latest image
$gotten = @mysql_query("select * from pix order by pid desc limit 1");
if (
$row = @mysql_fetch_assoc($gotten)) {
        
$title htmlspecialchars($row[title]);
        
$bytes $row[imgdata];
} else {
        
$errmsg "There is no image in the database yet";
        
$title "no database image available";
        
// Put up a picture of our training centre
        
$instr fopen("../wellimg/ctco.jpg","rb");
        
$bytes fread($instr,filesize("../wellimg/ctco.jpg"));
}
// If this is the image request, send out the image
if ($_REQUEST[gim] == 1) {
        
header("Content-type: image/jpeg");
        print 
$bytes;
        exit ();
        }
?>
   </p>
       
      <h2>Welcome To Your Profile!</h2>
      <font color="red">
      <?= $errmsg ?>
      </font>
      <center>
        <img src="?gim=1" width="144" /><br />
        <b>
        <?= $title ?>
      </center>
      <hr />
      <h2>Upload A Photo Of Yourself &amp; Enhance Your Responce From Other Members</h2>
      <form enctype="multipart/form-data" method="post">
        <p>
          <input type="hidden" name="MAX_FILE_SIZE" value="150000" />
          <input type="hidden" name="completed" value="1" />
          <span class="style2"><font face="Tahoma">Please choose an image to upload:</font></span>
          <input type="file" name="imagefile" />
        </p>
        <p> <br />
            <span class="style2"><font face="Tahoma">Please enter the title of that picture:</font></span>
            <input name="whatsit" />
        </p>
        <p> <br />
            <span class="style2"><font face="Tahoma">Click Submit To Upload Your Image:</font></span>
            <input type="submit" />
        </p>
      </form>
      <div align="center">
        <table width="828" height="557" border="0">
          <tr>
            <td height="45"><h2>To Contact &amp; Be Contacted By Other Members Please Create Your Profile Id</h2></td>
          </tr>
          <tr>
            <td height="504" valign="top"><p>&nbsp;</p>
                <table width="736" height="484" border="0">
                  <tr>
                    <td valign="top" class="style4"><div align="center">
                        <p class="style2">Please Input Your First Name (no capitals)</p>
                      <form id="form1" method="post" action="">
                          <span class="style2">
                          <label>
                          <input type="text" name="name" id="name" />
                          </label>
                          </span>
                      </form>
                      <p class="style2">Please Input Your Age (digits only)</p>
                      <form id="form2" method="post" action="">
                          <span class="style2">
                          <label>
                          <input type="text" name="age" id="age" />
                          </label>
                          </span>
                        <p class="style2">Please Input Your Sex (male\female no capitals)</p>
                        <p>
                            <span class="style2">
                            <label>
                            <input type="text" name="sex" id="sex" />
                            </label>
                          </span></p>
                        <p class="style2">Please Input Your Phone number (optional)</p>
                        <p class="style2">Please Input Your User Name </p>
                        <p class="style2">(user name must be same as your login name)</p>
                        <p>
                            <span class="style2">
                            <label>
                            <input type="text" name="username" id="username" />
                            </label>
                          </span></p>
                        <p class="style2">Please Input Your Password</p>
                        <p class="style2">(password must be the same as your login password)</p>
                        <p>
                            <span class="style2">
                            <label>
                            <input type="text" name="password" id="password" />
                            </label>
                          </span></p>
                        <p>
                            <label></label>
                            <span class="style2">Please Describe Your Hobbies &amp; Interests</span></p>
                        <p>
                          <textarea name="hobbies" id="hobbies" cols="45" rows="5"></textarea>
                        </p>
                      </form>
                      <p class="style2">Please Input Your Email Address</p>
                      <form id="form9" method="post" action="">
                        <p>
                          <label>
                            <input type="text" name="email" id="email" />
                          </label>
                        </p>
                      </form>
                      <p class="style2">&nbsp;</p>
                    </div></td>
                    <td valign="top" class="style4"><div align="center">
                        <p class="style2"><span class="style2">Describe What Turns You On &amp; Why </span></p>
                      <form action="" method="post" class="style3" id="form3">
                          <span class="style2">
                          <label></label>
                        </span>
                      </form>
                      <form action="" method="post" class="style3" id="form4">
                          <span class="style2">
                          <label>
                          <textarea name="turnon" id="turnon" cols="45" rows="5"></textarea>
                          </label>
                          </span>
                      </form>
                      <form action="" method="post" class="style3" id="form5">
                          <span class="style2">
                          <label>Please Tell Us What You Look Like<br />
                          <br />
                          <textarea name="looklike" id="looklike" cols="45" rows="5"></textarea>
                          <br />
                          <br />
                          </label>
                          </span>
                        <p class="style2">I Am</p>
                        <p>
                            <span class="style2">
                            <label>
                            <select name="iam" id="iam">
                              <option>Man</option>
                              <option>Women</option>
                              <option>Bi Couple</option>
                              <option>Group</option>
                            </select>
                            </label>
                          </span></p>
                        <p>Interested In</p>
                        <p>
                          <label>
                          <select name="interestedin" id="interestedin">
                            <option>Man</option>
                            <option>Women</option>
                            <option>By Couple</option>
                            <option>Group</option>
                          </select>
                          </label>
                        </p>
                        <p class="style2">Looking For (Sexual Interests)</p>
                        <p>
                            <span class="style2">
                            <label>
                            <select name="sexsubject" id="sexsubject">
                              <option>Anythink</option>
                              <option>Group Sex</option>
                              <option>1 On 1 Sex</option>
                              <option>Sexual Discreet Ongoing Partner</option>
                              <option>Erotic Chat</option>
                              <option>Email Swopping</option>
                              <option>Photo Swopping</option>
                            </select>
                            </label>
                          </span></p>
                      </form>
                      <p class="style2">Please Input Your Area</p>
                      <form action="" method="post" class="style3" id="form6">
                          <span class="style2">
                          <label>
                          <select name="area" id="area">
                          </select>
                          </label>
                          </span>
                      </form>
                      <p class="style2">Please Input Your Postcode</p>
                      <p class="style2">(no capital letters) </p>
                      <form action="" method="post" class="style3" id="form7">
                          <span class="style2">
                          <label>
                          <input type="text" name="postcode" id="postcode" />
                          </label>
                          </span>
                      </form>
                      <form id="form8" method="post" action="">
                        <p>
                          <label>
                            <input type="submit" name="button" id="button" value="Submit" />
                          </label>
                        </p>
                      </form>
                      <p class="style3">&nbsp;</p>
                      <p>&nbsp;</p>
                      <p>&nbsp;</p>
                    </div></td>
                  </tr>
                </table>
              <h2 align="center" class="style5">Remember this is your space so be accurate with you data to ensure results!</h2>
              <p>&nbsp;</p></td>
          </tr>
        </table>
        <br />
      </div>
      <hr />
<p>&nbsp;</p>
   <p>&nbsp;</p>
       
<p>&nbsp;</p>
    
          
   </div>
<div id="footer">
     
       <p>Site Design by <a href="http://www.sixshootermedia.com">AJL Online Services Business Developement Specialists</a>.<br />
                              <!-- you can delete below here -->
© All  copyrights reserved.</p>
     
</div>
</body>
</html>
Reply With Quote
  #4 (permalink)  
Old Oct 8th, 2007, 15:45
Reputable Member
Join Date: Oct 2007
Location: Liverpool UK
Age: 29
Posts: 216
Thanks: 0
Thanked 0 Times in 0 Posts
Re: Linking php code to a form & mysql database

Here's my database

Code: Select all
CREATE DATABASE IF NOT EXISTS dbprofile;
USE dbprofile;
CREATE TABLE `images` (
`img` INT NOT NULL AUTO_INCREMENT ,
`data` LONGTEXT NOT NULL ,
PRIMARY KEY ( `img` ) 
);
CREATE TABLE `tbl_area` (
  `areaid` int(10) unsigned NOT NULL auto_increment,
  `areaname` varchar(45) NOT NULL,
  PRIMARY KEY  (`areaid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `tbl_area` (`areaid`,`areaname`) VALUES 
 (1,'England-Bath Avon'),
 (2,'England-Bedforshire');
CREATE TABLE `tbl_for` (
  `forid` tinyint(3) unsigned NOT NULL auto_increment,
  `forname` varchar(45) NOT NULL,
  PRIMARY KEY  (`forid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `tbl_for` (`forid`,`forname`) VALUES 
 (1,'PhoneFantasies\\Emal\\Erotic-Chat'),
 (2,'Discreet Relationship (Sex Partner)');
CREATE TABLE `tbl_iam` (
  `imid` tinyint(3) unsigned NOT NULL auto_increment,
  `imname` varchar(45) NOT NULL,
  PRIMARY KEY  (`imid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `tbl_iam` (`imid`,`imname`) VALUES 
 (1,'Man'),
 (2,'Woman'),
 (3,'Couple (Man/Woman)');
CREATE TABLE `tbl_interested` (
  `intid` tinyint(3) unsigned NOT NULL auto_increment,
  `intname` varchar(45) NOT NULL,
  PRIMARY KEY  (`intid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `tbl_interested` (`intid`,`intname`) VALUES 
 (1,'A Man'),
 (2,'A Woman');
CREATE TABLE `tbl_signup` (
  `sigid` int(10) unsigned NOT NULL auto_increment,
  `sigiam` tinyint(3) unsigned NOT NULL,
  `siginterested` tinyint(3) unsigned NOT NULL,
  `sigfor` tinyint(3) unsigned NOT NULL,
  `sigage` varchar(10) NOT NULL,
  `sigpostcode` varchar(10) NOT NULL,
  `sigarea` int(10) unsigned NOT NULL,
  `sigemail` varchar(45) NOT NULL,
  `sigusername` varchar(45) NOT NULL,
  `sigpassword` varchar(12) NOT NULL,
  `sigphonenumber` varchar(25) NOT NULL,
  `sigsexmalefemale` varchar(6) NOT NULL,
  `signame` varchar(20) NOT NULL,
  `sigwhatturnsmeon` varchar(150) NOT NULL,
  `sigtellwhatlooklike` varchar(150) NOT NULL,
  `sigdatejoined` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
  PRIMARY KEY  (`sigid`),
  KEY `FK_tbl_signup_1` (`sigiam`),
  KEY `FK_tbl_signup_2` (`siginterested`),
  KEY `FK_tbl_signup_3` (`sigfor`),
  KEY `FK_tbl_signup_4` (`sigarea`),
  CONSTRAINT `FK_tbl_signup_1` FOREIGN KEY (`sigiam`) REFERENCES `tbl_iam` (`imid`) ON UPDATE CASCADE,
  CONSTRAINT `FK_tbl_signup_2` FOREIGN KEY (`siginterested`) REFERENCES `tbl_interested` (`intid`) ON UPDATE CASCADE,
  CONSTRAINT `FK_tbl_signup_3` FOREIGN KEY (`sigfor`) REFERENCES `tbl_for` (`forid`) ON UPDATE CASCADE,
  CONSTRAINT `FK_tbl_signup_4` FOREIGN KEY (`sigarea`) REFERENCES `tbl_area` (`areaid`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Last edited by Rakuli; Oct 9th, 2007 at 11:18. Reason: Adding some code tags to assist readability
Reply With Quote
  #5 (permalink)  
Old Oct 9th, 2007, 10:34
Rakuli's Avatar
SuperMember

SuperMember
Join Date: Sep 2007
Location: Australia
Age: 24
Posts: 956
Blog Entries: 2
Thanks: 0
Thanked 0 Times in 0 Posts
Re: Linking php code to a form & mysql database

That code is a bit of a mess

It's no loading cause the php is broken.

It think this should do what you want when you test it outside of dreamweaver.

PHP: Select all

<?php

require_once('Connections/conndb.php'); 
$editFormAction $_SERVER['PHP_SELF'];
if (isset(
$_SERVER['QUERY_STRING'])) {
  
$editFormAction .= "?" htmlentities($_SERVER['QUERY_STRING']);
}
mysql_select_db($database_dbprofile$dbprofile) or die("oh no oh no, the database could't be selected! It's all going wrong");

// Okay, your submit button is named "button" so we check that this has been clicked, if it has we can start the form processing 

if (!empty($_POST['button'])) // !empty is a double check, checking for existence AND a value other than false, NULL, 0 or "" 

    
// I am unsure about your magic quotes setting so I'll use this to strip slashes and escape correctly 
     
    
$needStrip get_magic_quotes_gpc(); 
     
    
// Okay, let's assume that all form values are going into the same mySQL table 
    // Create an array of the form fields -- using the form code you have below, it looks like this 
     
    
$fields = array(); 
     
    
// The array key is the name of the form element 
     
    
$fields['name'] = array('type'        => 's',       // The type of value - we'll use s for string or n for number (hard for a form to be anything else) 
                               
'required'    => true,    // Is the field *required*, we will stop the script if it's not set if this is true 
                               
'column'        => 'signame'    // The mysql data column where the value will go 
                               
); 
    
$fields['sex'] = array('type'        => 's'
                               
'required'    => true
                               
'column'        => 'sigsexmalefemale' 
                               
); 
    
$fields['username'] = array('type'        => 's'
                               
'required'    => true
                               
'column'        => 'sigusername' 
                               
);
    
$fields