InMotion Hosting Support Center

In this tutorial series, we're using PHP and MySQL together to create a comment form so we can receive and display user comments on a website. We've already setup our database and our HTML form, and so our next step is to actually write the user's comment to the database once it has been submited.

Step 1 - Determining the correct SQL Insert command

When you write data to a database, you use SQL statements, specifically the INSERT command. It is straightforward, the INSERT command inserts data into the database. When you use phpMyAdmin, you use a GUI to manage your database, but it also shows you the MySQL commands that it ran when performing your requested tasks. We will use this feature to our advantge to find the correct code to use. What we will do is insert a test comment using phpMyAdmin, and then copy the INSERT command it used.

To INSERT using phpMyAdmin

  1. Log into your cPanel and click the phpMyAdmin icon
  2. In the left menu, first click your database name and then click the table to work with. If you're following our example, we'll first click on "_mysite" and then "comments".
  3. In the top menu, click "Insert"
  4. Type in a sample comment (refer to our screenshot below) and then click GO
    inserting-a-test-record-in-phpmyadmin
  5. After you have run the query, phpMyAdmin will display the insert command it used (see the screenshot below). Copy this SQL statement to a temporary location, such as a text file on your computer.
    sample-insert-query-in-phpmyadmin

Step 2 - Writing the PHP code that will execute MySQL Query

Now that we have a sample query, we need to modify it and run in once a user has submitted a comment. Below is example code that will do this. If you're not familiar with php, any line that begins with // is a comment. It is intended for programmers to leave comments about what their code is doing so that either themselves or other people who work on the code have an idea as to what the code is doing. In the example below, we've put in comments explaining what exactly certain peicies of code are doing:

<?

// When someone submits a comment, they "POST" the comment to the server.
// Therefore, we only want to insert a comment to the database if there
// is POST data. The if statement below checks to see if someone has
// posted data to the page
if( $_POST )
{
  // At this point in the code, we know someone has posted data and
  // is trying to post a comment. We therefore need to now connect
  // to the database

  // Below we are setting up our connection to the server. Because
  // the database lives on the same physical server as our php code,
  // we are connecting to "localhost". inmoti6_myuser and mypassword
  // are the username and password we setup for our database when
  // using the "MySQL Database Wizard" within cPanel
  $con = mysql_connect("localhost","inmoti6_myuser","mypassword");

  // The statement above has just tried to connect to the database.
  // If the connection failed for any reason (such as wrong username
  // and or password, we will print the error below and stop execution
  // of the rest of this php script
  if (!$con)
  {
    die('Could not connect: ' . mysql_error());
  }

  // We now need to select the particular database that we are working with
  // In this example, we setup (using the MySQL Database Wizard in cPanel) a
  // database named inmoti6_mysite
  mysql_select_db("inmoti6_mysite", $con);

  // We now need to create our INSERT command to insert the user's
  // comment into the database.
  //
  // Let's first take a look at the sample INSERT code we received when we
  // used phpMyAdmin to create a test comment:
  //
  // INSERT INTO `inmoti6_mysite`.`comments` (`id`, `name`, `email`, `website`,
  // `comment`, `timestamp`, `articleid`) VALUES (NULL, 'John Smith',
  // 'johns@domain.com', 'johnsmith.com', 'This is a test comment.',
  // CURRENT_TIMESTAMP, '1');
  //
  // If we ran this command, it would insert the same exact comment from John
  // Smith every time. What we need to do is update this query so that it
  // includes all of the data that the user typed in.
  //
  // When we setup our HTML Form, some of the text boxes we used were:
  // <input type='text' name='name' id='name' />
  // <input type='text' name='email' id='email' />
  // The important information we need from this is the "id" that is set.
  // For example, to get the user's name, we can grab the 'name'. To
  // get their email address, we need to get the value of 'email'.
  //
  // Using the $_POST variable, we can get this data. This is what we're
  // doing below
  $users_name = $_POST['name'];
  $users_email = $_POST['email'];
  $users_website = $_POST['website'];
  $users_comment = $_POST['comment'];

  // We now have all of the data that the user inputed. What you don't want
  // to do is trust the user's input. Savy users / hackers may attempt to use
  // an sql injection attack in order to run sql statements that you did not
  // intend to run. For example, the following is a basic query for checking
  // someone's username and password:
  //
  // SELECT * FROM users WHERE user='USERNAME' AND password='PASSWORD'
  //
  // In the above, we're assuming the user typed USERNAME as their username and
  // PASSWORD as their PASSWORD. But, what if the user typed the following as
  // their password?
  //
  // ' OR ''='
  //
  // The new query would then be the following:
  //
  // SELECT * FROM users WHERE user='USERNAME' AND password='' OR ''=''
  //
  // Running the above query would allow anyone to login as any user! We can use
  // the mysql_real_escape_string function to escape the user's input. If used in
  // the above example, the new query would read:
  //
  // SELECT * FROM users WHERE user='USERNAME' AND password='\' OR \'\'=\''
  //
  // Because the single quotes are "escaped" (i.e. appended with a backslash), the
  // hackers attempt would fail.
  $users_name = mysql_real_escape_string($users_name);
  $users_email = mysql_real_escape_string($users_email);
  $users_website = mysql_real_escape_string($users_website);
  $users_comment = mysql_real_escape_string($users_comment);
  
  // We also need to get the article id, so we know if the comment belongs
  // to page 1 or if it belongs to page 2. The article id is going to be
  // passed in the URL. For example, looking at this URL:
  //
  // http://phpandmysql.inmotiontesting.com/page1.php?id=1
  //
  // The article id is 1. To get data from the url, use the $_GET variable,
  // as in:
  $articleid = $_GET['id'];

  // We also want to add a bit of security here as well. We assume that the $article_id
  // is a number, but if someone changes the URL, as in this manner:
  // http://phpandmysql.inmotiontesting.com/page2.php?id=malicious_code_goes_here
  // ... then they will have the potential to run any code they want in your
  // database. The following code will check to ensure that $article_id is a number.
  // If it is not a number (IE someone is trying to hack your website), it will tell
  // the script to stop executing the page
  if( ! is_numeric($articleid) )
    die('invalid article id');

  // At this point, we've grabbed all of the data that we need. We now need
  // to update our SQL query. For example, instead of "John Smith", we'll
  // use $users_name. Below is our updated SQL command:
  $query = "
  INSERT INTO `inmoti6_mysite`.`comments` (`id`, `name`, `email`, `website`,
        `comment`, `timestamp`, `articleid`) VALUES (NULL, '$users_name',
        '$users_email', '$users_website', '$users_comment',
        CURRENT_TIMESTAMP, '$articleid');";

  // Our SQL stated is stored in a variable called $query. To run the SQL command
  // we need to execute what is in the $query variable.
  mysql_query($query);

  // We can inform the user to what's going on by printing a message to
  // the screen using php's echo function
  echo "<h2>Thank you for your Comment!</h2>";

  // At this point, we've added the user's comment to the database, and we can
  // now close our connection to the database:
  mysql_close($con);
}

?>

Don't let all of that code be intimidating! When we take out all of the comments, the code is much shorter and looks like this:

<?
if( $_POST )
{
  $con = mysql_connect("localhost","inmoti6_myuser","mypassword");

  if (!$con)
  {
    die('Could not connect: ' . mysql_error());
  }

  mysql_select_db("inmoti6_mysite", $con);

  $users_name = $_POST['name'];
  $users_email = $_POST['email'];
  $users_website = $_POST['website'];
  $users_comment = $_POST['comment'];

  $users_name = mysql_real_escape_string($users_name);
  $users_email = mysql_real_escape_string($users_email);
  $users_website = mysql_real_escape_string($users_website);
  $users_comment = mysql_real_escape_string($users_comment);

  $articleid = $_GET['id'];
  if( ! is_numeric($articleid) )
    die('invalid article id');

  $query = "
  INSERT INTO `inmoti6_mysite`.`comments` (`id`, `name`, `email`, `website`,
        `comment`, `timestamp`, `articleid`) VALUES (NULL, '$users_name',
        '$users_email', '$users_website', '$users_comment',
        CURRENT_TIMESTAMP, '$articleid');";

  mysql_query($query);

  echo "<h2>Thank you for your Comment!</h2>";

  mysql_close($con);
}
?>

Step 3 - Placing our php code in our pages

Now that we have the php code to insert the comments into the database, we need to put the code into our pages (page1.php and page2.php). In our previous article, we showed you how to use php's include function to help manage blocks of code effeciently, and we will again use the include function.

To incorporate our php code:

  1. Create a file named manage_comments.php
  2. Paste in the sample code above
  3. Update both page1.php and page2.php to include manage_comments.php by using
    <? include("manage_comments.php"); ?>
    at the top of the file

At this time, we are now working with 4 different files, and they are all in the same directory:
showing-all-files-in-one-folder

Also, after incorporating <? include("manage_comments.php"); ?>, our page1.php file now looks like this:

<? include("manage_comments.php"); ?>

<h1>This is page1.php</h1>

<div><a href='page2.php?id=2'>Click here</a> to go to page2.php</div>

<div style='margin:20px; width:100px; height:100px; background:blue;'></div>

<? include("formcode.php"); ?>

In our next article, we'll take a look at what we've done thus far and test out our comment system to see exactly how it works.

Continued Education in Course 205: Using PHP to create dynamic pages
You are viewing Section 5: Using PHP to INSERT data into a database
Section 4: Using the php include function to reuse code
Section 6: Reviewing sample PHP code that interacts with a MySQL Database
2013-09-11 8:54 am
"After you have ran" should be "After you have run"...
Staff
26,137 Points
2013-09-13 3:03 pm
Hello Dubosqued,

Thanks for the input! Your correction has been applied!

Regards,
Arnel C.
n/a Points
2014-03-22 7:41 pm

Thank your for this but i get always invalid article.

I tryed delete articlied process but still can not insert a new comment in a database.

This is mine php code.

<?

  if( $_POST )

  {
  
  $con = mysql_connect("mysql1.000webhost.com","db_user","db_pass","comments");

  if (!$con)
  {
    die('Could not connect: ' . mysql_error());
  }

  mysql_select_db("db_user", $con);
  $users_name = $_POST['name'];
  $users_email = $_POST['email'];
  $users_website = $_POST['website'];
  $users_comment = $_POST['comment'];
  $users_name = mysql_real_escape_string($users_name);
  $users_email = mysql_real_escape_string($users_email);
  $users_website = mysql_real_escape_string($users_website);
  $users_comment = mysql_real_escape_string($users_comment);

  $query = "

  INSERT INTO `db_user`.`comments` (`id`, `name`, `email`, `website`,

        `comment`, `timestamp`, `articleid`) VALUES (NULL, '$users_name',

        '$users_email', '$users_website', '$users_comment',

        CURRENT_TIMESTAMP, '$articleid');";

  mysql_query($query);

 echo "<h2>Thank you for your Comment!</h2>";

  mysql_close($con);

  }  

?>
Staff
11,186 Points
2014-03-24 9:39 am
This code should appropriately insert data into a database. What is the specific error you are getting?
n/a Points
2014-03-28 2:11 pm

invalid article id

This error i get all time.

Staff
9,968 Points
2014-03-28 2:53 pm
Hello Amir,

It looks like you've got an extra entry in your MySQL connect line, here is yours:

$con = mysql_connect("mysql1.000webhost.com","db_user","db_pass","comments");


While the original mentioned in this article is:

$con = mysql_connect("localhost","inmoti6_myuser","mypassword");


It appears the code that you have pasted in the comment above is not the full PHP script detailed in this guide. As you seem to be missing this section of the code dealing with throwing that error invalid article id:

 $articleid = $_GET['id'];
if( ! is_numeric($articleid) )
die('invalid article id');


If you've removed this line, the script should still function and place a comment in the database. You might want to double-check to ensure that you've setup a database to handle form data correctly, and also that you properly create a HTML form to get user comments.

- Jacob
n/a Points
2014-05-05 8:00 am

COULD NOT CONNECT MYSQL_ERROR

HELP ME BRO

 

 

<?php

if(isset($_POST['form']))

$con=mysql_connect("localhost","root","");

$db="dum";

if

(!$con)

{

die("could not connect:mysql_error()");

}

if (mysql_query("CREATE DATABASE dum;$con"))

{

echo"your Database created which name is:dum";

}

else

{

echo"Error creating database:".mysql_error();

}

//create table

if(!$con)

mysql_select_db("dum",$con);

{

die('could not connect:'.mysql_error());

}

if(! get_magic_quotes_gpc() )

$sql="CREATE TABLE 

(

name VARCHAR (50);

destination VACHAR (30);

sal int(10);

qualificaqtion VARCHAR (35);

)";

mysql_query($dum,$con);

echo"your table created which is as follows";

 

//insert data

 

{

$name=$_POST['name'];

$destinatiion=$_POST['destination'];

$sal=$_POST['sal'];

$qualification=$_POST['qualification'];

 

 

$sql="INSERT INTO $gum(id,name,destination,sal,qualification)

VALUES('$name','$destionation','$sal','$qualification')";

 

mysql_query($query);

 

if(! $retval )

{

  die('Could not enter data: ' . mysql_error());

}

echo "Entered data successfully\n";

 

}

 

mysql_close($con)

?>

<table border="1">

<tr>

<td align="center">Form Input Employees data</td>

</tr>

<tr>

<td>

<table>

<form method="post"actio="post">

<tr>

<td>Name</td>

<td><input type="text"name="name"size="50">

</td>

</tr>

<tr>

<td>Destination</td>

<td><input type="text"name="Destination"size="30">

</td>

</tr>

<tr>

<td>sal</td>

<td><input type="text"name="sal"size="10">

</td>

</tr>

<tr>

<td>Qualification</td>

<td><input type="text"name="Qualification"size="35" >

</td>

</tr>

<tr>

<td></td>

<td align="right"><input type="submit"

name="submit"value="sent" ></td>

</tr>

</table>

</td>

</tr>

</table>

 

</body>

</html><?php

if(isset($_POST['form']))

$con=mysql_connect("localhost","root","");

$db="dum";

if

(!$con)

{

die("could not connect:mysql_error()");

}

if (mysql_query("CREATE DATABASE dum;$con"))

{

echo"your Database created which name is:dum";

}

else

{

echo"Error creating database:".mysql_error();

}

//create table

if(!$con)

mysql_select_db("dum",$con);

{

die('could not connect:'.mysql_error());

}

if(! get_magic_quotes_gpc() )

$sql="CREATE TABLE 

(

name VARCHAR (50);

destination VACHAR (30);

sal int(10);

qualificaqtion VARCHAR (35);

)";

mysql_query($dum,$con);

echo"your table created which is as follows";

 

//insert data

 

{

$name=$_POST['name'];

$destinatiion=$_POST['destination'];

$sal=$_POST['sal'];

$qualification=$_POST['qualification'];

 

 

$sql="INSERT INTO $gum(id,name,destination,sal,qualification)

VALUES('$name','$destionation','$sal','$qualification')";

 

mysql_query($query);

 

if(! $retval )

{

  die('Could not enter data: ' . mysql_error());

}

echo "Entered data successfully\n";

 

}

 

mysql_close($con)

?>

<table border="1">

<tr>

<td align="center">Form Input Employees data</td>

</tr>

<tr>

<td>

<table>

<form method="post"actio="post">

<tr>

<td>Name</td>

<td><input type="text"name="name"size="50">

</td>

</tr>

<tr>

<td>Destination</td>

<td><input type="text"name="Destination"size="30">

</td>

</tr>

<tr>

<td>sal</td>

<td><input type="text"name="sal"size="10">

</td>

</tr>

<tr>

<td>Qualification</td>

<td><input type="text"name="Qualification"size="35" >

</td>

</tr>

<tr>

<td></td>

<td align="right"><input type="submit"

name="submit"value="sent" ></td>

</tr>

</table>

</td>

</tr>

</table>

 

</body>

</html>

Staff
29,164 Points
2014-05-05 1:06 pm
Hello Shams,

Running the code you provided, the first line evaluates as False. This means it will not run the second line of code, which is where your connection should set up. Since the connection is never set up nor connected it fails the check and gives the error code you see on the screen.

To learn more about this please check our article on Connecting to a Database using PHP.

Kindest Regards,
Scott M
n/a Points
2014-06-10 3:00 am

Hello, i have used this code and after pressing the submit button the query is executed and displays the message "Thank You For Your Comment " but when i open my datatbase the  data is not inserted into table, everything is correct but still data is not inserted...???? help??

Staff
11,186 Points
2014-06-10 8:19 am
Could you provide us with the code that is causing the issue?
n/a Points
2014-06-11 10:03 am

Can't figure out what's going on here. It's a singe page, single topic setup. I've embeded the code for manage_comments.php straight into index.html - and it all seems to work, except for actually putting the comment into the database. It does say "Thank you for your Comment! - but there's no database entry. Any ideas?

<?

                                                if( $_POST )

                                                {

                                                 $con = mysql_connect("localhost","xxxxx","yyyyy");

 

                                                  if (!$con)

                                                  {

                                                    die('Could not connect: ' . mysql_error());

                                                  }

 

                                                  mysql_select_db("databasename", $con);

 

                                                  $users_comment = $_POST['comment'];

 

                                                  $users_comment = mysql_real_escape_string($users_comment);

                                                  $query = "

                                                  INSERT INTO `databasename`.`comments` (`id`,`timestamp`, `comment`) VALUES (DEFAULT, CURRENT_TIMESTAMP, '$users_comment');";

 

                                                  mysql_query($query);

 

                                                  echo "<h2>Thank you for your Comment!</h2>";

 

                                                  mysql_close($con);

                                                }

                                                ?>

                                        <?php include('formcode.php'); ?>

 

The database has 3 columns. ID (whcih auto-increments with DEFAULT), timestamp, and the actualy comment. Nothing gets populated, no error message. Just the flash on the screen saying "Thank you for your Comment". 

Staff
11,186 Points
2014-06-11 11:28 am
Looking over your code, it looks fine. To further debug the issue, I recommend that you echo out the $query variable that you have set and take a look at it. If it looks fine, try to run it through PHPMyAdmin and see what happens.
n/a Points
2014-06-16 4:22 am

im trying to add data to my database bt its not. kindly assist guys

<?php

 

require_once('connect.php');

//receive values from form and assign them to variable

$school_id = $_POST['school_id'];

$sch_name = $_POST['sch_name'];

$team = $_POST['team'];

$amount = $_POST['amount'];

$telephone = $_POST['telephone'];

$year = $_POST['year'];

 

//execute insert statement

$mydata ="insert into registration (school_id,sch_name,team,amount,telephone,year)

values('$school_id','$sch_name','$team','$amount','$telephone','$year')";

if(!mysql_query($mydata))

{

echo "Record not added into the table";

}

else

echo "Recorded added successfully!";

 

 

mysql_close($mydata);

 

?>

This site has no rating
Staff
11,186 Points
2014-06-16 10:08 am
Could you clarify what exactly happens when you attempt to run your script?
n/a Points
2014-07-01 11:09 am

hi - everything seems to be working, but the rows that get inserted into mysql database are just blank, here is the code i'm using:

 

<? if( $_POST ) { $con =mysql_connect("localhost","amitpatel","denlax11"); if (!$con) {die('Could not connect: ' . mysql_error()); }mysql_select_db("Inquiries", $con); $users_firstname =$_POST['FNAME']; $users_lastname = $_POST['LNAME']; $users_email =$_POST['EMAIL']; $users_comments = $_POST['COMMENTS'];$users_firstname = mysql_real_escape_string($users_firstname);$users_lastname = mysql_real_escape_string($users_lastname);$users_email = mysql_real_escape_string($users_email); $users_comments= mysql_real_escape_string($users_comments); $query = " INSERT INTO`Inquiries`.`Inquiries` (`IDKEY`, `FNAME`, `LNAME`, `EMAIL`,`COMMENTS`, `DATE`) VALUES (NULL, '$users_firstname','$users_lastname', '$users_email', '$users_comments',CURRENT_TIMESTAMP);"; mysql_query($query); echo "<h2>Thank you foryour Comment!</h2>"; mysql_close($con); } ?>

 

also - what does the $users mean before the form id fields? do i need to change that to something else?

 

Thanks!

Staff
29,164 Points
2014-07-01 11:34 am
Hello amit,

I would have your code echo out the query to ensure they are getting populated. Also make sure you error check the query as well for any information it may be putting out.

Kindest Regards,
Scott M
n/a Points
2014-07-01 11:36 am

hi scott - thanks for the quick response. i'm pretty newb to this so can you elaborate on what you mean by have my code echo out the query?

 

THanks!

Staff
29,164 Points
2014-07-01 12:02 pm
Hello Amit,
What you want to do is to have a statement like the one below after you set your $query variable:
echo $query;

This should print out the full query statement that is being run against the database. It will show you whether or not the variable fields are being populated before the insert.

Kindest Regards,
Scott M
n/a Points
2014-07-15 2:42 am

This code should appropriately insert data into a database. What is the specific error you are getting?

n/a Points
2014-07-21 4:10 am

Hi guys, I'm very interested in PHP after looking at this tutorial and I decided to a small project for myself. I have created my own Web Control Interface and setup hardware already, by the way, I'm using Raspberry PI as my hardware.

The main issues right now is that I don't know why my INSERT method won't works and when I check mySQL database, is empty. Hope you guys could help me out with it as soon as possible, thanks in advance, guys.

This is my control.php:

<?php

error_reporting(E_ALL);

ini_set('display_errors','On');

 

session_start();

 

$MySQLUsername = "gpio";

$MySQLPassword = "kang";

 

$MySQLHost = "localhost";

$MySQLDB = "gpio";

 

If (($MySQLUsername == "USERNAME HERE") || ($MySQLPassword == "PASSWORD HERE")){

print 'ERROR - Please set up the script first';

exit();

}

 

$dbConnection = mysql_connect($MySQLHost, $MySQLUsername, $MySQLPassword);

mysql_select_db($MySQLDB, $dbConnection);

If (isset($_POST['action'])){

If ($_POST['action'] == "setPassword"){

$password1 = $_POST['password1'];

$password2 = $_POST['password2'];

If ($password1 != $password2){

header('Location: control.php');

}

$password = mysql_real_escape_string($_POST['password1']);

If (strlen($password) > 28){

mysql_close();

header('location: control.php');

}

$resetQuery = "SELECT username, salt FROM users WHERE username = 'admin';";

$resetResult = mysql_query($resetQuery);

If (mysql_num_rows($resetResult) < 1){

mysql_close();

header('location: control.php');

}

$resetData = mysql_fetch_array($resetResult, MYSQL_ASSOC);

$resetHash = hash('sha256', $salt . hash('sha256', $password));

$hash = hash('sha256', $password);

function createSalt(){

$string = md5(uniqid(rand(), true));

return substr($string, 0, 8);

}

$salt = createSalt();

$hash = hash('sha256', $salt . $hash);

mysql_query("UPDATE users SET salt='$salt' WHERE username='admin'");

mysql_query("UPDATE users SET password='$hash' WHERE username='admin'");

mysql_close();

header('location: control.php');

}

}

If ((isset($_POST['username'])) && (isset($_POST['password']))){

$username = mysql_real_escape_string($_POST['username']);

$password = mysql_real_escape_string($_POST['password']);

$loginQuery = "SELECT UserID, password, salt FROM users WHERE username = '$username';";

$loginResult = mysql_query($loginQuery);

If (mysql_num_rows($loginResult) < 1){

mysql_close();

header('location: control.php?error=incorrectLogin');

}

$loginData = mysql_fetch_array($loginResult, MYSQL_ASSOC);

$loginHash = hash('sha256', $loginData['salt'] . hash('sha256', $password));

If ($loginHash != $loginData['password']){

mysql_close();

header('location: control.php?error=incorrectLogin');

} else {

session_regenerate_id();

$_SESSION['username'] = "admin";

$_SESSION['userID'] = "1";

mysql_close();

header('location: control.php');

}

}

If ((!isset($_SESSION['username'])) || (!isset($_SESSION['userID']))){

print '

<html>

<head>

<title>GPIO Control - Login</title>

</head>

<body>

<table border="0" align="center">

<form name="login" action="control.php" method="post">

<tr>

<td>Username: </td><td><input type="text" name="username"></td>

</tr>

<tr>

<td>Password: </td><td><input type="password" name="password"></td>

</tr>

<tr>

<td colspan="2" align="center"><input type="submit" value="Log In"></td>

</tr>

</form>

</table>

</body>

</html>

';

die();

}

If (isset($_GET['action'])){

If ($_GET['action'] == "logout"){

$_SESSION = array();

session_destroy();

header('Location: control.php');

} else If ($_GET['action'] == "setPassword"){

print '

<form name="changePassword" action="control.php" method="post">

<input type="hidden" name="action" value="setPassword">

<p>Enter New Password: <input type="password" name="password1">  Confirm: <input type="password" name="password2"><input type="submit" value="submit"></p>

</form>

';

} else {

$action = $_GET['action'];

$storing = $_POST['storing'];

$pin = mysql_real_escape_string($_GET['pin']);

if ($action == "turnOn"){

$setting = "1";

mysql_query("UPDATE pinStatus SET pinStatus='$setting' WHERE pinNumber='$pin';");

mysql_close();

header('Location: control.php');

} else If ($action == "turnOff"){

$setting = "0";

mysql_query("UPDATE pinStatus SET pinStatus='$setting' WHERE pinNumber='$pin';");

mysql_close();

header('Location: control.php');

} else If ($storing == "turnOn"){

mysql_query("INSERT INTO 'gpio'.'sensor' ('id', 'sensorId', 'sensor', 'switchOnLog', 'switchOffLog') VALUES (NULL, '1', 'Red LED', NOW(), '') FROM pinStatus WHERE pinNumber='4';");

mysql_query("INSERT INTO 'gpio'.'sensor' ('id', 'sensorId', 'sensor', 'switchOnLog', 'switchOffLog') VALUES (NULL, '2', 'Blue LED', NOW(), '') FROM pinStatus WHERE pinNumber='17';");

mysql_query("INSERT INTO 'gpio'.'sensor' ('id', 'sensorId', 'sensor', 'switchOnLog', 'switchOffLog') VALUES (NULL, '3', 'LED', NOW(), '') FROM pinStatus WHERE pinNumber='18';");

mysql_query("INSERT INTO 'gpio'.'sensor' ('id', 'sensorId', 'sensor', 'switchOnLog', 'switchOffLog') VALUES (NULL, '4', 'LED', NOW(), '') FROM pinStatus WHERE pinNumber='21';");

mysql_query("INSERT INTO 'gpio'.'sensor' ('id', 'sensorId', 'sensor', 'switchOnLog', 'switchOffLog') VALUES (NULL, '5', 'LED', NOW(), '') FROM pinStatus WHERE pinNumber='22';");

mysql_query("INSERT INTO 'gpio'.'sensor' ('id', 'sensorId', 'sensor', 'switchOnLog', 'switchOffLog') VALUES (NULL, '6', 'Green LED', NOW(), '') FROM pinStatus WHERE pinNumber='23';");

mysql_query("INSERT INTO 'gpio'.'sensor' ('id', 'sensorId', 'sensor', 'switchOnLog', 'switchOffLog') VALUES (NULL, '7', 'LED', NOW(), '') FROM pinStatus WHERE pinNumber='24';");

mysql_query("INSERT INTO 'gpio'.'sensor' ('id', 'sensorId', 'sensor', 'switchOnLog', 'switchOffLog') VALUES (NULL, '8', 'LED', NOW(), '') FROM pinStatus WHERE pinNumber='25';");

mysql_close();

header('Location: control.php');

} else If ($storing == "turnOff"){

mysql_query("INSERT INTO 'gpio'.'sensor' ('id', 'sensorId', 'sensor', 'switchOnLog', 'switchOffLog') VALUES (NULL, '1', 'Red LED', '', NOW()) FROM pinStatus WHERE pinNumber='4';");

mysql_query("INSERT INTO 'gpio'.'sensor' ('id', 'sensorId', 'sensor', 'switchOnLog', 'switchOffLog') VALUES (NULL, '2', 'Blue LED', '', NOW()) FROM pinStatus WHERE pinNumber='17';");

mysql_query("INSERT INTO 'gpio'.'sensor' ('id', 'sensorId', 'sensor', 'switchOnLog', 'switchOffLog') VALUES (NULL, '3', 'LED', '', NOW()) FROM pinStatus WHERE pinNumber='18';");

mysql_query("INSERT INTO 'gpio'.'sensor' ('id', 'sensorId', 'sensor', 'switchOnLog', 'switchOffLog') VALUES (NULL, '4', 'LED', '', NOW()) FROM pinStatus WHERE pinNumber='21';");

mysql_query("INSERT INTO 'gpio'.'sensor' ('id', 'sensorId', 'sensor', 'switchOnLog', 'switchOffLog') VALUES (NULL, '5', 'LED', '', NOW()) FROM pinStatus WHERE pinNumber='22';");

mysql_query("INSERT INTO 'gpio'.'sensor' ('id', 'sensorId', 'sensor', 'switchOnLog', 'switchOffLog') VALUES (NULL, '6', 'Green LED', '', NOW()) FROM pinStatus WHERE pinNumber='23';");

mysql_query("INSERT INTO 'gpio'.'sensor' ('id', 'sensorId', 'sensor', 'switchOnLog', 'switchOffLog') VALUES (NULL, '7', 'LED', '', NOW()) FROM pinStatus WHERE pinNumber='24';");

mysql_query("INSERT INTO 'gpio'.'sensor' ('id', 'sensorId', 'sensor', 'switchOnLog', 'switchOffLog') VALUES (NULL, '8', 'LED', '', NOW()) FROM pinStatus WHERE pinNumber='25';");

mysql_close();

header('Location: control.php');

} else IF ($action =="edit"){

$pin = mysql_real_escape_string($_GET['pin']);

$query = mysql_query("SELECT pinDescription FROM pinDescription WHERE pinNumber='$pin';");

$descRow = mysql_fetch_assoc($query);

$description = $descRow['pinDescription'];

print '

<html><head><title>Update Pin ' . $pin . '</title></head><body>

<table border="0">

<form name="edit" action="control.php" method="get">

<input type="hidden" name="action" value="update">

<input type="hidden" name="pin" value="' . $pin . '">

<tr>

<td><p>Description: </p></td><td><input type="text" name="description" value="' . $description . '"></td><td><input type="submit" value="Confirm"></td>

</tr>

</form>

</table>

</body></html>

';

mysql_close();

} else IF ($action =="update"){

$pin = mysql_real_escape_string($_GET['pin']);

$description = mysql_real_escape_string($_GET['description']);

mysql_query("UPDATE pinDescription SET pinDescription='$description' WHERE pinNumber='$pin';");

header('Location: control.php');

} else {

header('Location: control.php');

}

}

} else {

print '

<html>

<head>

<title>GPIO Control</title>

</head>

<font face="verdana">

<p><h1>Sensors</h1></p>

';

$query = mysql_query("SELECT pinNumber, pinStatus FROM pinStatus;");

$query2 = mysql_query("SELECT pinNumber, pinDescription FROM pinDescription;");

$totalGPIOCount = mysql_num_rows($query);

$currentGPIOCount = 0;

print '<table name="GPIO" border="1" cellpadding="5">';

print '<tr><th>GPIO #</th><th>GPIO Description</th><th>Status</th><th>Action</th><th>Edit</th></tr>';

while ($currentGPIOCount < $totalGPIOCount){

$pinRow = mysql_fetch_assoc($query);

$descRow = mysql_fetch_assoc($query2);

$pinNumber = $pinRow['pinNumber'];

$pinStatus = $pinRow['pinStatus'];

$pinDescription = $descRow['pinDescription'];

If ($pinStatus == "0"){

$buttonValue = "Turn On";

$action = "turnOn";

$image = "off.jpg";

} else {

$buttonValue = "Turn Off";

$action = "turnOff";

$image = "on.jpg";

}

print '<tr>';

print '<td align="center">' . $pinNumber . '</td><td>' . $pinDescription . '</td><td align="center"><img src="' . $image . '" width="50"></td><td align="center" valign="middle"><form name="pin' . $pinNumber . 'edit" action="control.php" method="get"><input type="hidden" name="action" value="' . $action . '"><input type="hidden" name="pin" value="' . $pinNumber . '"><input type="submit" value="' . $buttonValue . '"></form></td><td><form name="pin' . $pinNumber . '" action="control.php" method="get"><input type="hidden" name="action" value="edit"><input type="hidden" name="pin" value="' . $pinNumber . '"><input type="submit" value="Edit"></form></td>';

print '</tr>';

$currentGPIOCount ++;

}

print '</table>';

mysql_close();

print '

<br><br>

<a href="/support/control.php?action=logout">Log Out</a>

</font>

</html>

';

}

?>

Staff
29,164 Points
2014-07-21 12:24 pm
Hello,

When working with databases as well as other important functions and tasks, error trapping is important. For instance, you will need to ensure that you are actually connecting to the database without issue. To do so, you need to test the connection return variable. If an error occurs, then you want to know that specific error. You simply need to check that variable as in the sample code below:
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}


You can do the same for each INSERT statement you have so if any of them return an error you will see it:
$success= mysql_query("INSERT INTO 'gpio'.'sensor' ('id', 'sensorId', 'sensor', 'switchOnLog', 'switchOffLog') VALUES (NULL, '8', 'LED', '', NOW()) FROM pinStatus WHERE pinNumber='25';");;
if (!$success) {
die('Could not Insert: ' . mysql_error());
}

As you can see, they are very similar and simple. Do this for all SQL statements including the connection so you can see any errors you are getting.

One last thing, you may want to look into mysqli instead of mysql when working in php. The mysql functions are older and will be removed in a future version.

Kindest Regards,
Scott M
n/a Points
2014-07-21 9:35 pm

Thanks Scott, I found out my mistake and I needed your help again cause I want to do subqueries but I just can't get it right.

This is my error message for mySQL:

Could not Insert: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT '4' FROM pinStatus WHERE pinNumber='4'' at line 1

This is my new edited code:

*** Extra code removed ***

mysql_query("UPDATE pinStatus SET pinStatus='$setting' WHERE pinNumber='$pin';");

$success=mysql_query("INSERT INTO sensor VALUES(NULL, '1', 'Red LED', NOW(), NULL) SELECT '4' FROM pinStatus WHERE pinNumber='4';");

if (!$success) {

die('Could not Insert: ' . mysql_error());

}

$success=mysql_query("INSERT INTO sensor VALUES(NULL, '2', 'Blue LED', NOW(), NULL) SELECT '17' FROM pinStatus WHERE pinNumber='17';");

if (!$success) {

die('Could not Insert: ' . mysql_error());

}

*** Extra Code Removed ***
Staff
29,164 Points
2014-07-22 9:24 am
Hello,

When constructing a Select statement, you are typically looking to pull a column name (or * meaning all information from the referenced tables). You are asking it to pull a 4 where the pinNumber ='4'. If you want the number 4 to be pulled you may want to say something like:
SELECT pinNumber FROM pinStatus WHERE pinNumber='4';


This will return the 4 you are looking for.

Kindest Regards,
Scott M
2014-07-22 1:56 am
Hi guys, I would like to seek help on my INSERT method to mySQL database. I manage to store data but it always store the 1st data if I click second or third button, it will record all instead of just record that data which I have switch on or off.

This is my control.php:
<?php
error_reporting(E_ALL);
ini_set('display_errors','On');

session_start();

$MySQLUsername = "gpio";
$MySQLPassword = "kang";

$MySQLHost = "localhost";
$MySQLDB = "gpio";

If (($MySQLUsername == "USERNAME HERE") || ($MySQLPassword == "PASSWORD HERE")){
print 'ERROR - Please set up the script first';
exit();
}

$dbConnection = mysql_connect($MySQLHost, $MySQLUsername, $MySQLPassword);
mysql_select_db($MySQLDB, $dbConnection);
If (isset($_POST['action'])){
If ($_POST['action'] == "setPassword"){
$password1 = $_POST['password1'];
$password2 = $_POST['password2'];
If ($password1 != $password2){
header('Location: control.php');
}
$password = mysql_real_escape_string($_POST['password1']);
If (strlen($password) > 28){
mysql_close();
header('location: control.php');
}
$resetQuery = "SELECT username, salt FROM users WHERE username = 'admin';";
$resetResult = mysql_query($resetQuery);
If (mysql_num_rows($resetResult) < 1){
mysql_close();
header('location: control.php');
}
$resetData = mysql_fetch_array($resetResult, MYSQL_ASSOC);
$resetHash = hash('sha256', $salt . hash('sha256', $password));
$hash = hash('sha256', $password);
function createSalt(){
$string = md5(uniqid(rand(), true));
return substr($string, 0, 8);
}
$salt = createSalt();
$hash = hash('sha256', $salt . $hash);
mysql_query("UPDATE users SET salt='$salt' WHERE username='admin'");
mysql_query("UPDATE users SET password='$hash' WHERE username='admin'");
mysql_close();
header('location: control.php');
}
}
If ((isset($_POST['username'])) && (isset($_POST['password']))){
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$loginQuery = "SELECT UserID, password, salt FROM users WHERE username = '$username';";
$loginResult = mysql_query($loginQuery);
If (mysql_num_rows($loginResult) < 1){
mysql_close();
header('location: control.php?error=incorrectLogin');
}
$loginData = mysql_fetch_array($loginResult, MYSQL_ASSOC);
$loginHash = hash('sha256', $loginData['salt'] . hash('sha256', $password));
If ($loginHash != $loginData['password']){
mysql_close();
header('location: control.php?error=incorrectLogin');
} else {
session_regenerate_id();
$_SESSION['username'] = "admin";
$_SESSION['userID'] = "1";
mysql_close();
header('location: control.php');
}
}
If ((!isset($_SESSION['username'])) || (!isset($_SESSION['userID']))){
print '
<html>
<head>
<title>GPIO Control - Login</title>
</head>
<body>
<table border="0" align="center">
<form name="login" action="control.php" method="post">
<tr>
<td>Username: </td><td><input type="text" name="username"></td>
</tr>
<tr>
<td>Password: </td><td><input type="password" name="password"></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Log In"></td>
</tr>
</form>
</table>
</body>
</html>
';
die();
}
If (isset($_GET['action'])){
If ($_GET['action'] == "logout"){
$_SESSION = array();
session_destroy();
header('Location: control.php');
} else If ($_GET['action'] == "setPassword"){
print '
<form name="changePassword" action="control.php" method="post">
<input type="hidden" name="action" value="setPassword">
<p>Enter New Password: <input type="password" name="password1"> Confirm: <input type="password" name="password2"><input type="submit" value="submit"></p>
</form>
';
} else {
$action = $_GET['action'];
$pin = mysql_real_escape_string($_GET['pin']);
$pinNo = mysql_query("SELECT pinNumber FROM pinStatus WHERE pinNumber='$pinNo';");
if ($action == "turnOn"){
$setting = "1";
mysql_query("UPDATE pinStatus SET pinStatus='$setting' WHERE pinNumber='$pin';");
if ($pinNo = '4'){
mysql_query("INSERT INTO sensor VALUES(NULL, '1', 'Red LED', NOW(), NULL);");
}
else if ($pinNo = '17'){
mysql_query("INSERT INTO sensor VALUES(NULL, '2', 'Blue LED', NOW(), NULL);");
}
else If ($pinNo = '18'){
mysql_query("INSERT INTO sensor VALUES(NULL, '3', 'LED', NOW(), NULL);");
}
else If ($pinNo = '21'){
mysql_query("INSERT INTO sensor VALUES(NULL, '4', 'LED', NOW(), NULL);");
}
else If ($pinNo = '22'){
mysql_query("INSERT INTO sensor VALUES(NULL, '5', 'LED', NOW(), NULL);");
}
else If ($pinNo = '23'){
mysql_query("INSERT INTO sensor VALUES(NULL, '6', 'Green LED', NOW(), NULL);");
}
else If ($pinNo = '24'){
mysql_query("INSERT INTO sensor VALUES(NULL, '7', 'LED', NOW(), NULL);");
}
else If ($pinNo = '25'){
mysql_query("INSERT INTO sensor VALUES(NULL, '8', 'LED', NOW(), NULL);");
}
mysql_close();
header('Location: control.php');
} else If ($action == "turnOff"){
$setting = "0";
mysql_query("UPDATE pinStatus SET pinStatus='$setting' WHERE pinNumber='$pin';");
if ($pinNo = "4"){
mysql_query("INSERT INTO sensor VALUES(NULL, '1', 'Red LED', NULL, NOW());");
}
else if ($pinNo = "17"){
mysql_query("INSERT INTO sensor VALUES(NULL, '2', 'Blue LED', NULL, NOW());");
}
else If ($pinNo = '18'){
mysql_query("INSERT INTO sensor VALUES(NULL, '3', 'LED', NULL, NOW());");
}
else If ($pinNo = '21'){
mysql_query("INSERT INTO sensor VALUES(NULL, '4', 'LED', NULL, NOW());");
}
else If ($pinNo = '22'){
mysql_query("INSERT INTO sensor VALUES(NULL, '5', 'LED', NULL, NOW());");
}
else If ($pinNo = '23'){
mysql_query("INSERT INTO sensor VALUES(NULL, '6', 'Green LED', NULL, NOW());");
}
else If ($pinNo = '24'){
mysql_query("INSERT INTO sensor VALUES(NULL, '7', 'LED', NULL, NOW());");
}
else If ($pinNo = '25'){
mysql_query("INSERT INTO sensor VALUES(NULL, '8', 'LED', NULL, NOW());");
}
mysql_close();
header('Location: control.php');
} else IF ($action =="edit"){
$pin = mysql_real_escape_string($_GET['pin']);
$query = mysql_query("SELECT pinDescription FROM pinDescription WHERE pinNumber='$pin';");
$descRow = mysql_fetch_assoc($query);
$description = $descRow['pinDescription'];
print '
<html><head><title>Update Pin ' . $pin . '</title></head><body>
<table border="0">
<form name="edit" action="control.php" method="get">
<input type="hidden" name="action" value="update">
<input type="hidden" name="pin" value="' . $pin . '">
<tr>
<td><p>Description: </p></td><td><input type="text" name="description" value="' . $description . '"></td><td><input type="submit" value="Confirm"></td>
</tr>
</form>
</table>
</body></html>
';
mysql_close();
} else IF ($action =="update"){
$pin = mysql_real_escape_string($_GET['pin']);
$description = mysql_real_escape_string($_GET['description']);
mysql_query("UPDATE pinDescription SET pinDescription='$description' WHERE pinNumber='$pin';");
header('Location: control.php');
} else {
header('Location: control.php');
}
}
} else {
print '
<html>
<head>
<title>GPIO Control</title>
</head>
<font face="verdana">
<p><h1>Sensors</h1></p>
';
$query = mysql_query("SELECT pinNumber, pinStatus FROM pinStatus;");
$query2 = mysql_query("SELECT pinNumber, pinDescription FROM pinDescription;");
$totalGPIOCount = mysql_num_rows($query);
$currentGPIOCount = 0;
print '<table name="GPIO" border="1" cellpadding="5">';
print '<tr><th>GPIO #</th><th>GPIO Description</th><th>Status</th><th>Action</th><th>Edit</th></tr>';
while ($currentGPIOCount < $totalGPIOCount){
$pinRow = mysql_fetch_assoc($query);
$descRow = mysql_fetch_assoc($query2);
$pinNumber = $pinRow['pinNumber'];
$pinStatus = $pinRow['pinStatus'];
$pinDescription = $descRow['pinDescription'];
If ($pinStatus == "0"){
$buttonValue = "Turn On";
$action = "turnOn";
$image = "off.jpg";
} else {
$buttonValue = "Turn Off";
$action = "turnOff";
$image = "on.jpg";
}
print '<tr>';
print '<td align="center">' . $pinNumber . '</td><td>' . $pinDescription . '</td><td align="center"><img src="' . $image . '" width="50"></td><td align="center" valign="middle"><form name="pin' . $pinNumber . 'edit" action="control.php" method="get"><input type="hidden" name="action" value="' . $action . '"><input type="hidden" name="pin" value="' . $pinNumber . '"><input type="submit" value="' . $buttonValue . '"></form></td><td><form name="pin' . $pinNumber . '" action="control.php" method="get"><input type="hidden" name="action" value="edit"><input type="hidden" name="pin" value="' . $pinNumber . '"><input type="submit" value="Edit"></form></td>';
print '</tr>';
$currentGPIOCount ++;
}
print '</table>';
mysql_close();
print '
<br><br>
<a href="control.php?action=logout">Log Out</a>
</font>
</html>
';
}
?>
Staff
29,164 Points
2014-07-22 9:37 am
Hello aoiregion,

This sounds like a logic issue and not a syntax issue. Being a logic issue I would need to run the code against a database to figure out where the code is incorrect. That is not something we can do from here.

However, you should have the code echo out (print) the query to the screen so you can see which one it is firing off. Once you know which query it is sending, you can then check the code to see why it is setting those particular conditions. It can take many tries until you iron it out, but that is part of the fun of coding!

Kindest Regards,
Scott M
n/a Points
2014-08-09 12:00 pm
This was a easy to read clear article. After I read the code with the comments I understood what the process is. Well Done!
n/a Points
2014-09-18 9:36 am

Hello, I did exactly whats in the article.  I get the message that is successful but it does not insert the data to the database.  my code is:

 

<?

if( $_POST )

{

  $con = mysql_connect("localhost","root","");

 

  if (!$con)

  {

    die('Could not connect: ' . mysql_error());

  }

 

  mysql_select_db('samidb', $con);

 

  $number = $_POST['number'];

  $name = $_POST['name'];

  $desc = $_POST['desc'];

 

  $number = mysql_real_escape_string($number);

  $name = mysql_real_escape_string($name);

  $number = mysql_real_escape_string($desc);

 

  //$articleid = $_GET['id'];

  //if( ! is_numeric($articleid) )

    //die('invalid article id');

 

  $query = "

  INSERT INTO 'samidb'.'sami' (`number`, `name`, `desc`, `website) VALUES ('$number',

        '$name', '$desc');";

 

if (!$query) {

die('Could not Insert: ' . mysql_error());

}

 

  mysql_query($query);

  

  echo "<h2>Thank you for your Comment!</h2>";

 

    mysql_close($con);

  }

  ?>

Staff
17,726 Points
2014-09-18 10:59 am
Hello Sami,

Thank you for your question. I recommend checking your Database name, and confirming you are checking the correct database.

Also, you may want to print out the query, to ensure it is running what you expected.

If you have any further questions, feel free to post them below.

Thank you,
John-Paul
n/a Points
2014-09-18 11:13 am

Thank you John for quick response, 

The database name and the table name are identical to the one I see in myphpadmin. I printed the query and it works.  I have no idea why it is not inserting into the database.  It does not give me any errors but basically it does not insert.  

I am working on local host user name is root and has no password 

I made sure root at local host has all the privileges 

Thank you 

Staff
11,186 Points
2014-09-18 11:22 am
If you have confirmed that everything is correct as far as your connection goes, be sure that your variables are getting assigned with the expected data. This can be as simple as echoing out the variables to ensure that the correct data is returned.
n/a Points
2014-10-25 11:24 am

Somebody please help...how to fix

 Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting ']'...

my code is:

$sql="INSERT INTO information(student name,sex,religious,dateofbirth,email,ic number,address,zipcode,country)

VALUES

('$_POST[student name]','$_POST[sex]','$_POST[religious]','$_POST[dateofbirth]','$_POST[email]','$_POST[ic number]','$_POST

 

[address]', '$_POST[zipcode]', '$_POST[country]')";

 

Staff
29,164 Points
2014-10-27 8:40 am
Hello,

What you have here is a php syntax error. It appears there is a problem with one of your values. It would be much easier if you placed each POST into a specific variable and then placed the variables into the VALUES section. This way, the one POST that is giving the issue would be flagged and you could see which one is incorrect.

Kindest Regards,
Scott M
n/a Points
2014-11-03 2:34 am

Not getting errors, its simply not inserting to database?

 

<?

if( $_POST )

{

  $con = mysql_connect("localhost","walding_test","test123");

 

  if (!$con)

  {

    die('Could not connect: ' . mysql_error());

  }

 

  mysql_select_db("walding_Master", $con);

 

  $users_name = $_POST['name'];

  $users_email = $_POST['email'];

  $users_website = $_POST['website'];

  $users_comment = $_POST['comment'];

 

  $users_name = mysql_real_escape_string($users_name);

  $users_email = mysql_real_escape_string($users_email);

  $users_website = mysql_real_escape_string($users_website);

  $users_comment = mysql_real_escape_string($users_comment);

 

 

 

  $query = "INSERT INTO `walding_Master`.`Comment` (`ID`, `name`, `email`, `website`, `comment`)

   VALUES (NULL, '$users_name','$users_email', '$users_website', '$users_comment');";

 

  mysql_query($query);

 

  echo "<h2>Thank you for your Comment!</h2>";

echo $query;

  mysql_close($con);

}

?>

 

//////HTML///////

 

 <form action="contactus.php" method="POST">

          <div>

           <input type="text" name="name" id="name" value="" placeholder="Name">

          </div>

          <div>

           <input type="email" name="email" id="email" value="" placeholder="Email">

          </div>

          <div>

           <input type="url" name="website" id="website" value="" placeholder="Website URL">

          </div>

          <div>

           <textarea rows="10" name="comment" id="comment" placeholder="Comment"></textarea>

          </div>

          <div>

           <input type="submit" name="submit" value="Add Comment">

Staff
29,164 Points
2014-11-03 11:56 am
Hello Marty,

In the code you provided, you are not checking the return code for the mysql_query function. This is why you are not getting a syntactical error message. You will want to set the function to a variable like so:
$return = mysql_query($query);


Then you can echo out the $return variable to see what the error message is. Another thing to check is to echo out the $query string before it runs so you can see what the actual query is.

Kindest Regards,
Scott M
n/a Points
2014-12-01 7:45 am

Hello Sir,

I have a querry regarding insert when i run my registration code that my entries are added in two different tables that are registration and individual table at a time which should not happen actually values are for registration table and in tha individual table some filled and some blank are there and i am not getting the problem why that happen so can you please help me ?

Staff
17,726 Points
2014-12-01 12:08 pm
Hello Gauri,

Thank you for contacting us. We are happy to help, but will need some additional details to troubleshoot the problem.

Can you explain what you are trying to accomplish?

Can you provide the query you are executing?

Can you explain the steps you are taking? This will allow us to follow along with you.

Thank you,
John-Paul
n/a Points
2014-12-01 11:32 pm

Hey! I have read through everyone else's comments/error messages and I still have not been able to figure out what is wrong with my code. I am following this tutorial for a class, and I did everything in order but I am getting "invalid article id", and it is also not inserting any information into the database. Is there something I am missing? Here is my code: 

<?

if( $_POST )

{

  $con = mysql_connect("localhost","aburnham_user","mypassword");

 

  if (!$con)

  {

    die('Could not connect: ' . mysql_error());

  }

 

  mysql_select_db("aburnham_form", $con);

 

  $users_name = $_POST['name'];

  $users_email = $_POST['email'];

  $users_website = $_POST['website'];

  $users_comment = $_POST['comment'];

 

  $users_name = mysql_real_escape_string($users_name);

  $users_email = mysql_real_escape_string($users_email);

  $users_website = mysql_real_escape_string($users_website);

  $users_comment = mysql_real_escape_string($users_comment);

 

  $articleid = $_GET['id'];

  if( ! is_numeric($articleid) )

    die('invalid article id');

 

  $query = "

  INSERT INTO `aburnham_form`.`comments` (`id`, `name`, `email`, `website`,

        `comment`, `timestamp`, `articleid`) VALUES (NULL, '$users_name',

        '$users_email', '$users_website', '$users_comment',

        CURRENT_TIMESTAMP, '$articleid');";

 

  mysql_query($query);

  $return = mysql_query($query);

 

  echo "<h2>Thank you for your Comment!</h2>";

 

  mysql_close($con);

}

 

?>

Staff
11,186 Points
2014-12-02 9:31 am
The reason your are getting this error is because of this code:

$articleid = $_GET['id'];
if( ! is_numeric($articleid) )
die('invalid article id');


It should look something like this:

$articleid = $_GET['id'];

if( ! is_numeric($articleid) ) {

die('invalid article id'); }

n/a Points
2014-12-02 7:13 pm

That code still doesn't work :/ There must be an error somewhere else then... Thanks for the advice!!

Staff
11,186 Points
2014-12-02 7:14 pm
Could you provide me with the exact error you are getting now?
n/a Points
2014-12-02 7:21 pm

Still the same error "invalid article id" when I type in information and click submit. But actually I just tried doing a test comment again in my cPanel and I got this error: 

1 row inserted.

Inserted row id: 2Warning: #1366 Incorrect integer value: '' for column 'articleid' at row 1

It is in red instead of green like in your tutorial on adding a test comment. 

n/a Points
2014-12-02 7:25 pm

Wait, now the comments are showing up! I have no idea why it didn't work at first after I changed it to the code you provided. Thank you! :)

Staff
11,186 Points
2014-12-02 7:24 pm
It sounds like you are not passing the correct information from the GET variable. Could you provide me with the full URL on this page you are referring to?
n/a Points
2014-12-02 7:31 pm

http://annaburnham.com/phpForm/

I just found out that it works if you go to page 2 first (and type stuff in and submit), and then go back to page 1. But if you start typing and submit info on page 1 first, the "invalid article id" error happens. At least it works for the most part? 

Staff
11,186 Points
2014-12-02 7:56 pm
This is because of the URL. The code that inserts data into the database requires that an ID be defined within the URL. If you take a look at the URL after you click on Page 2, you will notice that it says id="1". Without this defined, it does not know the article ID that the comment would be left on.
n/a Points
2014-12-02 8:07 pm

Oh yup I see that! I thought I did that correctly.. That would be this code correct? 

 

<? include("manage_comments.php"); ?>

 <h1>This is page1.php</h1>

<div><a href='page2.php?id=1'>Click here</a> to go to page2.php</div>

<div style='margin:20px; width:100px; height:100px; background:blue;'></div>

 <? include("formcode.php"); ?>

 

and this: 

 

<? include("manage_comments.php"); ?>

 <h1>This is page2.php</h1>

<div><a href='page1.php?id=1'>Click here</a> to go to page1.php</div>

<div style='margin:20px; width:100px; height:100px; background:orange;'></div>

 <? include("formcode.php"); ?>

Staff
11,186 Points
2014-12-02 8:09 pm
Yes, that is fine.
Staff
11,186 Points
2014-12-02 8:10 pm
As for the URL that I am referring to in the above comment, I am referring to the URL in the address bar. When a user commends on your site, they should be visiting something like page1.php?id=1 so that the code knows what page the comment is being left on.
n/a Points
2014-12-02 8:15 pm

Oh ok! I'm so sorry if this is a dumb question, but how do I change the URL for the first page? Or if it is too involved to explain, can you point me to a good tutorial if you know any?

Staff
11,186 Points
2014-12-02 8:16 pm
When a user is leaving a comment, you would simply point them to http://annaburnham.com/phpForm/page1.php?id=1
n/a Points
2014-12-02 8:18 pm

Oh! Perfect, thanks so much for all of your help! :) Can I rate you on this site or something?

Staff
11,186 Points
2014-12-02 8:20 pm
There aren't any user ratings or anything, but I'm glad I was able to answer your questions!
n/a Points
2014-12-02 8:23 pm

Oh ok, well thank you so much again!!

n/a Points
2015-01-12 7:55 am

hey ive got a problem and its eating away my head! when i load page1 it displays the form but also this code: echo "<h2>Thank you for your Comment!</h2>"; ?>

idont know whats wrong? also i think due to this queer display i cant submit anything

this is my manage_comments.php

 

<?if( $_POST ){  $con = mysql_connect("localhost","x","y");  if (!$con)  {    die('Could not connect: ' . mysql_error());  }  mysql_select_db("search", $con);  $users_name = $_POST['name'];  $users_email = $_POST['email'];  $users_website = $_POST['website'];  $users_comment = $_POST['comment'];  $users_name = mysql_real_escape_string($users_name);  $users_email = mysql_real_escape_string($users_email);  $users_website = mysql_real_escape_string($users_website);  $users_comment = mysql_real_escape_string($users_comment);  $articleid = $_GET['id'];  if( ! is_numeric($articleid) ){    die('invalid article id'); }  $query = "  INSERT INTO `search`.`comments` (`id`, `name`, `email`, `website`,        `comment`, `timestamp`, `articleid`) VALUES (NULL, '$users_name',        '$users_email', '$users_website', '$users_comment',        CURRENT_TIMESTAMP, '$articleid');";   mysql_query($query);  echo "<h2>Thank you for your Comment!</h2>";    mysql_close($con);}?>

 

 

Staff
26,137 Points
2015-01-12 9:34 am
Hello David,

Sorry for the problems with the code. We unfortunately can't really troubleshoot your code. However, if your code is not working, it's most likely centered around the conditions of the if statements in the beginning of the code. If those conditions aren't being met, then your form won't post. Apologies again that we can't give you a direct answer. If you have any further questions, please let us know.

Regards,
Arnel C.
n/a Points
2015-02-05 11:21 pm

Hi 

I am creating login and register page. when I am trying to enter data into register.php then data is not inserted into table as well as email not send.

Find a solution.

register.php

 

<?php

 

 $conn =new mysqli('localhost','admin_password','test123','password_app');

 

 include("../PHPMailer/PHPMailerAutoload.php");

 

 

//require_once'connection.php';

 

//check for spam 

//if(empty($_POST['spamProtection']))

//{

if(isset($_POST['Register']))

{

$count=0;

 

//check if required fields are not empty

if(trim($_POST['name']) == '') {

                $hasError = true;

        } else {

                $name = trim($_POST['name']);

        }

 

if(trim($_POST['user']) == '') {

                $hasError = true;

        } else {

                $user=trim($_POST['user']);

        }

if(trim($_POST['email']) == '') {

                $hasError = true;

        } else {

                $email = trim($_POST['email']);

        }

 

if(trim($_POST['password']) == '') {

                $hasError = true;

        } else {

                $email = trim($_POST['password']);

        }

$level=trim($_POST['level']);

 

//If there is no error, open the connection and send the email

        if(!isset($hasError)) {

 

$sql  ="INSERT INTO users (name,user,pass,email,level) VALUES ('$name','$user','$pass','$email','$level')";

 

echo $conn;

echo $name,$user,$pass,$level;

 

if (!mysqli_query($conn,$sql))

 {

 ?>

 <script>

alert("Account already exist!");

window.location.href="home.php";

</script>

<?php

 }

 else{

  $mail = new PHPMailer;

 

 

 $mail->isSMTP();                                      // Set mailer to use SMTP

 $mail->Host = 'mail.the-right-solution.com';          // Specify main and backup SMTP servers

 $mail->SMTPAuth = true;                               // Enable SMTP authentication

 $mail->Username = 'info@the-right-solution.com';      // SMTP username

 $mail->Password = 'Pwd@12345';                        // SMTP password

 $mail->Port = 25;                                     // TCP port to connect to

 

 $mail->From = 'info@the-right-solution.com';

 $mail->addAddress($email);                            // Add a recipient

 

 

 $mail->isHTML(true);                                  // Set email format to HTML

 

 $mail->Subject = 'User Information';

 $mail->Body    = '<h1>Hello </h1>  <p> Name : ' .$name .

                  '</p> <p> User : ' .$user  .

                  '</p> <p> Password : ' .$pass  .

                  '</p> <p> Level : ' .$level ;

  

   if(!$mail->send()) {

 $message.= 'Message could not be sent. ';

 $message.= 'Mailer Error: ' . $mail->ErrorInfo;

 } else {

 $message.= 'Message has been sent. ';

 }

  

 

 ?>

<script>

alert("To complete your registration, please check your mailbox for further instructions!");

window.location.href="home.php";

</script>

<?php

mysqli_close($conn);

// $mysql->close;

 }

}

else{

?>

<script>

alert('stuck here');

/*window.location.href="home.php";*/

</script>

<?php

}

}

else

 

{

header('Location: home.php');

}

?>

 

 

...login.php...

 

<?php

@session_start();

include_once 'connection.php';

 

     // Create connection

$mysqli = new mysqli($servername, $username, $password, $dbname);

// Check connection

if ($mysqli->connect_error) {

die("Connection failed: " . $mysqli->connect_error);

 

 

$allowed_codes=$mysqli->query("select * from users");

?>

 

<!DOCTYPE html>

<html>

<meta charset="UTF-8">

<head> 

<title>User Information</title>  

 

<style>

.error {color: #FF0000;}

</style>

 

 

  

<meta name="viewport" content="width=device-width, initial-scale=1">

<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">

 

 

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<script type="text/javascript" src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>

 

 

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> 

<link href="/support/../css/main.css" rel="stylesheet" type="text/css">

 

<script src="/support/../js/jquery.validate.js"></script>

<script src="/support/../js/home.js"></script>

 

 

 

 

</head>   

 

<style>

/*?>input[type="text"]{

width:93%;

}

input[type="password"]{

width:93%;

} */

 

#register{

display:none;

}

.error{

color:#F00;

}

 

 

</style>

 

</head>

<body id="main">

 

 

       <h1> User Information </h1>

        <section id="login">

        <form id="authform" form method="post" action="Authentication.php" >

            

            <!--<p> please enter your email and password below.</p>-->

            

 

  

 

             <div class="row">

    <div class="sm-8">

 

         

         <label>Email</label> 

  <input type="text" name="email" required="required" class="input-large" />

           </div>

</div>

  

      <div class="row">

    <div class="sm-8">

          <label> </label>

         <input name = "client" width="140" type="radio" id="client_login"  value="old" checked="checked" />I have a Password 

        </div>

</div>

        

        <div class="row">

    <div class="sm-8">

        <label> </label>

         <input name = "client" width="140" type="radio" value="new" />I'm New 

    

       </div>

</div>

        

        <div class="row">

   <div class="sm-4">

            

           <label>Password</label>

               

    <input id= "password" input name="password" type="password" size="8" maxlength="8" class="form-control" required="required"/>

   

      </div>

      </div>   

 

<div class="row">

   <div class="sm-4">                               

                        

        <a href="/support/" onclick="winOpen('forgotPassword.php','auto',500,300)" > <span style="color:#D00;font-size:10px" >Forgot Your Password?</span> </a>

   

       

      </div>

      </div> 

 

<div class="row">

  <div class="sm-8">

    

<input name="Login" type="submit" value="Login" class="btn_login" align="right" colspan="2"/> 

        

    </div>

</div>            

            

            

            </form>

            </section><!--#login-->

            

            

             <section id="register">

     <form method="post" action="register.php" name="registerform" id="registerform" onsubmit1="return validateForm()" onsubmit="return CheckPassword()"/>

                   

                    

                    <div class="row">

    <div class="sm-8">

        <label>Email</label>

         <input name = "email1" required="required"  type="text" size="40" class="input-large"/>

      

       </div>

</div>

  

      <div class="row">

    <div class="sm-8">

          <label> </label>

         <input name = "client" width="140" type="radio" value="old" />I have a Password 

       

       </div>

</div>

        

        <div class="row">

    <div class="sm-8">

        <label> </label>

         <input name = "client" width="140" type="radio" id="client_register" value="new" checked="checked"/>I'm New 

  

       </div>

</div>

       

       

        

        <div class="row">

   <div class="sm-4">

        <label>Name</label>

        <input name="name" type="text" size="20" maxlength="20" class="form-control" required="required" />

       

   </div>

</div>

    

    

   <div class="row">

    <div class="sm-4">

        <label>User</label>

        <input name="user" type="text" size="20" minlength="8" maxlength="20" class="form-control" required="required"/>

       

   </div>

</div>

 

        

        <div class="row">

   <div class="sm-4">

            

           <label>Password</label>

               

   <input id= "password" input name="password" type="password" size="8" maxlength="8" class="form-control" required="required"/>

   

     </div>

      </div>   

 

        <div class="row">

   <div class="sm-4">

            <label>Level</label>

      <select name="level" required="required"  id="level" class="form-control scroll" />

     <option value="0">1</option> 

</select>

 

   </div>

</div>

        

        <div class="row">

  <div class="sm-8">

    

<input name="Register" type="submit" value="REGISTER" class="button btn-danger" align="right" colspan="2"/> 

         <ul> </ul>

        

    </div>

</div>   

                                     

                <br /><br />

            

                </form>

                </section>

  

    </div>

<?php $mysqli->close(); ?>

</body>

 

<script type="text/javascript">

 

function validateForm() {

    var x = document.forms["registerform"]["name"].value;

    if (x==null || x=="") {

        alert("Name must be filled out");

        return false;

    }

    var x = document.forms["registerform"]["user"].value;

    if (x==null || x=="") {

        alert("User must be filled out");

        return false;

    }

var x = document.forms["registerform"]["password"].value;

    if (x==null || x=="") {

        alert("Password must be filled out");

        return false;

    }

 

var x = document.forms["registerform"]["level"].value;

    if (x==null || x=="") {

        alert("Level must be filled out");

        return false;

    }

    var x = document.forms["registerform"]["email"].value;

    var atpos = x.indexOf("@");

    var dotpos = x.lastIndexOf(".");

    if (atpos< 1 || dotpos<atpos+2 || dotpos+2>=x.length) {

        alert("Not a valid e-mail address");

        return false;

   }

}

</script>

 

<script type="text/javascript">

 

function CheckPassword() {   

    var error = "";

    var illegalChars = /[\W_]/; // allow only letters and numbers

 

    if (document.forms["registerform"]["password"].value == "") {

        document.forms["registerform"]["password"].style.background = 'Yellow';

        error = "You didn't enter a password.\n";

        alert(error);

        return false;

 

    } else if ((document.forms["registerform"]["password"].value.length < 8) ) {

        error = "The password is the wrong length. \n";

        document.forms["userForm"]["password"].style.background = 'Yellow';

        alert(error);

        return false;

 

    } else if (illegalChars.test(document.forms["registerform"]["password"].value)) {

        error = "The password contains illegal characters.\n";

        document.forms["registerform"]["password"].style.background = 'Yellow';

        alert(error);

        return false;

 

    } else if ( (document.forms["registerform"]["password"].value.search(/[a-zA-Z]+/)==-1) || (document.forms["registerform"]["password"].value.search(/[0-9]+/)==-1) ) {

        error = "The password must contain at least one numeral.\n";

        document.forms["registerform"]["password"].style.background = 'Yellow';

        alert(error);

        return false;

 

    } else {

        document.forms["registerform"]["password"].style.background = 'White';

    }

   return true;

}

</script>

</html>

 

 

 

Staff
11,186 Points
2015-02-06 6:30 pm
Are you receiving any error messages?
n/a Points
2015-02-09 1:44 pm

Hello, When I log in my cpanel there is no option for "comments"

Staff
26,137 Points
2015-02-09 2:37 pm
Hello Stephen,

Thanks for the question. We are a little puzzled by it. We're not sure if you're looking for a place to leave feedback, or if you are thinking that the interface is similar to WordPress where you can manage comments. The cPanel is the interface for installing software, accessing your hosting account files, managing email, ftp, security, domain options, security, and many other options. It's basically the control center for your hosting account. If you're looking at managing a website, then the interface depends on the software you used to build the website. If you can provide more information about what you are looking for specifically, then we would be happy to provide whatever support we can.

Kindest regards,
Arnel C.
n/a Points
2015-03-06 11:59 pm

Helo 

How can I place a "thank you page" in this PHP?

What would a example be ?

Staff
17,726 Points
2015-03-09 10:44 am
Hello Joe,

Thank you for contacting us. We are happy to help, but will need some additional information.

What type of "thank you page" do you want to place, and where?

Can you provide a link to an example page, etc.

Thank you,
John-Paul
n/a Points
2015-03-10 2:16 am

Very Nice

n/a Points
2015-03-14 10:45 am
the site is ok.good work
n/a Points
2015-04-08 11:08 am

Hi,

I have followed the steps and somehow "Thank you for your Comment!"; mysql_close($con);}?>" is displaying at the top of each page before I even submit anything. I can't seem to figure out why. Any feedback would greatly appreciated.

Thanks in advance!

Staff
26,137 Points
2015-04-08 11:31 am
Hello Eugene,

If you are seeing that portion of the code from above, then it's most likely happening because you didn't close the quotes with the echo command. Double-check your code and let us know if you have any further questions or comments.

Regards,
Arnel C.
n/a Points
2015-04-08 11:41 am

Hi Arnel,

My manage_comments code is as follows:

<?

if( $_POST )

{

 $con = mysql_connect("localhost","","");

 

  if (!$con)

  {

    die('Could not connect: ' . mysql_error());

  }

  mysql_select_db("verifytrade", $con);

 

  $users_name = $_POST['name'];

  $users_email = $_POST['email'];

  $users_website = $_POST['website'];

  $users_comment = $_POST['comment'];

 

  $users_name = mysql_real_escape_string($users_name);

  $users_email = mysql_real_escape_string($users_email);

  $users_website = mysql_real_escape_string($users_website);

  $users_comment = mysql_real_escape_string($users_comment);

  

  $articleid = $_GET['id'];

 

  if( ! is_numeric($articleid) )

    die('invalid article id');

 

  $query = "

  INSERT INTO `verifytrade`.`comments` (`id`, `name`, `email`, `website`,

        `comment`, `timestamp`, `articleid`) VALUES (NULL, '$users_name',

        '$users_email', '$users_website', '$users_comment',

        CURRENT_TIMESTAMP, '$articleid');";

 

  mysql_query($query);

 

  echo "<h2>Thank you for your Comment!</h2>";

 

  mysql_close($con);

}

?>

 

Thanks!

Staff
26,137 Points
2015-04-08 1:20 pm
Hello,
Make sure to put the "<?php" in place the current statement and then your code should work. If you have any further questions or comments, please let us know.

Regards, Arnel C.
n/a Points
2015-04-10 8:11 am

Hi, the pages now work and when I click submit the "Thank You" message appears but nothing write to my database? 

 

My manage_comments.php is as follows:

<body>

<?php

if( $_POST )

{

  $con = mysqli_connect("localhost","root","");

 

 

  mysqli_select_db($con, "verifytrade");

 

  if (!$con)

  {

    die('Could not connect: ' . mysql_error());

  }

 

  $users_name = $_POST['name'];

  $users_email = $_POST['email'];

  $users_comment = $_POST['comment'];

 

  $users_name = mysql_real_escape_string($users_name);

  $users_email = mysql_real_escape_string($users_email);

  $users_comment = mysql_real_escape_string($users_comment);

 

  $query = "

  INSERT INTO `verifytrade`.`comments` (`id`, `name`, `email`,`comment`, 

  `timestamp`) VALUES (NULL, '$users_name',

        '$users_email', '$users_comment',

        CURRENT_TIMESTAMP);";

 

  mysql_query($query);

 

  echo "<h2>Thank you for your Comment!</h2>";

 

  mysqli_close($con);

}

?>

 

</body>

 

Thanks in advance. This has been a lot of help!

Staff
29,164 Points
2015-04-13 8:27 am
Hello,

You will need to have rthe query print to the screen to see if it has the information you expect. Also, it is a good idea to error trap the query call so you can see any error messages that the function throws.

Kindest Regards,
Scott M
n/a Points
2015-04-13 6:33 am

<?php

include('connection.php');

mysql_select_db('employee');

error_reporting(1);

$query="INSERT INTO emp_info VALUES ('', '$name','$Address','$email','$mobial')";

mysql_query($query);

?>

<html>

<body>

 

<form method="post" enctype="multipart/form-data">

  <table align="left">

    <tr align="left">

      <th>Name :</th>

      <th><input type="text" name="name" required></th>

    </tr>

    <tr align="left" valign="top">

      <th>Address :</th>

      <th><textarea rows="4" cols="21" name="Address" required></textarea></th>

    </tr>

    <tr align="left">

      <th>email :</th>

      <th>        <input type="text" name="email" required>      </th>

    </tr>

    <tr align="left">

      <th width="100">Mobial :</th>

      <th width="100">        <input type="text" pattern="[0-9]*" maxlength="10" name="mobial" required>      </th>

    </tr>

    <tr>

      <th colspan="2"><input type="submit"  value="INSERT"></th>

   </tr>

  </table>

</form>

 

</body>

</html>

plese help me to insert data to database with php

i am a many try but program sucssess but data not inserted

 

Staff
29,164 Points
2015-04-13 5:05 pm
Hello manoj,

You will want to use normal code troubleshooting techniques such as printing out the query variable to see what is being created. Also, you can add error trapping to see if the query function is throwing any error codes.

Kindest Regards,
Scott M
n/a Points
2015-05-08 8:16 pm

This is the error message I receive upon submit:

Warning: mysql_connect(): Access denied for user 'afx_u1'@'localhost' (using password: YES) in /home/afx/public_html/dev/manage_comment.php on line 4 Could not connect: Access denied for user 'afx_u1'@'localhost' (using password: YES)

My password is not YES, and it is entered correctly (i'm positive)

What can I test or change to make this work?

Staff
17,726 Points
2015-05-11 11:25 am
Hello Tubby,

Thank you for contacting us. Make sure you have created the user and gave them permission to access the database.

Also, check the database, and database username for typos or misspellings.

Thank you,
John-Paul
n/a Points
2015-06-10 4:49 pm

Hi, Not sure if you could help. I have followed the guide but when I click submit I get half an error of:

Thank you for your Comment!"; mysql_close($con); } ?>

Which looks like its not understanding the close connection as a function and just echoing it.

Also it is not uploading to my SQL database.

 

My code as follows:

###########

 

<?php

if( $_POST )

{

  $con = mysql_connect("localhost","root","password");

 

  if (!$con)

  {

    die('Could not connect: ' . mysql_error());

  }

 

  mysql_select_db("paranormal", $con);

 

  $users_name = $_POST['name'];

  $users_email = $_POST['email'];

  $users_region = $_POST['dropdown'];

  $users_where = $_POST['where'];

  $users_when = $_POST['date'];

  $users_comment = $_POST['comment'];

 

  $users_name = mysql_real_escape_string($users_name);

  $users_email = mysql_real_escape_string($users_email);

  $users_region = mysql_real_escape_string($users_region);

  $users_where = mysql_real_escape_string( $users_where); 

  $users_when = mysql_real_escape_string($users_when);

  $users_comment = mysql_real_escape_string($users_comment);

 

  $articleid = $_GET['id'];

  if( ! is_numeric($articleid) )

    die('invalid article id');

 

  $query = "INSERT INTO `paranormal`.`comments` (`id`, `name`, `email`, `when`, `where`, `comment`, `timestamp`, `articleid`, `Region`) VALUES (NULL, '$users_name', '$users_email', '$users_when', '$users_where', '$users_comment', CURRENT_TIMESTAMP, '$articleid', '$users_region');";

  

 mysql_query($query);

 

  echo "<h2>Thank you for your Comment!</h2>";

 

mysql_close($con);

}

 

?>

n/a Points
2015-06-25 4:09 pm

Dear Sir / Madam, 

I have followed exactly the steps but when I enter the details, it shows 

"Notice: Undefined index: id in C:\xampp\htdocs\manage_comments.php on line 23

invalid article id"

Line 23: $articleid = $_GET['id'];

I have tried many ways, like inserting "issets( )" but it still doesn't work. 

May I kindly request for your help please? Thank you? 

 

 

Staff
17,726 Points
2015-06-25 7:27 pm
Hello Danzo,

Thank you for contacting us. Since this is just one guide in a 7 section series, have you completed the previous guides too?

Unfortunately, it is difficult for us to troubleshoot code, especially in a xampp environment, since I have no way of knowing if it was setup correctly. Similar to other questions above, you will want to use normal code troubleshooting techniques such as printing out the query variable to see what is being created. Also, you can add error trapping to see if the query function is throwing any error codes.

Thank you,
John-Paul
n/a Points
2015-06-29 10:55 am

I need help.I cant able to find errors in this codes.It failed to insert data into the database created in phpmyadmin and im using xampp.

<html>

<body>

<?php 

 

$con = mysql_connect("localhost","root","");

if (!$con)

{

  die('Could not connect: ' . mysql_error());

}

mysql_select_db("patients", $con);

$sql="INSERT INTO `patients`(`id`, `patient_name`, `patient_pass`, `patient_email`) VALUES ([value-1],[value-2],[value-3],[value-4])

('$_POST[id]','$_POST[patient_name]','$_POST[patient_pass]','$_POST[patient_email]')";

 

 

if (!mysql_query($sql,$con))

{

  die('Error: ' . mysql_error());

}

else

{

echo "You are successfully registered!!!";

}

 

mysql_close($con);

?>

</font>

</br>

</br>

<input type="button"value="Finish"onclick="history.go(-2);return true;">

</table>

</body>

</html>

Staff
29,164 Points
2015-06-29 3:16 pm
Hello dineas,

You will first want to rule out the query itself by testing it alone within the phpmyadmin. You then will also want to test the error code when it does the Insert in the php.

Kindest Regards,
Scott M
n/a Points
2015-06-30 3:54 pm

please help me solve this: uploading a file is the problem.

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>HOME</title><link rel="stylesheet" href="/support/../CSS/general.css"  /></head><body><?phpinclude("../menu.php");?><div id = "content"><div id="left-side"><h2>farming tools</h2><div id="upload"><table ><form  enctype="multipart/form-data" action="" method="POST" name="f tools"><legend></legend><tr align="center"><td> <label>FIRST NAME:</label></td><td><input name="name" type="text" /> </td></tr><tr align="center"><td><label>ITEM NAME:</label></td><td><input name="item" type="text" /> </td></tr><tr align="center"><td><label>Price:</label></td><td><input name="PRICE" type="text" required="required"/> </td></tr><tr align="center"><td><label>LOCATION:</label></td><td><input name="location" type="text" /> </td></tr><tr align="center"><td><label>PHONE NO:</label></td><td><input name="phone" type="text" /> </td></tr><tr align="center"><td><label>EMAIL:</label></td><td><input name="email" type="email"  required="required"/> </td></tr><tr>    <td>Select image to upload:</td><td>    <input type="file" name="upload" />    </td></tr><tr align="center"><td><label>details:</label></td><td><textarea id = "Message" name = "Message" type = "text" placeholder = "Type Message Here" data-validate = "required">                            </textarea></td></tr> <tr><td><input  class="submit" type="submit" value="update" name="update"/></form> <?php                if(isset($_POST["update"])){                                if(!empty($_POST['email'])  && !empty($_POST['PRICE']) ) {                $Name=$_POST["name"];                $item=$_POST["item"];                $email=$_POST['email'];                $price=$_POST['PRICE'];                $location=$_POST['location'];                $phone=$_POST['phone'];                $upload=$_FILES['upload']['name'];                $tmp_name  = $_FILES['upload']['tmp_name'];               $message=$_POST['Message'];                                           include("../connect.php");                                  move_uploaded_file($_FILES['upload']['tmp_name'],"../upload/".$_FILES['upload']['name']) or die(mysql_error());                               $sql="INSERT INTO tool (Name, itemName,    PRICE, location, phone,    email, image, description)                 VALUES ('$Name','$item','$price','$location','$phone','$email','$upload','$message')";                                if($result=mysqli_query($con,$sql)){                echo "Thank you, your item was posted successfully";                } else {                                    echo "Failure!";                }                    }                mysqli_close($con);                }                             ?></td></tr> </table><?phpecho "<BR/>";?>    <!-- what to buy --> </div> </div> <div align="right"> <img src="/support/../slide/img/home/tanks.png" width="501" height="450"/> </div></div> <?php include("../footer.php"); ?></body></html>

Staff
5,084 Points
2015-07-01 12:59 am
Hello Shwe,

What error are you getting when you try to upload files? Are you trying to upload files into the database or just onto the server?

Best Regards,
TJ Edens
n/a Points
2015-07-04 6:24 pm

Could someone please tell me what other reason besides wrong credentials would cause me to get an access denied error message with this code? I have checked the users access and set the password several times to ensure that it is right. Could not connect: Access denied for user 'db_username'@'localhost' (using password: YES)[code]<?if( $_POST ){  $con = mysql_connect("localhost","db_username","lamepassword");  if (!$con)  {    die('Could not connect: ' . mysql_error());  }  mysql_select_db("database_name", $con);  $users_name = $_POST['name'];  $users_email = $_POST['email'];  $users_website = $_POST['website'];  $users_comment = $_POST['comment'];  $users_name = mysql_real_escape_string($users_name);  $users_email = mysql_real_escape_string($users_email);  $users_website = mysql_real_escape_string($users_website);  $users_comment = mysql_real_escape_string($users_comment);  $articleid = $_GET['id'];  if( ! is_numeric($articleid) )    die('invalid article id');  $query = "  INSERT INTO `database_name`.`comments` (`id`, `name`, `email`, `website`,        `comment`, `timestamp`, `articleid`) VALUES (NULL, '$users_name',        '$users_email', '$users_website', '$users_comment',        CURRENT_TIMESTAMP, '$articleid');";  mysql_query($query);  echo "<h2>Thank you for your Comments!</h2>";  mysql_close($con);}?>[/code]

Staff
26,137 Points
2015-07-06 3:34 pm
Jack,

To be honest, if that error appears, then the problem has to do with the credentials. I know you're asking for another possible reason, but in this case it typically no other reason than credentials. You may need to double-check what USER is assigned to run the script as well. I hope this helps to answer your question, please let us know if you require any further assistance.

Regards,
Arnel C.
n/a Points
2015-07-10 5:50 am

it is not working . plz es ko thek kr mujy send kre

<html>

<head> 

<title> Table of Student</title>

</head>

<body>

<table border="1">

<tr> 

<th>Std_ID</th>

<th>Std_Name</th>

<th>Std_Address</th>

<th>Std_Email</th>

</tr>

</table>

</body>

</html>

 

<?php

$servername = "localhost";

$username = "root";

$password = "";

$dbname = "University";

 

// Create connection

$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection

if (!$conn) {

    die("Connection failed: " . mysqli_connect_error());

}

$sql = "INSERT INTO student*

VALUES ('1', 'Faisal', 'M.B.DIN','mfs.uos@gmail.com')";

 

 

 

$conn->close();

?>

 

Staff
17,726 Points
2015-07-13 1:22 pm
Hello faisal,

Thank you for contacting us. We can help you troubleshoot, but will need some additional information. What happens when you try to use the script? Do you get any errors?

Also, have you verified the database settings are correct? Specifically these:
$username = "root";
$password = "";
$dbname = "University";

Thank you,
John-Paul
n/a Points
2015-07-10 3:26 pm

Hello, thanks for the codes but i'm encoutering some problems. First, i am not sure my database even connects to the form page. Secondly, if its connecting, data is not been inserted into the data base. I can't seen to find the problem, please help me.

Here is the html for the form:

<html>

<head>

<title>test</title>

</head>

<body>

<h1>This is page1.php</h1>

<div><a href='page2.php?id=2'>Click here</a> to go to page2.php</div>

<div style='margin:20px; width:100px; height:100px; background:blue;'></div>

  <form action='contact.php' method='post'>

  NAME: <input type='text' name='name' id='name' required /><br />

  Email: <input type='email' name='email' id='email' required /><br />

  Website: <input type='text' name='website' id='website' required /><br />

  Comment:<br />

  <textarea name='comment' id='comment' required ></textarea><br />

  <input type='submit' value='Submit' />  

</form>

</body>

</html>

And here is the PHP (contact.php):

<?php

  $users_name = $_POST['name'];

  $users_email = $_POST['email'];

  $users_website = $_POST['website'];

  $users_comment = $_POST['comment'];

 

  $database= "comments";

  $password= "password";

  $username= "username";

  

if($users_name&&$users_email&&$users_website&&$users_comment){

  $con = mysql_connect("localhost", $username, $password) or die("Could not connect");

  

  @mysql_select_db("comments", $con) or die("Unable to Connect");

 

  mysql_query("INSERT INTO `comments`.`test` (`id`, `Name`, `Email`, `Website`, `Comment`) 

VALUES ("", '$users_name', '$users_email', '$users_website', '$users_comment');") or die("Strange error");

 

  echo "Comment Posted";

 

  mysql_close($con);

 

 header("location:index.html");

 

} else{

  echo "You need to fill all options";

}

?>

Please, is there a way I can test if my database is connected?

Anticipating your quick response.

Staff
17,726 Points
2015-07-13 1:32 pm
Hello Lord,

Thank you for contacting us. I looked at your code, and if the database connection fails, you should see a message stating: "Could not connect"

If you do not see this error message, you most likely are connecting successfully.

Thank you ,
John-Paul
n/a Points
2015-07-15 1:26 am

 Why won't my form data insert properly into my MySQL database? .

Staff
17,726 Points
2015-07-15 9:17 am
Hello olivia,

Thank you for contacting us. We will need some additional information. What steps are you taking? Are you following the above guide?

Are you getting an error message?

Please include any additional information to help you troubleshoot further.

Thank you,
John-Paul
n/a Points
2015-07-16 1:30 pm

I need a help. I need the php codes for the patients to book an appointment with the specific doctors after they have been registers into the system. After,the patient booked an appointment,the selected doctor should able to view the appointment and able to approve or reject the appointment by click the approve and reject button. Im also need the validation codes for dates to check whether the dates are available or not.Can someone help me,please?

Staff
17,726 Points
2015-07-16 1:57 pm
Hello Dineas,

Thank you for contacting us. We are happy to help guide you, but you will need an actual developer to code a custom solution for this.

This is because it will require more access and troubleshooting before the code can be created.

Thank you,
John-Paul
n/a Points
2015-07-26 12:11 pm

I have encountered some errors while registering new doctor but the data is added to the database.The errors encountered are,

Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\clinicosight\doctors.php on line 7Warning: fopen(): Filename cannot be empty in C:\xampp\htdocs\clinicosight\doctors.php on line 23Warning: fread() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\clinicosight\doctors.php on line 24Warning: fclose() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\clinicosight\doctors.php on line 26Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\clinicosight\doctors.php on line 46Notice: Undefined variable: maxpatid in C:\xampp\htdocs\clinicosight\doctors.php on line 50Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\clinicosight\doctors.php on line 51

please edit the codes below and help me with it.Thanks

<?php

 

include("validation/header.php");

include("dbconnection.php");

$result = mysql_query("SELECT MAX(docid) FROM doctor");

while($row = mysql_fetch_array($result))

  {

$maxpatid = $row[0];

$maxpatid++;

  }

 

//insert doctors record

if(isset($_POST["button"]))

{

 

// UPLOAD IMAGE CODE

 

// Temporary file name stored on the server

      $tmpName  = $_FILES['image']['tmp_name'];  

       

      // Read the file 

      $fp      = fopen($tmpName, 'r');

      $data = fread($fp, filesize($tmpName));

      $data = addslashes($data);

      fclose($fp);

 

 

//UPLOAD IMAGE CODE ENDS HERE AND IMAGE BINARY VALUE STORES IN VARIABLE $data

 

$sql="INSERT INTO doctor(doctorname, quali, specialistin, contactno, emailid, image, biodata,password )

VALUES

('$_POST[dfn] $_POST[dmn] $_POST[dln]' ,'$_POST[quali]','$_POST[spin]','$_POST[contact]','$_POST[emailid]','$data','$_POST[bio]','$_POST[password]')";

 

if (!mysql_query($sql,$con))

 {

 die('Error: ' . mysql_error());

 }

  

}

?>

<?php

if(isset($_POST["button"]))

{

$result = mysql_query("SELECT MAX(docid) FROM doctor");

while($row = mysql_fetch_array($result))

  {

$maxpatid = $row[0];

  }

$docrec = mysql_query("SELECT * FROM doctor where docid ='$maxpatid'");

while($row = mysql_fetch_array($docrec))

  {

   

echo "<form id='formID1' class='formular' method='post' enctype='multipart/form-data'>";

echo "<b>Doctor Record inserted successfully.. <br><br>";

//image code ends here

echo "Doctor ID is : $row[docid]<br><br>";

echo "Doctor Name : $row[doctorname]<br><br>";

echo "Qualification : $row[quali]<br><br>";

 echo "Specialist in : $row[specialistin]<br><br>";

  echo "Contact No : $row[contactno]<br><br>";

   echo "Email ID : $row[emailid]<br><br>";

echo "Biodata : $row[biodata]<br><br>";

 

 

echo "</b></form>";

 }

 

}

else

{

?>        

<form id="formID" class="formular" method="post"  enctype="multipart/form-data">

  

    <div align="center"><strong>Doctors</strong></div>

 

  

    <p>Doctor ID

      <label for="dfn2"></label>

      <input type="text" name="dfn2" id="dfn2"  class="validate[required] text-input" readonly value="<?php echo $maxpatid; ?>"/>

      <label for="textfield4">Password</label>

      <input type="password" name="password" id="password"  class="validate[required] text-input"/>

      <label for="textfield3"> </label>

Confirm Password

<input type="password" name="textfield5" id="textfield5" class="validate[required,equals[password]] text-input" />

First Name

<label for="dfn"></label>

      <input type="text" name="dfn" id="dfn"  class="validate[required] text-input">

      

      

      Middle Name

      <input type="text" name="dmn" id="dmn"  class="validate[required] text-input">

      

      

      Last Name

      <input type="text" name="dln" id="dln"  class="validate[required] text-input">

      

      

      Qualification

      <input type="text" name="quali" id="quali"  class="validate[required] text-input">

      

      

      Specialist in 

      <input type="text" name="spin" id="spin" class="validate[required] text-input"/>

      <label for="spid"></label>

      

      Contact No

      <input type="text" name="contact" id="contact" class="validate[required] text-input">

      

      

      Email ID

      <input type="text" name="emailid" id="emailid" class="validate[required,custom[email]] text-input">

      

      

      Image

      <label for="image"></label>

      <input name="image" accept="image/jpeg" type="file">

      

      

      Bio-data

      <label for="bio"></label>

      <textarea name="bio" id="bio" cols="45" rows="5" ></textarea>

  </p>

<p>&nbsp;</p>

    <div align="center">

      <input type="submit" name="button" id="button" value="Add"  class="submit">

       &nbsp;&nbsp;&nbsp;&nbsp;<input type="submit" name="button2" id="button2" value="Cancel"  class="submit">

  </div><br /><br />

</form>

<?php

}

 

?>

Staff
29,164 Points
2015-07-27 2:37 pm
Hello,

Unfortunately we are not able to provide custom code support. You may want to check the php documentation online to see what you need to change in order for your form to work properly.

Since you are going to work on it anyway, you may want to explore using mysqli instead of mysql as the one mysql will be replaced eventually.

Kindest Regards,
Scott M
2015-08-28 8:43 am
there is no error in my code ,,,and still the data is not inserted into the database
Staff
5,084 Points
2015-08-28 11:47 am
Hello Maxeekhan,

Have you tried doing a var_dump($query); right after the insert variable to make sure its spitting out all of the required information?

Best Regards,
TJ Edens

Post a Comment

Name:
Email Address:
Phone Number:
Comment:
Submit

Please note: Your name and comment will be displayed, but we will not show your email address.

95 Questions & Comments

Post a comment

Back to first comment | top

Need more Help?

Search

Ask the Community!

Get help with your questions from our community of like-minded hosting users and InMotion Hosting Staff.

Current Customers

Chat: Click to Chat Now E-mail: support@InMotionHosting.com
Call: 888-321-HOST (4678) Ticket: Submit a Support Ticket

Not a Customer?

Get web hosting from a company that is here to help. Sign up today!