Avatar of mSprout
mSprout
 asked on

Have a MySQL Database, PHP Form isn't working, but connection is Successful

I created a PHP form, and I would like to record the results to a database. When I test the connection file on its own it is successful. When I attempt to include the file with the connection instead, the form does not save the information? Am I missing a step here?

<body onload="myUploadFunction()">
  <!-- Primary Page Layout
  –––––––––––––––––––––––––––––––––––––––––––––––––– -->
  <div class="container">
    <div class="row">
      <div class="one column" style="margin-top: 2%">


      <?php
         if(isset($_POST['add'])) {
         require '*********.php';
            
            if(! get_magic_quotes_gpc() ) {
               $PTitle = addslashes ($_POST['PTitle']);
               $PContent = addslashes ($_POST['PContent']);
            }else {
               $PTitle = $_POST['$PTitle'];
               $PContent = $_POST['PContent'];
            }
            
            $PType = $_POST['PType'];
            $PDisplay = $_POST['PDisplay'];
            $POrder = $_POST['POrder'];
            
               
            mysql_select_db('**************');
            $retval = mysql_query( $sql, $conn );
            
            if(! $retval ) {
               die('Could not enter data: ' . mysql_error());
            }
            
            echo "Entered data successfully\n";
            
            mysql_close($conn);
         }else {
            ?>
            

         <form method = "post" action = "dor.php">
  <fieldset>
    <legend>Create A Page</legend>
    Title: <input type="text" name="PTitle"> Page Type: <select name="PType">
  <option value="home">Home</option>  
  <option value="event">Event</option>
  <option value="vehicle">Vehicle</option>
  <option value="testimonial">Testimonial</option>
  <option value="special">Special</option>
  <option value="about">About</option>
  <option value="quote">Quote</option>
</select> Page Order: <input type="text" name="POrder"> 
  <textarea id="PContent">Please enter text and images only. Images will automatically be formatted based on the number of images included.

</textarea>  
<br>
    <select name="PDisplay">
  <option value="False">Hide</option>  
  <option value="True">Show</option>
</select><input type="submit" id="add" value="Save">
  </fieldset>
Upload New Image:
<input type="file" id="myFile" multiple size="50" onchange="myUploadFunction()">


<p id="demo"></p>
    
<script>
function myUploadFunction(){
    var x = document.getElementById("myFile");
    var txt = "";
    if ('files' in x) {
        if (x.files.length == 0) {
            txt = "Select one or more files.";
        } else {
            for (var i = 0; i < x.files.length; i++) {
                txt += "<br><strong>" + (i+1) + ". file</strong><br>";
                var file = x.files[i];
                if ('name' in file) {
                    txt += "name: " + file.name + "<br>";
                }
                if ('size' in file) {
                    txt += "size: " + file.size + " bytes <br>";
                }
            }
        }
    } 
    else {
        if (x.value == "") {
            txt += "Select one or more files.";
        } else {
            txt += "The files property is not supported by your browser!";
            txt  += "<br>The path of the selected file: " + x.value; // If the browser does not support the files property, it will return the path of the selected file instead. 
        }
    }
    document.getElementById("demo").innerHTML = txt;
}
</script>

<p><strong>Tip:</strong> Use the Control or the Shift key to select multiple files.</p>

Set Page Image:
Image: <input type="text" name="ImageLink">

</form>

     <?php
         }
      ?>
   
      </div>
    </div>
  </div>
<!-- End Document
  –––––––––––––––––––––––––––––––––––––––––––––––––– -->
</body>
</html>

Open in new window

PHPWeb DevelopmentMySQL Server

Avatar of undefined
Last Comment
mSprout

8/22/2022 - Mon
SOLUTION
Ray Paseur

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
arnold

Besides what was already pointed out by Ray Paseur; You have require .php only if add is within the submitted form, but your processing continues including trying to access DB.
Presumably require php gas the global $conn set to the connection.

See if you move the require directive above the check for form add.
The posted data does not seem to have an early exit but include a close connection directive.

When executing you are not checking their status which could help when outputting errors when encountered, I.e. On the mysql_select_db an error that a connection is not present ..... Etc.
Chris Stanyon

Your code is expecting a POST key called 'add' but your form doesn't contain one. The POST variables are named according to the name attribute. You're using the id attribute:

<input type="submit" id="add" value="Save">

should be

<input type="submit" name="add" value="Save">
arnold

Great catch, Chris.
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
mSprout

ASKER
I'm not sure how to better ask my question, since my answers don't seem to be helping. Please bear with me.

Ok, lets try issue by issue.

Issue #1, switching to MySQLi @ray, I will pass on E E Gigs, as I am debating whether or not Experts Exchange is worth my continued membership. If I cannot get this question answered (should be simple) I will close my account. Once the connection issue is resolved, I can do all the other stuff (Javascript, SQL Queries, HTML). LoL.

That being said, here is the updated, still not functional code...

The Connection information file

<?php

$mysqli = new mysqli('localhost', '*****', '**********', '********');


if($db->connect_errno > 0){
    die('Unable to connect to database [' . $db->connect_error . ']');


} else {
    echo "Have a good night!";
}


error_reporting(E_ALL);


?>

Open in new window


This code runs pretty good, and returns have a goodnight. The next step would then be inserting, or selecting information from the database. Based on this article:

http://markonphp.com/simple-select-mysqli-php/

I came up with the following updated code (for now I am going to ignore include/require)

<?php

$conn = new mysqli('localhost', '********', '***********', '*********');


if($db->connect_errno > 0){
    die('Unable to connect to database [' . $db->connect_error . ']');


} else {
    echo "Have a good night!";
}


error_reporting(E_ALL);

$query = "SELECT id AS txt FROM `Pages`";
$result = $conn->query($query);
 
if($result === false) {
  trigger_error('Wrong SQL: ' . $query . ' Error: ' . $conn->error, E_USER_ERROR);
} else {
	$result->data_seek(0);
	while($row = $result->fetch_assoc()){
	    echo $row['txt'] . '<br>';
	}  
}

$result->free();
$conn->close();

?>

Open in new window


However the new error I get is as follows:

Have a good night!
Warning: mysqli::query(): Couldn't fetch mysqli in ***** on line 18

Fatal error: Call to a member function data_seek() on a non-object in ****** on line 23
arnold

The suggestion to switch to using mysqli is something to consider over time, Chris pointed out how/what you need to fo to address the issue for which you opened this query. You can not transition the connection to mysqli while the remaining code is remaining....
I tend to do it myself pointing out something that should be consider even when it is directly an issue in the question. But might be in the future....



In your original code, line 59 make sure you have either submit gave the name add or add an input even hidden that has name=add to match your outer conditional test.
Try adding this above line 59 of your original code.
<input type=hidden name=add value=process>
..
mSprout

ASKER
Hello Arnold,

I updated the $db to be $mysqli, and now the connection isn't working, but giving the correct error. I don't think I am at line 59 yet.
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
arnold

Transitioning to mysqli is something to consider but as you noted is not the issue. Chris pointed out that your conditional test for add to be set, but your references add as an ID of submit versus name=add.

Create a copy of your original, output as comments/or displayed  the parameters received. This way you can see the parameters received and assess whether the info you are looking for is met by data received.
mSprout

ASKER
<?php

$conn = new mysqli('localhost', 'nnn', 'nnn', 'nnn');


if($conn->connect_errno > 0){
    die('Unable to connect to database [' . $conn->connect_error . ']');


} else {
    echo "Have a good night!";
}


error_reporting(E_ALL);

$query = "SELECT id AS txt FROM `Pages`";
$result = $conn->query($query);
 
if($result === false) {
  trigger_error('Wrong SQL: ' . $query . ' Error: ' . $conn->error, E_USER_ERROR);
} else {
      $result->data_seek(0);
      while($row = $result->fetch_assoc()){
          echo $row['txt'] . '<br>';
      }  
}

$result->free();
$conn->close();

?>
mSprout

ASKER
Error: Unable to connect to database [Access denied for user 'nnn'@'localhost' (using password: YES)]
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
arnold

The issue is as follows using distinguishable items in their respective places to convey the point.
$conn=new mysqli('localhost','username','password','database');

Does username@localhost with password have access to database

On the command line in the shell, run
mysql -u username -p database
Does it work? Or do you get a similar error, access denied?
Check your user account definition
Non admin user requires that username@host, password  and database to match to gain access.
The issue might be that you have special characters that throws it off.
Try
$username='username';
$password='password';
$db='database';

$conn=new mysqli("localhost",$username,$password,$database);
mSprout

ASKER
Can't use shell/commandline. On a shared host, and putty won't allow me to type a password, only user name.
arnold

Do you have access to phpmyadmin? Check what credentials you use to login into it versus the php directives you are setting.
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
mSprout

ASKER
Yes, I do. My credentials are correct.
arnold

Definition of the user might be at issue,

Quick guide to mysqli...

http://php.net/manual/en/mysqli.quickstart.connections.php
Try adding a port,3306 on the end of your mysqli set in the event you can not access via UNIX socket.
Try 127.0.0.1 with port.  Authentication may require username/password and database to gain access.
See if you can besides getting the error message to also get the numerical error.
mSprout

ASKER
Failed to connect to MySQL: (1045) Access denied for user 'nnn'@'localhost' (using password: YES) Failed to connect to MySQL: (1045) Access denied for user 'nnn'@'localhost' (using password: YES)

It's better, at least there is the 1045 to work with now?
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
Chris Stanyon

Right - let's work through this one step at a time.

Firstly, the DB Connection. This is how you handle the connection to your database:

<?php 
error_reporting(E_ALL);
ini_set('display_errors', 1);
mysqli_report(MYSQLI_REPORT_STRICT);
 
$hostname = 'localhost';
$username = 'username';
$password = 'password';
$database = "dbName";

try {
     $db = new mysqli($hostname, $username, $password, $database);
} catch (Exception $e ) {
     echo "DB Error: " . $e->getMessage();
     exit;
}
?>
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Chris Stanyon</title>
    </head>
    <body>
        <h1>Connected</h1>
    </body>
</html>

Open in new window

Try this code and don't move on to the next step until you know this is working.  If it fails, you'll get an error. If it works, you'll see 'Connected'
Mustafa bezi

hello my dear mSprout:
I have tested your code successfully on my pc , i create database : nnn, with user: root , and password empty. i have created pages table too
Everything had gone well..!!

I think for this problem to note the following:
1-  you must compile PHP with support for the mysqli extension.
2- The mysqli extension is designed to work with the version 4.1.3 or above of MySQL.
3- write exactly the same name your table "pages" in your code.

If the problem is not solved yet, please see the link
http://stackoverflow.com/questions/6445917/connect-failed-access-denied-for-user-rootlocalhost-using-password-yes
mSprout

ASKER
Chris, I get the same error, but with the numbers removed. DB Error: Access denied for user 'Huntress'@'localhost' (using password: YES)
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Chris Stanyon

OK. Then as the error suggests, you have a permissions issue. Nothing we can do to help with that really - you'll need to make sure you username and password are valid, and that you have access to the relevant database.

You may have access to the database via some control panel such as PHPMyAdmin where you can reset permissions. You may need to talk to your hosting provider.
Ray Paseur

Failed to connect to MySQL: (1045) Access denied for user 'nnn'@'localhost' (using password: YES)
If you're using a shared hosting service, the service probably has a customer support organization.  They have been through this part of the issue before, and probably have canned instructions to help you get over this particular hump.  Databases have users, and users have username, password, permissions.  All of these have to line up correctly before you can run a query.  MySQL and MySQLi are notoriously bad about their error messages, giving ambiguous and confusing responses, so don't feel bad if this is not working yet -- we all go through this stuff at some point.  I would ask the hosting company for help, then come back once you're able to connect and run a basic query like SELECT 2+2.
ASKER CERTIFIED SOLUTION
arnold

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
mSprout

ASKER
Ok, surprise surprise... The issue with the connection was coming from an illegal character in the autogenerated password. That being said, connection is established, and now I am trying to troubleshoot inserting/updating/deleting the rows in the database. For some reason the page is now blank???

Here is what I have:

<!DOCTYPE html>
<html lang="en">
<head>

  <!-- Basic Page Needs
  –––––––––––––––––––––––––––––––––––––––––––––––––– -->
  <meta charset="utf-8">
  <title>Your page title here :)</title>
  <meta name="description" content="">
  <meta name="author" content="">

  <!-- Mobile Specific Metas
  –––––––––––––––––––––––––––––––––––––––––––––––––– -->
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <!-- FONT
  –––––––––––––––––––––––––––––––––––––––––––––––––– -->
  <link href="//fonts.googleapis.com/css?family=Raleway:400,300,600" rel="stylesheet" type="text/css">

  <!-- CSS
  –––––––––––––––––––––––––––––––––––––––––––––––––– -->
  <link rel="stylesheet" href="css/normalize.css">
  <link rel="stylesheet" href="css/skeleton.css">

<script src='//cdn.tinymce.com/4/tinymce.min.js'></script>
  <script>
  tinymce.init({
    selector: '#PContent',
    theme: 'modern',
    width: 600,
    height: 300,
    plugins: [
      'advlist autolink link image lists charmap print preview hr anchor pagebreak spellchecker',
      'searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking',
      'save table contextmenu directionality emoticons template paste textcolor'
    ],
    content_css: 'css/content.css',
    toolbar: 'insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image | print preview media fullpage | forecolor backcolor emoticons'
 
  });
  </script>


  <!-- Favicon
  –––––––––––––––––––––––––––––––––––––––––––––––––– -->
  <link rel="icon" type="image/png" href="images/favicon.png">


</head>
<body onload="myUploadFunction()">
  <!-- Primary Page Layout
  –––––––––––––––––––––––––––––––––––––––––––––––––– -->
  <div class="container">
    <div class="row">
      <div class="one column" style="margin-top: 2%">


      <?php

 // STEP 1. Get the connection
            require 'dor.php';

        // STEP 0. Are we getting form submission or should we show the form's field for filling?
         if(isset($_POST['add'])) {
          
            
            // STEP 2. Validate user's input
        //    $PType = $_POST['PType'];
         //   $PDisplay = $_POST['PDisplay'];
         //   $POrder = $_POST['POrder'];
            
            // STEP 3. Properly encode user input for SQL
            




            
            // STEP 4. Construct the SQL query



$sql = $mysqli->prepare("INSERT INTO Pages(ID,PTitle, 
PType,PContent,PDisplay,POrder) VALUES (?, ?, ?, ?, ?, ?)");
$sql->bind_param('sssdi', $_POST['ID'], 
$_POST['PTitle'],
$_POST['PType'],
$_POST['PContent'],
$_POST['PDisplay']);
$_POST['POrder']);
$sql->execute();
$newId = $stmt->insert_id;
$sql->close();

            
            //$retval = mysql_query( $sql, $mysqli ); // procedural version

            $retval = $mysqli->query($sql);





            
            // STEP 5. Execute the SQL query
            if(! $retval ) {
                // STEP 5.1 Deal with insuccess
               die('Could not enter data: ' . $mysqli->error);
            }
            
            // STEP 5.2 Deal with success
            echo "Entered data successfully\n";
            
            // STEP 6. We're done, close the connection
            //mysqli_close($mysqli);
            $mysqli->close();
         }
   // user is editing stuff:
   elseif(isset($_POST['edit']))
   {
   	
$sql = $mysqli->prepare("Update Pages(ID,PTitle, 
PType,PContent,PDisplay,POrder) VALUES (?, ?, ?, ?, ?, ?)");
$sql->bind_param('sssdi', $_POST['ID'], 
$_POST['PTitle'],
$_POST['PType'],
$_POST['PContent'],
$_POST['PDisplay']);
$_POST['POrder']);
$sql->execute();
$newId = $stmt->update_id;
$sql->close();

            
            //$retval = mysql_query( $sql, $mysqli ); // procedural version

            $retval = $mysqli->query($sql);





            
            // STEP 5. Execute the SQL query
            if(! $retval ) {
                // STEP 5.1 Deal with insuccess
               die('Could not enter data: ' . $mysqli->error);
            }
            
            // STEP 5.2 Deal with success
            echo "Entered data successfully\n";
            
            // STEP 6. We're done, close the connection
            //mysqli_close($mysqli);
            $mysqli->close();

   	$display_button_valu = "delete";
   	$display_button_name = "delete";
   	// 4: set a confirmation message:
   	$msg = "Your stuff has been EDITED";
   }
   // user is deleting stuff:
   elseif(isset($_POST['delete']))
   {
  

$sql = "DELETE FROM Pages WHERE id=$_POST['ID']";


   	$display_button_valu = "add";
   	$display_button_name = "add";
   	// 4: set a confirmation message:
   	$msg = "Your stuff has been DELETED";
   }
   // user is doing nothing, it's his/her first time (ooer)
   else
   {
   	// 1: set variable that displays "add" button:

            
            // STEP 2. Validate user's input
         //   $PType = $_POST['PType'];
         //   $PDisplay = $_POST['PDisplay'];
        //    $POrder = $_POST['POrder'];
         //   
            // STEP 3. Properly encode user input for SQL
            
            
            // STEP 4. Construct the SQL query
            




//$sql = $mysqli->prepare("INSERT INTO Pages(ID,PTitle, 
PType,PContent,PDisplay,POrder) VALUES (?, ?, ?, ?, ?, ?)");
$stmt->bind_param('sssdi', $_POST['ID'], 
$_POST['PTitle'],
$_POST['PType'],
$_POST['PContent'],
$_POST['PDisplay']);
$_POST['POrder']);
$stmt->execute();
$newId = $stmt->insert_id;
$stmt->close();



            //$retval = mysql_query( $sql, $mysqli ); // procedural version

            $retval = $mysqli->query($sql);




            
            // STEP 5. Execute the SQL query
            if(! $retval ) {
                // STEP 5.1 Deal with insuccess
               die('Could not enter data: ' . $mysqli->error);
            }
            
            // STEP 5.2 Deal with success
            echo "Entered data successfully\n";
            
            // STEP 6. We're done, close the connection
            //mysqli_close($mysqli);
            $mysqli->close();

   	//$display_button_valu = "add";//
   	//$display_button_name = "add";//
   	// 2: set a welcome message:
   	$msg = "Welcome. Please add some stuff in the form below";
   }
   
   ?>
   <!-- display your message here -->
   <p><?=$msg?></p>
   
//<form method = "post" action = "adm.php">
   <form action="<?=$_SERVER['PHP_SELF']?>" method="post">
   <!-- create your form here -->
   

  <fieldset>
    <legend>Create A Page</legend>
    Title: <input type="text" name="PTitle">
    Page Type: <select name="PType">
  <option value="Home">Home</option>  
  <option value="Event">Event</option>
  <option value="Vehicle">Vehicle</option>
  <option value="Testimonial">Testimonial</option>
  <option value="Special">Special</option>
  <option value="About">About</option>
  <option value="Quote">Quote</option>
</select> Page Order: <input type="text" name="POrder"> 
  <textarea id="PContent">Please enter text and images only. Images will automatically be formatted based on the number of images included.

</textarea>  
<br>
    <select name="PDisplay">
  <option value="False">Hide</option>  
  <option value="True">Show</option>
</select><input type="submit" id="add" value="Save">
  </fieldset>
Upload New Image:
<input type="file" id="myFile" multiple size="50" onchange="myUploadFunction()">


<p id="demo"></p>
    
<script>
function myUploadFunction(){
    var x = document.getElementById("myFile");
    var txt = "";
    if ('files' in x) {
        if (x.files.length == 0) {
            txt = "Select one or more files.";
        } else {
            for (var i = 0; i < x.files.length; i++) {
                txt += "<br><strong>" + (i+1) + ". file</strong><br>";
                var file = x.files[i];
                if ('name' in file) {
                    txt += "name: " + file.name + "<br>";
                }
                if ('size' in file) {
                    txt += "size: " + file.size + " bytes <br>";
                }
            }
        }
    } 
    else {
        if (x.value == "") {
            txt += "Select one or more files.";
        } else {
            txt += "The files property is not supported by your browser!";
            txt  += "<br>The path of the selected file: " + x.value; // If the browser does not support the files property, it will return the path of the selected file instead. 
        }
    }
    document.getElementById("demo").innerHTML = txt;
}
</script>

<p><strong>Tip:</strong> Use the Control or the Shift key to select multiple files.</p>

Set Page Image:
Image: <input type="text" name="ImageLink">

   <!-- display your button here -->
   <input type="submit" name="<?=$display_button_name?>" value="<?=$display_button_valu?>" />
   </form>

     
      ?>
   
      </div>
    </div>
  </div>
<!-- End Document
  –––––––––––––––––––––––––––––––––––––––––––––––––– -->
</body>
</html>

Open in new window

All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
Ray Paseur

If you're new to PHP application development and want some good learning resources, this article can help you stay on firm ground.
https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html

Best of luck with your project, ~Ray
SOLUTION
Chris Stanyon

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
mSprout

ASKER
I already got the add working!!! Thanks for the error reporting tip.
Chris Stanyon

OK. Quite surprised by that. There are so many problems with your code. You can carry on trying to be lucky with your coding or you could take a step back and do it properly. Your call really.

Few other pointers to get you on your way:

Your INSERT query tries to insert an ID which doesn't seem to exist in your form
Your try to call insert_id on a non-existent statement (several times)
You call execute() on your statement and then straight after you call query() on the connection (several times)
Your UPDATE query syntax is invalid
You're running a DELETE query with direct user input (a BIG No-No!)
You seem to be running the INSERT query twice
Your form has 2 submit buttons
Your form is not multipart, so the file won't upload
Your form doesn't have an ID field
You're using PHP echo shorttags (may be a problem)

You're a long way from this being a functional robust script. At some point you'll have to decide whether you're happy coding like this, or whether you want to learn better techniques.

Good luck with it
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
mSprout

ASKER
That was my initial attempt, after kind of being tired... The only way for me to improve, is by asking questions, and that is why I am here. Here is the code I have now. I think I have already resolved most of those errors you mentioned?  I am going step by step, but there is some code I copied and pasted and edited that was bad, and the file upload is just a placeholder currently.  

Sometimes it is hard for me to explain, and I think if I show all the code it will help people understand what I want. Final error now is

Fatal error: Call to a member function query() on a non-object in /home/liberreta/public_html/adm/adm.php on line 176

Once this is resolved I can close the question. Once I get a functional prototype I can clean it up.

<!DOCTYPE html>
<html lang="en">
<head>

  <!-- Basic Page Needs
  –––––––––––––––––––––––––––––––––––––––––––––––––– -->
  <meta charset="utf-8">
  <title>Your page title here :)</title>
  <meta name="description" content="">
  <meta name="author" content="">

  <!-- Mobile Specific Metas
  –––––––––––––––––––––––––––––––––––––––––––––––––– -->
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <!-- FONT
  –––––––––––––––––––––––––––––––––––––––––––––––––– -->
  <link href="//fonts.googleapis.com/css?family=Raleway:400,300,600" rel="stylesheet" type="text/css">

  <!-- CSS
  –––––––––––––––––––––––––––––––––––––––––––––––––– -->
  <link rel="stylesheet" href="css/normalize.css">
  <link rel="stylesheet" href="css/skeleton.css">

<script src='//cdn.tinymce.com/4/tinymce.min.js'></script>
  <script>
  tinymce.init({
    selector: '#PContent',
    theme: 'modern',
    height: 300,
    plugins: [
      'advlist autolink link image lists charmap print preview hr anchor pagebreak spellchecker',
      'searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking',
      'save table contextmenu directionality emoticons template paste textcolor'
    ],
    content_css: 'css/content.css',
    toolbar: 'insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image | print preview media fullpage | forecolor backcolor emoticons'
 
  });
  </script>


  <!-- Favicon
  –––––––––––––––––––––––––––––––––––––––––––––––––– -->
  <link rel="icon" type="image/png" href="images/favicon.png">


</head>
<body onload="myUploadFunction()">
  <!-- Primary Page Layout
  –––––––––––––––––––––––––––––––––––––––––––––––––– -->
  <div class="container">
    <div class="row">
      <div class="one-half column" style="margin-top: 2%">


      <?php
        // STEP 0. Are we getting form submission or should we show the form's field for filling?
         if(isset($_POST['add'])) {
           // STEP 1. Get the connection
            require 'dor.php';
            
            // STEP 2. Validate user's input
 $PTitle = $_POST['PTitle'];
           $PType = $_POST['PType'];
           $POrder = $_POST['POrder'];
           $PContent = $_POST['PContent'];
           $PDisplay = $_POST['PDisplay'];
         
            
            // STEP 3. Properly encode user input for SQL
            
            
            // STEP 4. Construct the SQL query


$sql = "INSERT INTO Pages ( PTitle,  PType,  POrder, PContent, PDisplay)
VALUES ('".$_POST["PTitle"]."','".$_POST["PType"]."','".$_POST["POrder"]."','".$_POST["PContent"]."','".$_POST["PDisplay"]."')";


            
            //$retval = mysql_query( $sql, $mysqli ); // procedural version
            $retval = $mysqli->query($sql);
            
            // STEP 5. Execute the SQL query
            if(! $retval ) {
                // STEP 5.1 Deal with insuccess
               die('Could not enter data: ' . $mysqli->error);
            }
            
            // STEP 5.2 Deal with success
            echo "Entered data successfully\n";
            
            // STEP 6. We're done, close the connection
            //mysqli_close($mysqli);
            $mysqli->close();
         }else {
            ?>
            

<form method = "post" action = "adm.php">
  <fieldset>
    <legend>Create A Page</legend>
    Title: <input type="text" name="PTitle">
    Page Type: <select name="PType">
  <option value="Home">Home</option>  
  <option value="Event">Event</option>
  <option value="Vehicle">Vehicle</option>
  <option value="Testimonial">Testimonial</option>
  <option value="Special">Special</option>
  <option value="About">About</option>
  <option value="Quote">Quote</option>
</select> Page Order: <input type="text" name="POrder"> 
  <textarea id="PContent">Please enter text and images only. Images will automatically be formatted based on the number of images included.

</textarea>  
<br>
    <select name="PDisplay">
  <option value="False">Hide</option>  
  <option value="True">Show</option>
</select><input type="submit" name="add" id="add" value="Save">
  </fieldset>
Upload New Image:
<input type="file" id="myFile" multiple size="50" onchange="myUploadFunction()">


<p id="demo"></p>
    
<script>
function myUploadFunction(){
    var x = document.getElementById("myFile");
    var txt = "";
    if ('files' in x) {
        if (x.files.length == 0) {
            txt = "Select one or more files.";
        } else {
            for (var i = 0; i < x.files.length; i++) {
                txt += "<br><strong>" + (i+1) + ". file</strong><br>";
                var file = x.files[i];
                if ('name' in file) {
                    txt += "name: " + file.name + "<br>";
                }
                if ('size' in file) {
                    txt += "size: " + file.size + " bytes <br>";
                }
            }
        }
    } 
    else {
        if (x.value == "") {
            txt += "Select one or more files.";
        } else {
            txt += "The files property is not supported by your browser!";
            txt  += "<br>The path of the selected file: " + x.value; // If the browser does not support the files property, it will return the path of the selected file instead. 
        }
    }
    document.getElementById("demo").innerHTML = txt;
}
</script>

<p><strong>Tip:</strong> Use the Control or the Shift key to select multiple files.</p>

Set Page Image:
Image: <input type="text" name="ImageLink">

</form></div>



<div class="one-half column" style="margin-top: 2%">test

<?php


$sqli = "SELECT ID, PTitle, PType FROM Pages";
$resulti = $mysqli->query($sqli);

if ($resulti->num_rows > 0) {
    // output data of each row
    while($row = $resulti->fetch_assoc()) {
        echo "id: " . $row["ID"]. " - Name: " . $row["PTitle"]. " " . $row["PType"]. "<br>";
    }
} else {
    echo "0 results";
}


?>

</div>



     <?php
         }
      ?>
   
      


    </div>
  </div>
<!-- End Document
  –––––––––––––––––––––––––––––––––––––––––––––––––– -->
</body>
</html>

Open in new window

arnold

A quick scan, there is an earlier close event, line 96.  You should check first whether a connection is still present.
In portions as you have you can not assume/presume that a connection is still there.  Often in setup such as your the require rather than establishing a connection, provides functions to initiate a connection if needed whose logic includes checking whether a prior connection already exists returning the connection whether a new connection or the reference to the existing one.

Chris suggestion that you breakup into components and make each component work on its own, you can always consolidate it. The reason is that while you fix a, b, c, when fixing d, as at times happens a global variable/reference is changed that could have adverse impact on previously working a,b,c and you suddenly get an error in a,c which unless you keep prior versions of this page as you make change, .......you can get tangled.
Further, the separation may help you enhance modularity and setting up functions to perform the tasks without having to rewrite/write a similar code in different section.  Use of functions provides you with single point changes for db enhancements versus if you decide you need another column, etc, you would need to rewrite and scan through everything.
mSprout

ASKER
I like functions, but the examples in w3schools  don't have them... so I am missing an image of how to add them or seperate things that might get mixed up. I am more visual, and there is just text on text on text to read. It doesn't make sense though even if I read to the end.
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
arnold

The function similar to the manner in which you included the connections are defined in a php the you include./require.

Look at php.net. Are you raw coding using something like notepad++ context, or using an IDE such as netbeans, zend, etc.
mSprout

ASKER
Yes, I am raw coding. Regular notepad. Im assuming you mean put the insert in a different .php file. Is that correct?
mSprout

ASKER
Here is a good example of what you guys are saying for the next person:
http://stackoverflow.com/questions/21027689/pre-filling-php-form-on-update
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
mSprout

ASKER
Thank you for your patience!