Error Querying database when insert PHP code is executed - php

I've been tinkering with my PHP code to insert data into a SQL table and I always get ERROR QUERYING DATABASE. The values are coming from a normal HTML form and and then when I hit submit (action=memberadd.php) I get the error message from the code below. I'm missing something but can't see what it is????
<?php
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$city = $_POST['city'];
$state = $_POST['state'];
$country = $_POST['country'];
$industry = $_POST['industry'];//only showing one - need to fix
$profile_visibility = $_POST['profile_visibility'];
$position = $_POST['position'];
$status = $_POST['status'];
$profile_link = $_POST['profile_link'];
$skills = $_POST['skills'];
//connects and sends information to the database
$dbc = mysqli_connect('localhost', 'root', 'root', 'main') or die('Error connecting to MySQL server.');
//inserts data into the member_details table main db
$query = "INSERT INTO 'member_details' (first_name, last_name, city, state, country, industry, profile_visibility, position, status, profile_link, skills)
VALUES ('$first_name', '$last_name', '$city', '$state', '$country', '$industry', '$profile_visibility', '$position', '$status', '$profile_link', '$skills')";
$result = mysqli_query($dbc, $query) or die('Error querying database.');
mysqli_close($dbc);
echo '<h2>Here are your details.</h2>';
echo '<h3>First Name: '.$first_name.'<br />';
echo '<h3>Last Name: '.$last_name.'<br />';
echo 'City: '.$city.'<br />';
echo 'State: '.$state.'<br />';
echo 'Country: '.$country.'<br />';
echo 'Industry: '.$industry.'<br />';//only showing one - need to fix
echo 'Profile: '.$profile_visibility.'<br />';
echo 'Position: '.$position.'<br />';
echo 'Status: '.$status.'<br />';
echo 'Link: '.$profile_link.'<br />';
echo 'Skills: '.$skills.'<br /></h3>';
?>

The Problem
As #Fred -ii- has noted the problem is with the quotes being around the table name in your INSERT statement.
$query = "INSERT INTO 'member_details' (first_name, ...
^ ^
The solution
If you wish to 'quote' table or column names, you should use backticks which you can read more about on the MySQL documentation page.
$query = "INSERT INTO `member_details` (first_name, ...
Detecting errors
To check a MySQLi database request for errors there are a few methods that can be used to get error information. Probably the most useful is mysqli_error() which will give you an error string.
$result = mysqli_query($dbc, $query);
if(!$result)
{
printf("Errormessage: %s\n", mysqli_error($dbc));
}
As #Fred -ii- also mentioned you should use error reporting correctly when developing new code. Ideally you should configure this in your php.ini, but it can also easily be done by adding the following to the top of your page(s).
error_reporting(E_ALL);
ini_set('display_errors', 1);
Finally, you're wide open to SQL Injection Attacks. You should look into using prepared statements with MySQLi to help prevent this.

You can use mysql query like...
$query = "INSERT INTO `member_details` SET first_name = '".$first_name."', last_name = '".$last_name."', city = '".$city."', state = '".$state."', country = '".$country."', industry = '".$industry."', profile_visibility = '".$profile_visibility."', position = '".$position."', status = '".$status."', profile_link = '".$profile_link."', skills = '".$skills."'";

Related

MySQL - PHP form to insert values into table?

I would like to add comments to a database using a simple form. For whatever reason, I can't seem to get the table to update when I use said form. I'm not getting any errors, it's just that nothing happens when I refresh the table afterwards. In other words, even after submitting the form, the table still has 0 entries. Here is my code:
<?php
session_start();
$connection = mysql_connect("server", "username", "password");
if ($connection->connect_error) {
die('Connect Error: ' . $connection->connect_error);
}
// Selecting Database
mysql_select_db("database", $connection) or die(mysql_error());
$name = $_POST['name'];
$title = $_POST['title'];
$comments = $_POST['comments'];
$sql = "INSERT INTO comments (Name, Title, Comments)
VALUES ('$name', '$title', '$comments')";
mysql_close($connection); // Closing Connection
?>
Thank you for your help!
You don't ever actually execute your query:
$sql = "INSERT INTO comments (Name, Title, Comments)
VALUES ('$name', '$title', '$comments')";
$result = mysql_query($sql);
Other things:
if ($connection->connect_error) { is not valid. You can't use the old mysql API in an OOP fashion. You need to use mysqli for that.
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
You are also wide open to SQL injections
You do no error checking. How do you expect to know if there are problems if you don't look for them?
(note: please change server, username, and password for your server information)
<?php
session_start();
$connection = mysql_connect("server","username","password");
if (!$connection) {
die('Connect Error: ' . mysql_error());
}
// Selecting Database
mysql_select_db("database",$connection) or die(mysql_error());
$name = $_POST['name'];
$title = $_POST['title'];
$comments = $_POST['comments'];
$sql = "INSERT INTO comments (Name,Title,Comments)
VALUES ('$name', '$title', '$comments')";
mysql_query($sql);
mysql_close($connection); // Closing Connection
?>
For security (defense against SQL injection) you can using mysql_real_escape_string function for limit input fields. For example:
$name = mysql_real_escape_string($_POST['name']);
$title = mysql_real_escape_string($_POST['title']);
$comments = mysql_real_escape_string($_POST['comments']);

Flash as3 to PHP file not inserting data into mysql

I cannot find any syntax errors for the life of me so I don't understand why the data is not being inserted into my database. When I run the script in my browser with text instead of variables and no if statement I get a successful connection but It doesn't insert the data into mysql. Its driving me nuts! Thanks in advance.
PHP:
<?php
// Establish secure connection
$link = mysql_connect('myserver', 'myuser', 'mypass');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_select_db(events_60);
if ($_POST['requester'] == "NewSale") {
$FirstName = $_POST['First_Name'];
$LastName = $_POST['Last_Name'];
$Birthday = $_POST['UserBirthday'];
$PhoneNumber = $_POST['PhoneNo'];
$Email = $_POST['UserEmail'];
mysql_query($link, "INSERT INTO events_60 (LastName, FirstName, Birthday, Phone, email)
VALUES('$LastName', '$FirstName',' $Birthday', '$PhoneNumber', '$Email')")
or die ("SYSTEM FAILURE");
echo 'System Updated';
} // close first if for post
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// close mysql connection
mysql_close();
?>
Assuming all data is posting correctly to the webpage I think the error resides here:
mysql_select_db(events_60);
It should be:
mysql_select_db('events_60', $link);
http://www.php.net/manual/en/function.mysql-select-db.php
First of all select_db query should be
mysql_select_db('events_60',$link);
Then second problem is in mysql_query. It should be like this:
mysql_query("INSERT INTO events_60 (LastName, FirstName, Birthday, Phone, email)
VALUES('$LastName', '$FirstName',' $Birthday', '$PhoneNumber', '$Email')",$link)
or die ("SYSTEM FAILURE");
$link identifier should come after query.
Hope that fixes it. :)

Check if the value exist in another table and then insert

I'm working on a form in PHP that inserts data to MySQL, but before the data is inserted there is a field that must be checked in another table before inserting. If this value exist in the other table, then the data is inserted in the main table, if not, then data is not inserted.
Here is my code to insert the data:
$host = "localhost";
$username = "root";
$password = "";
$db_name = "forms";
$tbl_name = "table1";
mysql_connect("$host", "$username", "$password") or die("cannot connect");
mysql_select_db("$db_name") or die("cannot select DB");
$nombre = $_POST['nombre'];
$apellido = $_POST['apellido'];
$cedula = $_POST['cedula'];
$email = $_POST['email'];
$telefono = $_POST['telefono'];
$establecimiento = $_POST['establecimiento'];
$codigo = $_POST['codigo'];
$sql = " INSERT INTO $tbl_name(Nombre, Apellido, Cedula, Email, Telefono, Establecimiento, Codigo)VALUES('$nombre', '$apellido', '$cedula', '$email', '$telefono', '$establecimiento', '$codigo')";
$result = mysql_query($sql);
if ($result) {
echo "Your data was sent";
} else {
echo "You inserted a wrong code";
}
?>
<?php
// close connection
mysql_close();
?>
So, what I need is to check the value $codigo in table2, if exists, then insert $codigo in table1 with the other values. This is where I'm stuck.
All you really need to do is this.
// Check if Codigo already exists in table2
$codigo = mysql_real_escape_string($_POST['codigo']);
$result = mysql_query("SELECT Codigo FROM table2 WHERE Codigo = '$codigo'");
if (!mysql_num_rows($result)) {
// Go ahead and insert everything in table1
$data = array(
'Nombre' => $_POST['Nombre'],
'Apellido' => $_POST['apellido'],
'Cedula' => $_POST['cedula'],
'Email' => $_POST['email'],
'Telefono' => $_POST['telefono'],
'Establecimiento' => $_POST['establecimiento'],
'Codigo' => $_POST['codigo']
);
// Make sure all the data is safe for entry into the database
foreach ($data as $key => $val) {
$data[$key] = "'" . mysql_real_escape_string($val) . "'";
}
$fields = implode(', ', array_keys($data));
$values = implode(', ', array_values($data));
$result = mysql_query("INSERT INTO table1 ($fields) VALUES ($values)");
echo 'Your data was sent';
} else {
echo 'Codigo already exists in table2';
}
But please note there are many ways of doing this that are far better and more efficient. For one, I would recommend you use PHP's mysqli functions rather than the deprecated mysql ones (http://www.php.net/manual/en/book.mysqli.php)
More importantly, you don't look like you're protecting your queries against SQL injection at all. Please read up on this, but it's usually just a need for real_escape_string() on any value you are inserting into a SQL query.
Simply do a SELECT query on the other table with the data you are checking for and then if mysql_num_rows() > 0 you do an insert. Something like below
$query = "SELECT * FROM otherTable WHERE infoIsSame";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result) > 0) {
$sql=" INSERT INTO $tbl_name(Nombre, Apellido, Cedula, Email, Telefono, Establecimiento, Codigo)VALUES('$nombre', '$apellido', '$cedula', '$email', '$telefono', '$establecimiento', '$codigo')";
$result=mysql_query($sql);
if($result){
echo "Your data was sent";
}else {
echo "You inserted a wrong code";
}
}else{
echo "Not present in Other database";
}
One approach is to let the INSERT statement do the check for you:
INSERT INTO $tbl_name (Nombre, Apellido, Cedula, Email, Telefono, Establecimiento, Codigo)
SELECT '$nombre', '$apellido', '$cedula', '$email', '$telefono', '$establecimiento', '$codigo'
FROM table2
WHERE table2.Codigo = '$codigo'
LIMIT 1
Then check the number of rows inserted mysql_affected_rows() to determine whether a row was inserted or not. This fewer round trips to the database, for the "normative" case where you expect a row to be inserted.
NOTE: avoid using mysql_ functions and use mysqli_ or PDO instead.

-1 Record Inserted error

My code is showing -1 Record Inserted error and not inserting the fields to database. Any thoughts of why is it doing this?
<?php
include("dbconnect.php");
$con=new dbconnect();
$con->connect();
error_reporting(E_ALL);
if($_POST) {
$users_name = $_POST['name'];
$users_email = $_POST['email'];
$users_website = $_POST['website'];
$users_comment = $_POST['content'];
$users_name = htmlspecialchars($users_name);
$users_email = htmlspecialchars($users_email);
$users_website = htmlspecialchars($users_website);
$users_comment = htmlspecialchars($users_comment);
$postid = $_GET['id'];
$sSql = "INSERT INTO comments
( post_id, name, email, website,content)
VALUES ($postid, '$users_name',
'$users_email', '$users_website', '$users_comment' )";
mysql_query($sSql);
$update=mysql_affected_rows();
echo "<h2>$update Record Inserted</h2><br />";
echo '<h2> Your Comment is submitted</h2><br />';
}
?>
For some reason, the comments table is not getting updated. I am new to programming in mySQL and PHP. Any suggestions would be of so much help to me. Thanks.
First insert dummy values in your php SQL statement & comment mysql_query statement.
$sSql = "INSERT INTO comments (post_id,name,email,website,content) VALUES (100, 'anoop.pete','anoop.pete#gmail.com', 'www.anooppete.com', 'Nice Website' )";
//mysql_query($sSql);
//$update=mysql_affected_rows();
Print the SQL statement...
print($sSql);
Copy the SQL statement from web browser, Execute the $sSql in MySql
If the row is inserted, in MySQL, uncomment and run the same page again.
mysql_query($sSql);
$update=mysql_affected_rows();
If it runs, try removing htmlspecialchars()
$users_name = $_POST['name'];
$users_email = $_POST['email'];
$users_website = $_POST['website'];
$users_comment = $_POST['content'];
I guess your htmlspecialchars() is returning some invalid characters...
-1 means the query returned an error.
Put this sql query into your sql browser's sql 'querier' and see what the error is:
INSERT INTO
comments
(post_id,
name,
email,
website,
content)
VALUES
(2,
'name',
'email#',
'http://',
'comment')

php form script

I'm very new to PHP and am having some trouble. I have a form using HTML which is action=.php method=post
The form is using text boxes and select options, I'm not sure if it makes a difference in sqldatabase. I've tried about 30 different combinations of this script and can only get a connect successfully message but nothing is posted.
<?php
$link = mysql_connect('everybodyslistcom.ipagemysql.com', 'accounts', 'accounts');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_select_db("user");
$FName = $_POST["FName"];
$LName = $_POST["Lname"];
$Phone = $_POST["Phone"];
$EmailAddress = $_POST["EmailAddress"];
$Month = $_POST["Month"];
$Day = $_POST["Day"];
$Year = $_POST["Year"];
$Username = $_POST["Username"];
$Password = $_POST["Password"];
$sql = 'INSERT INTO Members (ID, FName, LName, Phone, EmailAddress, Month, Day, Year, Username, Password) VALUES'
. '(\'\', \'$FName\', \'$LName\', \'$Phone\', \'$EmailAddress\', \'$Month\', \'$Day\', \'$Year\', \'$Username\', \'$Password\')';
mysql_close();
php?>
try to execute your query
mysql_query($sql);
EDIT: I see you are doing this:
$sql = 'SELECT bla bal $variable';
PHP will not parse the variable. The right way:
$sql = "SELECT bla bla $variable"; // valid
$sql = "SELECT bla bla {$variable}"; // also valid
$sql = 'SELECT bla bla '.$variable; // also valid
your closing php tag is not correct, it should be
?>
rather than
php?>
Also u r not executing your query using:
mysql_query('your query here');
this might cause the problem.
Your variables are not interpreted by PHP. If you want variable to be parsed in string, it should be wrapped in double-quote (")
It may fail if any of your posted data contains some quote character, so you must apply mysql_real_escape_string to all of them.
I hope that database connection credentials are not real you posted here? :D
You said that your form contains "action=.php" literally, you have to turn it into :
<form name="form_name" method="post" action="your_script.php">
You need to execute the query too:
mysql_query($sql, $link);
you should also check whether POST was really sent:
if (!empty($_POST)) {
// ... your code here
}
next thing: you don't need closing tag ?> if your *.php file consist only PHP code - end of file is also correct end of PHP block of code - it's "good-to-have" habit, because in some cases it helps you to avoid error: "Cannot add/modify header information - headers already sent by..."
next problem - wrong way of inserting variables into string:
$sql = 'INSERT INTO Members (ID, FName, LName, Phone, EmailAddress, Month, Day, Year, Username, Password) VALUES'
. '(\'\', \'$FName\', \'$LName\', \'$Phone\', \'$EmailAddress\', \'$Month\', \'$Day\', \'$Year\', \'$Username\', \'$Password\')';
correct way:
$sql = "INSERT INTO Members (ID, FName, LName, Phone, EmailAddress, Month, Day, Year, Username, Password) VALUES (null, '$FName', '$LName', '$Phone', '$EmailAddress', '$Month', '$Day', '$Year', '$Username', '$Password')";
more info here
next - as Deniss said, instead of:
$FName = $_POST["FName"];
should be:
$FName = mysql_real_escape_string($_POST["FName"]);
actually you should fist check weather magic quotes gpc are on or off:
if (get_magic_quotes_gpc()) {
if (!empty($_POST)) {
array_walk_recursive($_POST, 'stripslashes_value');
}
}
function stripslashes_value(&$value) {
$value = stripslashes($value);
}
without this you could have problem with double \\ inserted into db (it depends on your server configuration)
and last but not least: as Robert said you miss one more important thing:
mysql_query($sql);
I think your error because your have not call mysql_query function
can try my code edit
<?php
$link = mysql_connect('everybodyslistcom.ipagemysql.com', 'accounts', 'accounts');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_select_db("user",$link);
$FName = $_POST["FName"];
$LName = $_POST["Lname"];
$Phone = $_POST["Phone"];
$EmailAddress = $_POST["EmailAddress"];
$Month = $_POST["Month"];
$Day = $_POST["Day"];
$Year = $_POST["Year"];
$Username = $_POST["Username"];
$Password = $_POST["Password"];
$sql = "INSERT INTO Members SET FName='{$FName}', LName='{$LName}', Phone='{$Phone}', EmailAddress='{$EmailAddress}', Month='{$Month}', Day='{$Day}', Year='{$Year}', Username='{$Username}', Password='{$Password}'";
// Call Function mysql_query insert new record in mysql table
mysql_query($sql,$link);
mysql_close($link);
?>
Comment for me if your have problem :) or notes of apache services
good day

Categories