Connecting Php, html, and mysql - php

Can someone look over my code and let me know what's wrong with it?
The problem I'm having is that when I enter text to the 3 fields and hit submit, it doesn't insert to my database (mysql, with phpmyadmin as gui). No error messages or anything; it simply doesn't insert the data..
I have looked over the code over and over, and I can't pin point what's wrong with it.
//---------------------------This is my index.php------------------------------
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Web Bar Title</title>
<link rel="stylesheet" href="styles.css" type="text/css" />
</head>
<body>
<?php
if(isset($_POST['Submit']))
{
include 'connectdb.php';
include 'openconnection.php';
$first = $_POST['first'];
$second = $_POST['second'];
$third = $_POST['third'];
$query = "INSERT INTO details (first, last, third) VALUES('$first','$second','$third');";
mysql_query($query) or die('Error, insert query failed');
}
?>
<div id="page">
<tbody>
<form method="post">
<table>
<tr>
<td ><b>First</b></td>
<td><input name="first" type="text" id="first"></td>
<tr>
<tr>
<td ><b>Second</b></td>
<td><input name="second" type="text" id="second"></td>
<tr>
<td ><b>Company</b></td>
<td><input name="third" type="text" id="third" > </td>
</tr>
</table>
<input name="submit" type="submit" id="submit" value="Submit" />
</form>
</body>
</html>
</tbody>
</div>
//---------------------------------connectdb.php------------------------------------------
<?php
$dbhost = 'localhost';
$dbuser = 'sharkk';
$dbpass = 'pw';
$dbname = 'test';
?>
//---------------------------------openconnection.php-------------------------------------
<?php
$dbhost = 'localhost';
$dbuser = 'sharkk';
$dbpass = 'pw';
$dbname = 'test';
?>
<?php
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
mysql_select_db($dbname) or die ('No Selection of Database');
?>
EDIT: It would be easier and faster to communicate via MSN/AIM/Steam/Skype, if anyone has any of those!

Change your top line to
if( isset( $_POST['submit'] ) ) {
I can't remember if it is case sensitive or not

Better still change it to
if($_SERVER['REQUEST_METHOD'] == 'POST')
The isset() method on the submit button is unreliable because Internet Explorer will not send the submit button as a post variable if the user presses the enter key to submit the form, and thus your code will not detect a form submission.

Just check MYSQL INSERT query in Your own MySQL platform, by simply copying your INSERT query and paste in your MySQL database, and check there. it wil report your fault.
If I'm right, then your problem lies on your INSERT query part. You have stated :
$query = "INSERT INTO details (first, last, third) VALUES('$first','$second','$third');";
In the above part, there shouldn't be 2 semicolons, Jus one is enough... it wil look like :
$query = "INSERT INTO details (first, last, third) VALUES('$first','$second','$third')";
Also, check ur include part too...
it shouldnt be :
include 'connectdb.php'; //braces r missing
include 'openconnection.php'; // braces r missing
it should be :
include ('connectdb.php');
include ('openconnection.php');
I hope this may do good fa U ....
CHEERS buddy.........

Try putting the values between double quotes instead of single quotes
VALUES("$first","$second","$third")

Related

Why will my input form not find a matching user to my search inside of my table?

I am trying to create a PHP search that looks through my table (users) and finds the user that matches the name they searched for and displays it on the screen. But the program won't display the user I searched up, and I don't know why. The variables all check out, and I didn't misspell anything in the code or table. My ifelse statement tells me that there is no query result, even though the user in the table and the user I searched are identical. I am using PHPMyAdmin to manage the tables and see changes (if there are any) to the table. The result I wanted was for the program to display the user and email on the page. I can't find a solution, so if you can please tell me!
addnone.php
<?php
include_once 'includes/db_connect.php';
?>
<!DOCTYPE html>
<html>
<head>
<title>SCIENCE FAIR</title>
<link rel="stylesheet" href="style.css">
<section class="container grey-text">
<form class="white" action="addnone.php" method="POST">
<tr>
<label>First Name:</label>
<td><input type="text" name="firstname" placeholder="First Name"></td></br>
</tr>
<div class="center">
<td colspan="2"><input type="submit" name="submit" value="Search"></td>
</div>
</form>
<div class="box">
<?php
if (isset($_POST['submit'])) {
$firstname = $_POST['firstname'];
$sql = "SELECT * FROM users WHERE name = '%$firstname%'";
$result = mysqli_query($conn, $sql);
$queryResult = mysqli_num_rows($result);
if ($queryResult > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "<div>
<p>".$row['name']."<p>
<p>".$row['email']."<p>
</div>";
}
} else {
echo "No users with name $firstname!";
}
}
?>
</div>
</section>
</html>
db_connect.php
<?php
$dbServername = "localhost";
$dbUsername = "scifair";
$dbPassword = "password";
$dbName = "scifair";
// connect to database
$conn = mysqli_connect($dbServername, $dbUsername, $dbPassword, $dbName);
// check connection
if(!$conn){
echo 'Connection error: ' . mysqli_connect_error();
}
?>
Use "LIKE" Operator
$sql = "SELECT * FROM users WHERE name LIKE '%$firstname%'";

Unable to insert mysql database through form data

I have created a form where I want to insert mysql database when I submit the values but when I click on the submit button the database isnt updated.. dont know where I am going wrong in my code..
<html>
<head>
<title>Form Data</title>
</head>
<body>
<form action="form.php" method="post">
Server Name: <input type="text" name="server_name"> <br />
IP Address: <input type="text" name="ip_address"> <br />
Server Role: <input type="text" name="server_role"> <br />
<input type="submit" name="submit">
</form>
<?php
if (isset($_POST['submit'])) {
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "abcx";
$dbname = "serverasset_inventory";
$connection = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
$sql = "INSERT INTO asset_inventory (server_name,ip_address,server_role)
VALUES ('$_POST[server_name]','$_POST[ip_address]'),'$_POST[server_role]')";
$state = mysqli_query($connection,$sql);
mysqli_close($connection);
}
?>
</body>
</html>
Any help?
-A
you are using a extra bracket between query and missing quote in variable's use like below
$sql = "INSERT INTO `asset_inventory` (`server_name`,`ip_address`,`server_role`)
VALUES ('".$_POST['server_name']."','".$_POST['ip_address']."','".$_POST['server_role']."')";
if you want to insert the fields
for example
your sql will be take in variables then insert it in sql
$server_name = $_POST['server_name'];
$ip_address = $_POST['ip_address'];
$server_role = $_POST['server_role'];
insert into asset_inventory (server_name,ip_address,server_role) VALUES ('$server_name','$ip_address','$server_role';

PHP login script will only login a specific user ?

I have been using this login script for a long time and its quite solid but its now broken and driving me insane.
Basically the script only accepts the first MySQL row user to login , the login system will work but just for the first SQL row , it appears to ignore all of the rows ?
global_database.php
<?php
$dbhost = 'localhost';
$dbuser = 'dealerpa_guest';
$dbpass = 'password_here';
function dbConnect($db='') {
global $dbhost, $dbuser, $dbpass;
$dbcnx = #mysql_connect($dbhost, $dbuser, $dbpass)
or die('We are currently applying some major patches and fixes to our systems. Please try again in 10 Minutes.');
if ($db!='' and !#mysql_select_db($db))
die('We are currently applying some major patches and fixes to our systems. Please try again in 10 Minutes.');
return $dbcnx;
}
?>
global_restriction.php
<?php
session_start();
include_once 'global_database.php';
include_once 'global_common.php';
$dealerUsername = isset($_POST['dealerUsername']) ? $_POST['dealerUsername'] : $_SESSION['dealerUsername'];
$pwd = isset($_POST['pwd']) ? $_POST['pwd'] : $_SESSION['pwd'];
if(!isset($dealerUsername)) {
?>
<html>
<body>
<form id="dealerLogin" name="dealerLogin" method="post" action="">
<input name="dealerUsername" type="text" id="dealerUsername" size="15" class="validate[required] text-input" />
<input name="pwd" type="password" id="pwd" size="15" class="validate[required] text-input" />
<input name="submit" id="submit" type="submit" value="Login" class="save-button" />
</form>
<?php
exit;
}
$_SESSION['dealerUsername'] = $dealerUsername;
$_SESSION['pwd'] = $pwd;
dbConnect("dealerpa_account");
$sql = "SELECT * FROM dealerAccount WHERE dealerUsername = '$dealerUsername' AND dealerPassword = md5('$pwd')";
$result = mysql_query($sql);
if (!$result) {
error('A database error occurred while checking your '.
'login details.\\nIf this error persists, please '.
'contact us.');
}
if (mysql_num_rows($result) == 0) {
unset($_SESSION['dealerUsername']);
unset($_SESSION['pwd']);
?>
<html>
<body>
<p>Display Login page again if password is wrong</p>
</body>
<?php
exit;
}
$dealerUsername = mysql_result($result,0,'dealerUsername');
$dealerID = mysql_result($result,0,'dealerID');
?>
I have checked the PHP settings and register globals is turned on , is there anything else I can try. The strange thing is only one user can login . Its like the script isn't checking the entire table and only looking at the first SQL Row.
Any help will be much appreciated.
I guess thats happening because your row index is set to 0 in mysql_result().Instead of using mysql_result try mysql_fetch_assoc. It will retrieve the user info in associated array. Hope that helps.

PHP insert data to Mysql

I am experimenting with PHP and Mysql. I have created a database and table at mu localhost using xampp. I have also created a file that suppose to populate my table by executing a query, but the strange thing is that i get no errors but at the same time no DATA has been inserted into my DataBase:
CODE:
register.php:
<?php
session_start();
if(isset($_POST['submitted'])){
include('connectDB.php');
$UserN = $_POST['username'];
$Upass = $_POST['password'];
$Ufn = $_POST['first_name'];
$Uln = $_POST['last_name'];
$Uemail = $_POST['email'];
$NewAccountQuery = "INSERT INTO users (user_id,username, password, first_name, last_name, emial) VALUES ('$UserN','$Upass', '$Ufn', '$Uln', '$Uemail')";
if(!mysql_query($NewAccountQuery)){
die(mysql_error());
}//end of nested if statment
$newrecord = "1 record added to the database";
}//end of if statment
?>
<html>
<head>
<title>Home Page</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="wrapper">
<header><h1>E-Shop</h1></header>
<article>
<h1>Welcome</h1>
<h1>Create Account</h1>
<div id="login">
<ul id="login">
<form method="post" action="register.php" >
<fieldset>
<legend>Fill in the form</legend>
<label>Select Username : <input type="text" name="username" /></label>
<label>Password : <input type="password" name="password" /></label>
<label>Enter First Name : <input type="text" name="first_name" /></label>
<label>Enter Last Name : <input type="text" name="last_name" /></label>
<label>Enter E-mail Address: <input type="text" name="email" /></label>
</fieldset>
<br />
<input type="submit" submit="submit" value="Create Account" class="button">
</form>
</div>
<form action="index.php" method="post">
<div id="login">
<ul id="login">
<li>
<input type="submit" value="Cancel" onclick="index.php" class="button">
</li>
</ul>
</div>
</article>
<aside>
</aside>
<div id="footer">This is my site i Made coppyrights 2013 Tomazi</div>
</div>
</body>
</html>
I have also one include file which is connectDB:
<?php
session_start();
$con = mysql_connect("127.0.0.1", "root", "");
if(!$con)
die('Could not connect: ' . mysql_error());
mysql_select_db("eshop", $con) or die("Cannot select DB");
?>
Database structure:
database Name: eshop;
only one table in DB : users;
users table consists of:
user_id: A_I , PK
username
password
first_name
last_name
email
I spend a substantial amount of time to work this out did research and looked at some tutorials but with no luck
Can anyone spot what is the root of my problem...?
It is because if(isset($_POST['submitted'])){
you dont have input field with name submitted give the submit button name to submitted
<input name="submitted" type="submit" submit="submit" value="Create Account" class="button">
Check your insert query you have more fields than your values
Change :
$NewAccountQuery = "INSERT INTO users (user_id,username, password, first_name, last_name, email) VALUES ('$UserN','$Upass', '$Ufn', '$Uln', '$Uemail')";
to :
$NewAccountQuery = "INSERT INTO users (user_id,username, password, first_name, last_name, email) VALUES ('','$UserN','$Upass', '$Ufn', '$Uln', '$Uemail')";
Considering user_id is auto increment field.
Your email in query is written wrongly as emial.
Is error reporting turned on?
Put this on the top of your screen:
error_reporting(E_ALL);
ini_set('display_errors', '1');
Some good answers above, but I would also suggest you make use of newer MySQLi / PDO instead of outdated 2002 MySQL API.
Some examples: (i will use mysqli since you wrote your original example in procedural code)
connectDB.php
<?php
$db = mysqli_connect('host', 'user', 'password', 'database');
if (mysqli_connect_errno())
die(mysqli_connect_error());
?>
register.php -- i'll just write out an example php part and let you do the rest
<?php
//i'll always check if session was already started, if it was then
//there is no need to start it again
if (!isset($_SESSION)) {
session_start();
}
//no need to include again if it was already included before
include_once('connectDB.php');
//get all posted values
$username = $_POST['username'];
$userpass = $_POST['password'];
$usermail = $_POST['usermail'];
//and some more
//run checks here for if fields are empty etc?
//example check if username was empty
if($username == NULL) {
echo 'No username entered, try again';
mysqli_close($db);
exit();
} else {
//if username field is filled we will insert values into $db
//build query
$sql_query_string = "INSERT INTO _tablename_(username,userpassword,useremail) VALUES('$username','$userpass','$usermail')";
if(mysqli_query($db,$sql_query_string)) {
echo 'Record was entered into DB successfully';
mysqli_close($db);
} else {
echo 'Ooops - something went wrong.';
mysqli_close($db);
}
}
?>
this should work quite nicely and all you need to add is your proper posted values and build the form to post it, that's all.
<?php
$db = mysqli_connect('host', 'user', 'password', 'database');
if (mysqli_connect_errno())
die(mysqli_connect_error());
?>
register.php -- i'll just write out an example php part and let you do the rest
<?php
//i'll always check if session was already started, if it was then
//there is no need to start it again
if (!isset($_SESSION)) {
session_start();
}
//no need to include again if it was already included before
include_once('connectDB.php');
//get all posted values
$username = $_POST['username'];
$userpass = $_POST['password'];
$usermail = $_POST['usermail'];
//and some more
//run checks here for if fields are empty etc?
//example check if username was empty
if($username == NULL) {
echo 'No username entered, try again';
mysqli_close($db);
exit();
} else {
//if username field is filled we will insert values into $db
//build query
$sql_query_string = "INSERT INTO _tablename_(username,userpassword,useremail) VALUES('$username','$userpass','$usermail')";
if(mysqli_query($db,$sql_query_string)) {
echo 'Record was entered into DB successfully';
mysqli_close($db);`enter code here`
} else {
echo 'Ooops - something went wrong.';
mysqli_close($db);
}
}
?>

Unable to insert data into database with php

I have a problem posting data in my database with a form. Very basic stuff I'm sure but Im quite stuck :/
I am able to get stuff out of my database using the select from database routine. So I know that the connection with the databse is probably not the problem.
This is my 'upload.php':
<html>
<head>
<title>Upload</title>
</head>
<body>
<form action="action.php" method="post">
<fieldset class="first">
Name:
<input type="text" name="author" />
Heading:
<input type="text" name="heading" />
Text:
<textarea type="text" name="thecontent"> </textarea>
</fieldset>
<fieldset>
<input type="submit"/>
</fieldset>
</form>
</body>
</html>
And this is my 'action.php':
<html>
<head>
<title>Send!</title>
</head>
<body>
<?php
ini_set('display_errors', 1); error_reporting(E_ALL);
$link = mysql_connect('localhost','name','pasword')
or die ("Unable to connect");
$mydb = mysql_select_db('the_database',$link)
or die ("No database found");
$author = $_POST['author'];
$heading = $_POST['heading'];
$thecontent = $_POST['thecontent'];
$mysql_query="INSERT INTO articles ('heading', 'author', 'content')
VALUES ('$heading','$author','$thecontent')" or die(mysql_error());
echo "This was send: $author $heading $thecontent <br> ";
mysql_close()
?>
</body>
</html>
All help would be much appreciated!!
Cheers,
Ziggy
Thanks for all the help guys! I'm trying to use mysqli to insert the data however it's not yet working this is my new code in action.php:
<html>
<head>
<title>Send!</title>
</head>
<body>
<?php
ini_set('display_errors', 1); error_reporting(E_ALL);
$DB_HOST = 'localhost';
$DB_USER = '**';
$DB_PASS = '***';
$DB_NAME = '***';
# $db = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if (mysqli_connect_errno()) {
echo 'Error.';
exit();
}
$author = $_POST['author'];
$heading = $_POST['heading'];
$thecontent = $_POST['thecontent'];
$query = 'INSERT INTO articles ('heading', 'author', 'content')
VALUES ('$heading','$author','$thecontent')';
$result = $db->query($query);
if ($result) {
echo $db->affected_rows."This was added.";
}
else {
echo "somethings gone very wrong.";
}
$db->close();
?>
</body>
</html>
What am I doing wrong guys?
Help is much appreciated!
Cheers,
Ziggy
You build the INSERT string, but you never call a method to realy INSERT the DB with it.
Moreover, old mysql_* methods are deprecated, use PDO or mysqli API instead, see http://www.php.net/manual/en/mysqlinfo.api.choosing.php
See also stackoverflow post about this : mysqli or PDO - what are the pros and cons?
Some PDO prepared statements examples with PDO : http://www.php.net/manual/en/pdo.prepare.php
$mysql_query="INSERT INTO articles ('heading', 'author', 'content')
 VALUES ('$heading','$author','$thecontent')";
mysql_query($mysql_query);
//required to run the query..
And mysql_close(); // missing :p

Categories