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

mSprout
mSprout used Ask the Experts™
on
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

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2011
Top Expert 2016
Commented:
Probably the most urgent issue is the use of MySQL.  It's dead, and must be replaced with MySQLi or PDO.  This article explains why it has been removed from PHP and what you must do to keep your scripts running.
http://www.experts-exchange.com/articles/11177/PHP-MySQL-Deprecated-as-of-PHP-5-5-0.html

Magic Quotes has been gone for a long time.  If you want to understand why, this will tell you.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_6630-Magic-Quotes-a-bad-idea-from-day-one.html

PHP form processing is described here.  You may want to read this all, and focus on the part about Dealing With Forms.
http://php.net/manual/en/tutorial.php

In the script, the query string $sql is an undefined variable.  This might be part of the problem, but it's impossible to know from the code we can see here.  My recommendation is to post this over in E-E Gigs and spend a few $$ to get an expert to dig into the code and test data, and show you how to make this work.  File uploads are one part, SQL queries are one part, JavaScript manipulation of HTML is another part, etc.  It's an application with a lot of moving parts and rather than try to get a single answer that covers all the questions, it might be best to get help deconstructing the problem into its component questions, each of which has a few answers!
Distinguished Expert 2017

Commented:
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.
Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
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">
Bootstrap 4: Exploring New Features

Learn how to use and navigate the new features included in Bootstrap 4, the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first websites.

Distinguished Expert 2017

Commented:
Great catch, Chris.

Author

Commented:
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
Distinguished Expert 2017

Commented:
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>
..

Author

Commented:
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.
Distinguished Expert 2017

Commented:
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.

Author

Commented:
<?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();

?>

Author

Commented:
Error: Unable to connect to database [Access denied for user 'nnn'@'localhost' (using password: YES)]
Distinguished Expert 2017

Commented:
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);

Author

Commented:
Can't use shell/commandline. On a shared host, and putty won't allow me to type a password, only user name.
Distinguished Expert 2017

Commented:
Do you have access to phpmyadmin? Check what credentials you use to login into it versus the php directives you are setting.

Author

Commented:
Yes, I do. My credentials are correct.
Distinguished Expert 2017

Commented:
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.

Author

Commented:
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?
Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
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 beziWeb Developer

Commented:
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

Author

Commented:
Chris, I get the same error, but with the numbers removed. DB Error: Access denied for user 'Huntress'@'localhost' (using password: YES)
Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
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.
Most Valuable Expert 2011
Top Expert 2016

Commented:
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.
Distinguished Expert 2017
Commented:
1045 is an auth mismatch. The issue could be that the username@localhost/password and the database you use is not correct. when you access the phpmyadmin, do you specify the same database that you
Let me rephrase it. When you access phpmyadmin, how many databases do you have access to?
Most hosting allow users, customers to create multiple databases, the difficutly is that while the user has rights to multiple, the login into sql might not be set/accepted with  a different DB.
In your mysqli connection string, are you specifying the DB to which it should connect?
username, password and you have database1, database2, database3 etc.
The connection string unless changes to the security mysql.DB are done, might only allow authentication for database1 requiring that upon connection you select a different DB.

See if you can an output for the following command
select * from mysql.user a left join mysql.host b on a.HOST=b.HOST left join mysql.db c on a.Db=c.db where a.User='yourusername';

The point is trying to see whether
your user might not be valid on localhost and might have to use the socket connection instead

$sock='/var/lib/mysql/mysql.sock';
$conn=new mysqli ($host,$username,$password,$database,$port,$sock);
see if the behavior changes.
Does your password have $@! characters? assigning those requires either the use of single quotes, or using the escape (\) that makes the next character to be interpreted literally.

Author

Commented:
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

Most Valuable Expert 2011
Top Expert 2016

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

Best of luck with your project, ~Ray
Most Valuable Expert 2018
Distinguished Expert 2018
Commented:
You're really going to need to break your project down into manageable chunks. 300+ lines of random code with no error reporting is going to be a nightmare to debug.

I've only got to line 90 and there are already several issues. Your SQL query is trying to insert into 6 fields and has 6 parameters, but the bind_param function is only taking 5 types (sssdi).

Your SQL statement is called $sql, but then you try and call insert_id on a statement called $stmt.

These are simple, straighforward things to pick up on, but you really need to turn on error reporting right at the start of you page.

Add this to the very top and call your page again.:

<?php 
error_reporting(E_ALL);
ini_set('display_errors', 1);
?>

Open in new window

As you're just beginning, I would strongly suggest you start with a very basic, clean HTML page (no CSS / no Javascript / no Forms etc.). From there, add in the connection code - test that. Then run a simple select query - test that. If that's all working, try running a simple UPDATE query with hard coded values - test that

This is how most of us do development - we start simple and build on it, testing and debugging as we go - it's a good habit to get into right now.

Author

Commented:
I already got the add working!!! Thanks for the error reporting tip.
Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
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

Author

Commented:
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

Distinguished Expert 2017

Commented:
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.

Author

Commented:
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.
Distinguished Expert 2017

Commented:
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.

Author

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

Author

Commented:
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

Author

Commented:
Thank you for your patience!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial