-1 Record Inserted error - php

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')

Related

Text not updating onto sql database

I'm currently trying to create a comment section on my website. The code is almost done but I have run into an issue. When submiting the text, it is not going to my database. Here is the code to take the text and send it to MySQL database.
<?php
include 'dbh.inc.php';
function setComments($conn) {
if(isset($_POST['commentSubmit'])){
$uid = $_POST['uid'];
$date = $_POST['date'];
$message = $_POST['message'];
$sql = "INSERT INTO comments (uid, date, message) VALUES ('$uid,
$date,
$message')";
$result = $conn->query($sql);
}
}
If you could provide me with an answer that would be great.
You have wrong quotation marks around the values. You need to quote around each individual variable in the $sql string.
<?php
include 'dbh.inc.php';
function setComments($conn) {
if(isset($_POST['commentSubmit'])){
$uid = $_POST['uid'];
$date = $_POST['date'];
$message = $_POST['message'];
$sql = "INSERT INTO comments (uid, date, message) VALUES ('$uid',
'$date',
'$message')";
$result = $conn->query($sql);
}
}
NOTE: Use parametrized queries. Read this post about sql injection.

MYSQL insert into multiple tables doesn't work

I have three files reg_form.php, dbconnection.php and insert.php.
When submitting the form the data is not inserted into the database. I can't figure out why. Initially I didn't know how to use insert into multiple tables but took the advice of many posts from here. Unfortunately I have still failed to make it work and it is driving me insane. Here is the sql code so far for the insert.
<?php
include ("dbconnection.php");
if(file_exists("dbconnection.php")) {
echo"Connected to database successfully";
} else if(!file_exists("dbconnection.php")){
echo "Connection failed";
}
$forename = "forename";
$surname = "surname";
$address_line1 = "address_line1";
$address_line2 = "address_line2";
$address_line3 = "address_line3";
$city = "city";
$postcode = "postcode";
$phone = "phone";
$email = "email";
$username = "username";
$password = "password";
$cpassword = "cpassword ";
$query = "INSERT INTO users (username,
password)VALUES('$username','$password');";
$query2 = "INSERT INTO users_details (forename, surname,address_line1,
address_line2, address_line3, city, postcode, phone, email)
VALUES('$forename','$surname','$address_line1','$address_line2',
'$address_line3','$city','$postcode','$phone','$email')";
query ($dbconnection,$sql);
?>
Ok problem is solved. I made a stored procedure because I am doing an INSERT INTO multiple tables and then called it like this.
$sql ="CALL add_user('".$username."', '".$password."', 'user',
'".$forename."','".$surname."', '".$address_line1."' ,
'".$address_line2."', '".$address_line3."', '".$city."', '".$postcode."',
'".$phone."', '".$email."','".is_bool($email_contact)."',
'".is_bool($phone_contact)."')";
$query = $con->prepare($sql);
$query->execute();

`mysql_real_escape_string()` returns empty MySql Fields

I have a HTML contact form in which the user is allowed to write whatever he wants in the message input field. This form is being posted using AJAX and being processed in the below PHP.
My problem is that i get an empty row in the MySql Table.
I am simply wondering why $message = $_POST['message']; returns the proper value, when $message = mysql_real_escape_string($_POST['message']); returns empty string!!
What am I missing here??
//posted data
$firstName = mysql_real_escape_string($_POST['firstName']);
$lastName = mysql_real_escape_string($_POST['lastName']);
$name = $firstName. ' ' .$lastName ;
$email = mysql_real_escape_string($_POST['email']);
$phone = mysql_real_escape_string($_POST['phone']);
$subject = mysql_real_escape_string($_POST['subject']);
$hear = mysql_real_escape_string($_POST['hear']);
$message = mysql_real_escape_string($_POST['message']);
$db_server = mysql_connect($db_hostname, $db_username, $db_password)
// Check if is Duplicates
$query_usercheck = " select * from `test` where Name='$name' and Email='$email' and Phone='$phone' and Subject='$subject' and Message='$message' "; //matching all fields
$usercheck = mysql_query($query_usercheck) or die(mysql_error());
$row_usercheck = mysql_fetch_assoc($usercheck);
$totalRows_usercheck = mysql_num_rows($usercheck);
if ( $totalRows_usercheck > 0 ) {
$duplicate = 'Yes';
} else {
$duplicate = 'No';
//adding application data to MySql database
$add = mysql_query("INSERT INTO `test` (`Date`, `Day`, `Time`, `Name`, `Email`, `Phone`, `Subject`, `From`, `Message`)
VALUES ('$date','$day','$time','$name','$email','$phone','$subject','$hear','$message')");
}
// close mysql
mysql_close();
The problem is that you connect to the database after you do mysql_real_escape_string. Please move your connecting to the database before escaping your variables.
Even better, get rid of the deprecated mysql_* functions (there are even gone in PHP7)! Use mysqli or even better: use PDO with prepared statements as even mysql_real_escape_string is not safe.
mysql_real_escape_string requires an active database connection to do its job. You have not established a connection at the point of calling it.

Error Querying database when insert PHP code is executed

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."'";

I can't insert data in my db cause of an empty primarykey

I'm new to PHP, MySQL and working on an project for my school. I need to make a form that inserts new students into a database.
I need to have an primary key named studentnummer so I can use this later on, but this needs to be created in the database table not in the form. When I try to insert the data of the form in the table I'll get an error saying I need to insert data in table row 1 (this is the primary key which is AI and an INT)
I've got the following for PHP and MySQL:
require ("connection.php");
//gets the data from the form
$voornaam = $_REQUEST['voornaam'];
$tussenvoegsel = $_REQUEST['tussenvoegsel'];
$achternaam = $_REQUEST['achternaam'];
$geboortedatum = $_REQUEST['geboortedatum'];
$woonplaats = $_REQUEST['woonplaats'];
$straat = $_REQUEST['straat'];
$huisnummer = $_REQUEST['huisnummer'];
$postcode = $_REQUEST['postcode'];
$telefoonnummer = $_REQUEST['telefoonnummer'];
$mobielnummer = $_REQUEST['mobielnummer'];
$email = $_REQUEST['email'];
$voor = $_REQUEST['voor'];
$motivatie = $_REQUEST['motivatie'];
$alt = $_REQUEST['alt'];
$tbl_name ="studenten";//db table name
$sql_ins = mysql_query("INSERT INTO $tbl_name values('??studentnummer??','$voornaam', '$tussenvoegsel', '$achternaam', '$geboortedatum', '$woonplaats', '$straat', '$huisnummer', ' $postcode' , '$telefoonnummer', '$mobielnummer', '$email', '$voor', '$motivatie', '$alt')");
This is a printscreen from my table stucture. If anyone knows what I can do about this problem I would appreciate it very much!!!
Thanks.
If you insert a NULL into an auto_increment primary key field, mysql will supply the value for you, so
INSERT INTO $tbl_name VALUES(NULL, blah blah blah)
and then you can retrieve the generated value with
$studentnummer = mysql_insert_id();
Note that you shouldn't be using the mysql_*() functions. They're deprecrated. Consider switching to mysqli or PDO
Please try this-
$sql_ins = mysql_query("INSERT INTO $tbl_name values('','$voornaam', '$tussenvoegsel', '$achternaam', '$geboortedatum', '$woonplaats', '$straat', '$huisnummer', ' $postcode' , '$telefoonnummer', '$mobielnummer', '$email', '$voor', '$motivatie', '$alt')");

Categories