session error-value fail to insert into DB - php

i have a php code that insert session value into database,but i get this error when trying to insert Error: INSERT INTO tbale name (amount,bankname) VALUES ( 20000.00,gtbank)
Unknown column 'gtbank' in 'field list'.the session has the value GTBANK
below is my code that insert session value to database
<?php
session_start(); {
//Include database connection details
include('../../dbconnect.php');
if($_SESSION["bn"]) {
}
$amount = strip_tags($_POST['cat']);
$field1amount = $_POST['cat'];
$field2amount = $field1amount + ($field1amount*0.5);
$sql = "INSERT INTO provide_help (amount,bankname) VALUES ( $field1amount,".$_SESSION['bn'].")";
if (mysqli_query($conn, $sql))
$sql = "INSERT INTO gh (ph_id, amount) VALUES (LAST_INSERT_ID(), $field2amount)";
if (mysqli_query($conn, $sql))
{
$_SESSION['ph'] ="<center><div class='alert alert-success' role='alert'>Request Accepted.</div></center>";
header("location: PH.php");
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
}
?>
anyone who can help please?.thanks

bankname field is type of varchar I think. So you need to pass string with quotes ''. See below your code should be like this.
$sql = "INSERT INTO provide_help (amount,bankname)
VALUES ( $field1amount,'".$_SESSION['bn']."')";

When inserting string (bankName) in data base it should be covered with quote.
Use this:
$sql = "INSERT INTO provide_help (amount,bankname) VALUES ( $field1amount,'".$_SESSION['bn']."')";
// ^ ^ --- Single quote added
I will suggest you to use bind_params like following:
$stmt = $conn->prepare("INSERT INTO provide_help (amount,bankname) VALUES (?, ?)");
$stmt->bind_param("ds", $field1amount, $_SESSION['bn']);
if ($stmt->execute()){
// handle success
} else {
// handle error
}
The argument may be one of four types while binding:
i - integer
d - double
s - string
b - BLOB

Related

Unable to insert data into MySQL database using PHP

I am unable to insert data into MySQL database. I do not know the reason since no error is triggered. I am using XAMPP on windows to run local server. Here is the code. It would be great if someone could help.
I am always getting "Values not inserted" output. I also tried printing the $query when I got exact values I entered through a form in the VALUES ('$email', ...) part of the SQL query.
<?php
$dbconnect = mysqli_connect("localhost","root","","id3626001_login_details");
if (!$dbconnect)
{
die("Connection Failed" .mysqli_connect_error());
}
if (!mysqli_select_db($dbconnect, "id3626001_login_details"))
{
echo "Could not connect to Database";
}
if (isset($_REQUEST['username']) && ($_SERVER["REQUEST_METHOD"] == "POST")){
$username = $_REQUEST['username'];
$email = $_REQUEST['email'];
$password = $_REQUEST['password'];
// Inserting values into the database through a query
$query = "INSERT INTO user_registration (ID, email, username, password) VALUES ('$email', $username', '".md5($password)."')";
if (!mysqli_query($dbconnect, $query))
{
echo "Values not inserted";
}
$result = mysqli_query($dbconnect, $query);
if($result){
echo "Registration Successful";
}
}
?>
there is a problem in your query,
1) your column counts and count of values you are passing are not the same (must be same
2) you forgot to put ' (quote befor $username')
change your query to
// Inserting values into the database through a query
$query = "INSERT INTO user_registration ( email, username, password) VALUES ('$email', '$username', '".md5($password)."')";
When you are testing you should not only print only query, you should also copy that query and run it directly into database through [(localhost/phpmyadmin)> select your databse > SQL ] and see what error are displaying there when firing a query.
UPDATE
for #Akintunde 's suggestion
for security concerns you should not be using these kind of insertion methods which is fully open to SQL injections you must follow some rule to avoid to get your script being target of sql injection
use Prepared Statements instead for database operations
Here in your query you forgot to put upper quote '-> $username',
$query = "INSERT INTO user_registration (email, username, password) VALUES ('$email', '$username', '".md5($password)."')";
Here we are not passing Id as a param so you need to make id auto increment in database for that table.
and why are to passing your query twice into mysqli_query() you can check for once like,
$result = mysqli_query($dbconnect, $query);
if ($result)
{
echo "Registration Successful";
}
else{
echo "Values not inserted";
}

PHP/mySQL: INSERT INTO is not posting the correct values

I try to insert some values from a form into my database with this code:
<?php
$link = mysqli_connect("myHost", "myUsername", "myPW", "myDB");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$name1 = mysqli_real_escape_string($link, $_REQUEST['plannercolumn1']);
$name2 = mysqli_real_escape_string($link, $_REQUEST['plannercolumn2']);
$name3 = mysqli_real_escape_string($link, $_REQUEST['plannercolumn3']);
$name4 = mysqli_real_escape_string($link, $_REQUEST['plannercolumn4']);
$name5 = mysqli_real_escape_string($link, $_REQUEST['plannercolumn5']);
$name6 = mysqli_real_escape_string($link, $_REQUEST['plannercolumn6']);
// attempt insert query execution
$sql = "INSERT INTO anmeldungen (FR_PM) VALUES ('$name1')";
$sql = "INSERT INTO anmeldungen (SA_AM) VALUES ('$name2')";
$sql = "INSERT INTO anmeldungen (SA_PM) VALUES ('$name3')";
$sql = "INSERT INTO anmeldungen (SO_AM) VALUES ('$name4')";
$sql = "INSERT INTO anmeldungen (SO_PM) VALUES ('$name5')";
$sql = "INSERT INTO anmeldungen (MO_AM) VALUES ('$name6')";
if(mysqli_query($link, $sql)){
echo "Name ", $name1, " erfolgreich eingetragen. Wir freuen uns auf dich!";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
When I submit the form, it's creating a new row, but it's not inserting any values in all of the columns, but the column MO_AM. Is there a fault in my PHP?
Your query should look like:
$sql = "INSERT INTO anmeldungen
(FR_PM,SA_AM,SA_PM,SO_AM,SO_PM,MO_AM)
VALUES ('$name1','$name2','$name3','$name3','$name4','$name5','$name6')";
Are you sure that the $name variables have values?
Your SQL Query should be:
$sql = "INSERT INTO `anmeldungen`(`FR_PM`,`SA_AM`,`SA_PM`,`SO_AM`,`SO_PM`,`MO_AM`)
VALUES ('$name1','$name2','$name3','$name4','$name5','$name6')";
Though you shouldn't be using $variable as the insert you should look to binding these to prevent SQL Injections.
What you did just overwrite the query.You can insert multiple values into the same table.
Change your query:-
EDIT:
If you use multiple lines for the query it should look like this.
Also When you append the variable.
$sql = 'INSERT INTO anmeldungen (FR_PM,SA_AM,SA_PM,...)'
.' VALUES ('.$name1.','.$name2.','. .... .)'
;

How to store data in mysql with php using GET method?

I am trying to store the data from php to mysql using GET method ,
<?php
$user = "root";
$password = "";
$host = "localhost";
$connection = mysql_connect($host,$user,$password);
$select = mysql_select_db('dam',$connection);
if($connection)
{
echo "connection succesfull";
}
else {
echo "Error";
}
?>
this is the Database connection code connection.php and also it shows connectionsucccesfull in localhos (browser) and i am trying to add some data to database using GET method
<?php
include("connect.php");
$sensor1 = $_GET['sensor1'];
$sensor2 = $_GET['sensor2'];
$sensor3 = $_GET['sensor3'];
$sql_insert = "insert into tablearduino (sensor1,sensor2,sensor3) values ('$sensor1,$sensor2,$sensor3')";
mysql_query($sql_insert);
if($sql_insert)
{
echo "Saving succeed";
}
else{
echo "Error occured";
}
?>
when i type the url like this
http://localhost/EPPF/index.php?sensor1=5.0&sensor2=3.0&sensor3=4.0
data is not storing in mysql database
What is the problem and how can i fix it ?
Change your query to
$sql_insert = "insert into tablearduino (sensor1,sensor2,sensor3) values ('$sensor1','$sensor2','$sensor3')";
change your query from
$sql_insert = "insert into tablearduino (sensor1,sensor2,sensor3) values ('$sensor1,$sensor2,$sensor3')";
to
$sql_insert = "insert into tablearduino (sensor1,sensor2,sensor3) values ('".$sensor1."','".$sensor2."','".$sensor3."')";
I don't know about the datatype you have assigned to these fields, so i assuming it to varchar
Change your query
FROM
$sql_insert = "insert into tablearduino (sensor1,sensor2,sensor3) values ('$sensor1,$sensor2,$sensor3')";
To
$sql_insert = "insert into tablearduino (sensor1,sensor2,sensor3) values ('$sensor1','$sensor2','$sensor3')";
Use single quotes with varibale name because its is string.
If it is flot or integer column in your database table then you can use it directly (without single quotes)
$sql_insert = "insert into tablearduino (sensor1,sensor2,sensor3) values ($sensor1,$sensor2,$sensor3)";
There is an error is your query
The query is below
insert into tablearduino (sensor1,sensor2,sensor3) values ('".$sensor1."','".$sensor2."','".$sensor3."')"
you are writing wrong the query
your query is
$sql_insert = "insert into tablearduino (sensor1,sensor2,sensor3) values ('$sensor1,$sensor2,$sensor3')";
where it should be
$sql_insert = "insert into tablearduino (sensor1,sensor2,sensor3) values ('{$sensor1}','{$sensor2}','{$sensor3}')";
mind the quotes locations

How do I concatenate single quotes in php?

I'm trying to create a simple sql statement in my php file, to insert two values into the database. Its throwing the error I implemented for non valid sql statements, and I believe its because the VALUES( ) part is wrong. How do I concatenate the single quotes for the sql statement? The database values should be varchars.
$sql = "INSERT INTO visitor_log_marcusw1(email_user, email_provider) "
. "VALUES ('".$email_user."' , '".$email_provider."')";
mysqli_query($con, $sql);
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
if (mysqli_query($conn, $sql)) {
Replace this with
if (mysqli_query($con, $sql)) {
$con not $conn
Try this:
$sql = "INSERT INTO visitor_log_marcusw1 (email_user, email_provider) VALUES ('{$email_user}' , '{$email_provider}')";
Also, there seems to be a typo with in the connection name ($conn vs $con).
Use mysql function mysql_real_escape_string($php_variable)
$sql = "INSERT INTO visitor_log_marcusw1(email_user, email_provider) \n"
. "VALUES (mysql_real_escape_string($email_user) , mysql_real_escape_string($email_provider)";

PHP, Error 1136 : Column count doesn't match value count at row 1 [duplicate]

This question already has answers here:
PHP, MySQL error: Column count doesn't match value count at row 1
(3 answers)
Closed 9 years ago.
I get this Exception:
Error 1136 : Column count doesn't match value count at row 1
Structure of the table :
create table gb_entries (
id int(4) not null auto_increment,
username varchar(40) not null,
name varchar(40),
gender varchar(40),
dob int(40),
email varchar(40),
primary key (id)
);
With this PHP code:
// Add a new entry to the database
function addEntry($username, $name, $gender, $dob, $email) {
$connection = mysql_open();
$insert = "insert into gb_entries " .
"values ('$username', '$name', '$gender', '$dob', '$email')";
$result = # mysql_query ($insert, $connection)
or showerror();
mysql_close($connection)
or showerror();
}
// Return an array of database entries that contain $name anad $email
function getEntries($username,$name,$gender,$dob,$email) {
// Sanitise user input to prevent SQL injection attacks
$username = mysql_escape_string($username);
$name = mysql_escape_string($name);
$gender = mysql_escape_string($gender);
$dob = mysql_escape_string($dob);
$email = mysql_escape_string($email);
// Open connection and select database
$connection = mysql_open();
// Construct query
$query =
"select username, name, gender, dob, email from gb_entries where 0=0 ";
if (! empty($username)) {
$query .= "AND username LIKE '%$username%' ";
}
if (! empty($name)) {
$query .= "AND name LIKE '%$name%' ";
}
if (! empty($gender)) {
$query .= "AND gender LIKE '%$gender%' ";
}
if (! empty($dob)) {
$query .= "AND dob LIKE '%$dob%' ";
}
if (! empty($email)) {
$query .= "AND email LIKE '%$email%' ";
}
$query .= "ORDER BY id";
// echo $query;
// Execute query
$result = # mysql_query($query, $connection)
or showerror();
// Transform the result set to an array (for Smarty)
$entries = array();
while ($row = mysql_fetch_array($result)) {
$entries[] = $row;
}
mysql_close($connection)
or showerror();
return $entries;
}
What does the Exception mean?
As it says, the column count doesn't match the value count. You're providing five values on a six column table. Since you're not providing a value for id, as it's auto increment, it errors out - you need to specify the specific columns you're inserting into:
$insert = "insert into gb_entries (username, name, gender, dob, email) " .
"values ('$username', '$name', '$gender', '$dob', '$email')"
Also, I really hate that WHERE 0=0 line. I know why you're doing it that way, but I personally find it cleaner to do something like this (warning: air code!):
$query = "select username, name, gender, dob, email from gb_entries ";
$where = array();
if (! empty($username)) {
$where[] = "username LIKE '%$username%'"; // add each condition to an array
// repeat for other conditions
// create WHERE clause by combining where clauses,
// adding ' AND ' between conditions,
// and append this to the query if there are any conditions
if (count($where) > 0) {
$query .= "WHERE " . implode($where, " AND ");
}
This is personal preference, as the query optimizer would surely strip out the 0=0 on it's own and so it wouldn't have a performance impact, but I just like my SQL to have as few hacks as possible.
If the error is occurring when trying to insert a row to your table, try specifying the list of fields, in the insert query -- this way, the number of data in the values clause will match the number of expected columns.
Else, MySQL expects six columns : it expects the id column -- for which you didn't specify a value.
Basically, instead of this :
$insert = "insert into gb_entries " .
"values ('$username', '$name', '$gender', '$dob', '$email')";
Use something like that :
$insert = "insert into gb_entries (username, name, gender, dob, email) " .
"values ('$username', '$name', '$gender', '$dob', '$email')";
I had a similar problem. The column count was correct. the problem was that i was trying to save a String (the value had quotes around it) in an INT field. So your problem is probably coming from the single quotes you have around the '$dob'. I know, the mysql error generated doesn't make sense..
funny thing, I had the same problem again.. and found my own answer here (quite embarrassingly)
It's an UNEXPECTED Data problem (sounds like better error msg to me). I really think, that error message should be looked at again
Does modifying this line help?
$insert = "insert into gb_entries (username, name, gender, dob, email) " .
"values ('$username', '$name', '$gender', '$dob', '$email')";

Categories