php/mysql returning empty set - php

<html>
<head>
</head>
<body>
<form action = "insertform.php" method = "post">
field: <input type = "text" name = "fielda">
field2: <input type = "text" name = "fieldb">
thedata: <input type = "text" name = "qdata">
<input type = "submit" name = "submit">
</form>
<?php
if (isset($_POST['submit'])){
$con = mysql_connect("localhost","user","password");
if (!$con){
die("cannot connect" . mysql_error());
}
mysql_select_db("stQutieria",$con);
$sql = "INSERT INTO qtable(fielda, fieldb, qdata) VALUES ("$_POST[fielda]","$_POST[fieldb]","$_POST[qdata]")";
mysql_query($sql,$con);
mysql_close($con);
}
?>
</body>
</html>
Edit: OK! so I changed my code, I played around with double quotes or ' around the $_POST areas. When I used double quotes I got errors saying fielda / fieldb wernt defined, I also got errors saying "syntax error, unexpected '$_POST' (T_VARIABLE)"... the code i am working with derives from the same page ass insertform.php. Here is the video I am watching http://www.youtube.com/watch?v=j4FUCoCxE8w. if anyone could help me on Skype / msn / teamview I would greatly appreciate it.

You're missing quotes around your $_POST keys: $_POST[fielda] should be $_POST['fielda'] etc. (actually not true)
You need a space after your table name and opening parenthesis qtable(fielda should be qtable (fielda
You're missing a quote after '$_POST[fielda] (should be '$_POST[fielda]') and after '$_POST[fieldb] (should be '$_POST[fieldb]')
You have no error handling. If you call mysql_error() after your query you would know exactly what your error is.
You are wide open to SQL injections
You are using an obsolete API

That means your query is failing. Likely because you have no space between the table name and the column names:
INSERT INTO qtable (fielda, fieldb, qdata)

replace Your SQL with:
$sql = "INSERT INTO qtable (fielda, fieldb, qdata) VALUES ('".$_POST['fielda']."','".$_POST['fieldb']."','".$_POST['qdata']."')";
but this is really unsafe...
Much more safer is to use something like this:
$values = array($_POST['fielda'], $_POST['fieldb'], $_POST['qdata']);
$st = $db->prepare('INSERT INTO qtable (fielda, fieldb, qdata) VALUES (?,?,?)');
$st->execute($values);

You are making mistake in coding the correct sql statement will be like this one
$sql ="INSERT INTO qtable(fielda, fieldb, qdata) VALUES (".$_POST[fielda].",".$_POST[fieldb].",".$_POST[qdata].")";
Note this above sql statement is for those fields which are integer in database if fields are varchar then following will be code
$sql ="INSERT INTO qtable(fielda, fieldb, qdata) VALUES ('".$_POST[fielda]."','".$_POST[fieldb]."','".$_POST[qdata]."')";
Thank You

Related

SQL Near error for inserting data through HTML form

I've been trying to insert some data into my database for an events page. I have an html form and a seperate script, as seen below and the submit seems to go through for the ename id and imgsrc values but nothing past that. Anything more and I get a 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 'when, descr, positions) VALUES (test, 1 ,www.vzdc.org,2017-1-20 23:59:00' at line 1I've done some reasearch but maybe it's just a weird error on my end? I'm fairly new to mysql and I would love some help! Thanks, code below.
<!-- HTML form -->
<form id="newevent" action="insertevent.php" method="post">
<p>Event Name:</p><input name="ename" type="text" width="100">
<p>ID:</p><input name="id" type="text" size="5">
<p>Banner Link:</p><input name="imgsrc" type="text" size="50">
<p>Description</p><input name="descr" type="text" height="1000px" >
<p>Date / Time (yyyy-mm-dd HH:MM:SS):</p><input name="when" type="text">
<p>Positions (ONE per line)</p><textarea name="positions" form="newevent" rows="10" cols="50"></textarea><br>
<input value="Add Event" type="submit">
</form>
/* PHP script on insertevent.php */
<?php
$link = mysqli_connect("localhost", "root", "xxx", "xxx");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$ename = mysqli_real_escape_string($link, $_POST['ename']);
$id = mysqli_real_escape_string($link, $_POST['id']);
$imgsrc = mysqli_real_escape_string($link, $_POST['imgsrc']);
$when = mysqli_real_escape_string($link, $_POST['when']);
$descr = mysqli_real_escape_string($link, $_POST['descr']);
$positions = mysqli_real_escape_string($link, $_POST['positions']);
// attempt insert query execution
$sql = "INSERT INTO events (ename, id, imgsrc, when, descr, positions) VALUES (`$ename`, $id , `$imgsrc`, `$when`, `$descr`, `$positions`)";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
Don't use back-ticks for binding variables to your query, use single ticks instead. You can use back-ticks for the table and column name:
INSERT INTO `events` (`ename`, `id`, `imgsrc`, `when`, `descr`, `positions`)
VALUES ('$ename', '$id', '$imgsrc', '$when', '$descr', '$positions')
WHEN is also a reserved word, so better change its name.
And since you're using mysqli_* API already, check prepared statement
You are using an SQL reserved word as a column name.
$sql = "INSERT INTO events (ename, id, imgsrc, when, descr, positions) VALUES (`$ename`, $id , `$imgsrc`, `$when`, `$descr`, `$positions`)";
You really shouldn't, but if you want to get away with this, surround your table/column names with back ticks ```, like this:
$sql = "INSERT INTO `events` (`ename`, `id`, `imgsrc`, `when`, `descr`, `positions`) VALUES ('$ename', '$id' , '$imgsrc', '$when', '$descr', '$positions')";
I've removed the back ticks you put around your values because, well, they shouldn't be there.
Please learn and use MySQLi prepared statements. They'll help.

PHP MySQL Insert Form not working

I have a MySQL database named "culvers" with a user_id INT(4) auto incrementing, a full_name varchar(20) and a user_name varchar(20). I am trying to use this HTML form to add values to the table, but it is not working. I have explored dozens of tutorials and help sites, and it still isn't working. I even put the code on another hosting provider to see if that was the problem. When I click "add" I am taken to a blank page (which is expected, since I don't have a success/error message) but the form data does not insert into the database table.
Also, I know I should sanitize my inputs, but that's not the issue right now. (At least I don't think so)
Here's the form.html code:
<html>
<head>
<title>Add User to Table</title>
</head>
<body>
<h1>Add User</h1>
<form action="adduser.php" method="POST">
<label>Full name:</label>
<input id="postname" type="text" name="fullname">
<label>Username:</label>
<input id="postuser" type="text" name="username">
<input type="submit" name="submit" value="Add">
</form>
</body>
</html>
And here's the adduser.php code:
<?php
if(isset($_POST['submit'])){
$connection = mysql_connect("localhost", "xxxx", "xxxxxxxxxx");
mysql_select_db("culvers");
$fullnameOfUser = $_POST['fullname'];
$usernameOfUser = $_POST['username'];
$sql = "INSERT INTO users (full_name, user_name) VALUES ('$fullnameOfUser', '$usernameOfUser');
$result = mysql_query($sql, $connection);
mysql_close($connection);
}else{
echo "Error no form data";
}
?>
Thank you very much for your help!
you have error in this line :
$sql = "INSERT INTO users (full_name, user_name) VALUES ('$fullnameOfUser', '$usernameOfUser');
you did not have ending "
this line should be :
$sql = "INSERT INTO users (full_name, user_name) VALUES ('$fullnameOfUser', '$usernameOfUser')";
You should use mysqli_* or PDO since all functions of mysql_* are deprecated.
You miss the double Quotes at the end of SELECT Query
$sql = "INSERT INTO users (full_name, user_name) VALUES ('$fullnameOfUser', '$usernameOfUser')";
First if it is not a typo the you need to add a double quote to query.
$sql = "INSERT INTO users (full_name, user_name) VALUES ('$fullnameOfUser', '$usernameOfUser')";
if still issue remains then print query and run it directly in phpmyadmin to see there is not issue with query.
Note: you are using mysql_* function. Please used PDO or Mysqli as your current code is prone to Sql Injection.
PDO Link: http://php.net/manual/en/book.pdo.php
Before submitting your form data, you need to start the mysql server.
you can start mysql server by the use of xampp software. once you have started your mysql server through xampp software, you can find the mysql server port number also.
the actual format of including the database is,
mysql_connect("localhost:port/database","username","password");
You forgot to close the double quotes !
'$fullnameOfUser', '$usernameOfUser')";
----^ // Add one there
The right code.
$sql = "INSERT INTO `users` (`full_name`, `user_name`) VALUES ('$fullnameOfUser', '$usernameOfUser')";
You need to switch to PreparedStatements seriously as the above code of yours is directly prone to SQL Injection.

MySQL error on form submission

I'm getting a mysql error saying "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..."
Here's the basics of my code:
First I'm populating the select menu options with rows from the categories table. This is working fine:
<select id="dropdown-select" name="Name">
<option value="" id="dropdown-option">Please select a category.</option>
<?php
$query_categories = "SELECT * FROM categories";
$result_categories = mysql_query($query_categories) or die(mysql_error());
while($categories_row = mysql_fetch_array($result_categories)) {
echo '<option id="dropdown-option" value="' . $categories_row['cat_name'] . '">' . $categories_row['cat_name'] . '</option>';
}
?>
</select>
Later, when I go submit the form to the transactions table (the above table I pulled data from was the categories table, could this be a problem?) is when I get the error. I think its related to the above code bc if I remove this element from my form submission, it writes the rest of the values to the database without any errors.
if(!isset($_POST['Name'])) {
die('You must select an income or expense from the drop down menu.');
} else {
$Name = $_POST['Name'];
}
//create query
$query = "INSERT INTO transaction (month, trans_name, budgeted, actual) VALUES ('$Month', '$Name', $Budgeted', '$Actual')";
$result = mysql_query($query) or die("Error in query: $query. " . mysql_error());
Thanks for any help you can provide.
You are missing a single quote in your insert statement before $Budgeted
INSERT INTO transaction (month, trans_name, budgeted, actual) VALUES ('$Month', '$Name', '$Budgeted', '$Actual')"
If you have some fields which are defined in Database as VARCHAR, CHAR.
Also, if you are inserting a string value in Database from a PHP script, you need to add an enclosing single quote (') around it.
In your case, you are inserting a string without semicolons, so, it showing error in MySQL.
Your statement should be corrected by adding a single quote around $budget as:
$query = "INSERT INTO transaction (month, trans_name, budgeted, actual) VALUES ('$Month',
'$Name', '$Budgeted', '$Actual')";
------^
The error "You have an error in your SQL syntax" is exactly correct!
$query = "INSERT INTO transaction (month, trans_name, budgeted, actual)
VALUES ('$Month', '$Name', $Budgeted', '$Actual')";
Look here, you missed something ----^
There is a ' missing from your statement causing the syntax error. Put the single quote in and you should be good to go!

MYSQL - INSERT error, unknown column in field list

i keep getting the following error from this simple mysql statement and i cant see why. im sure its something obvious.
require_once("connect.php");
$query = mysql_query("SELECT * FROM accounts ORDER BY id DESC LIMIT 1");
$row = mysql_fetch_assoc($query);
$balanceold = $row['balance'];
$difference = $_POST['predec'].".".$_POST['dec'];
$category = $_POST['category'];
$notes = $_POST['notes'];
if(isset($_POST['in'])){
$balancenew = $balanceold + $difference;
$query = mysql_query("INSERT INTO accounts(currentbalance, balancein, category, notes) VALUES (".$balancenew.", ".$difference.", ".$category.", ".$notes.")");
if($query){
header("Location: budget.php");
}
else{
die(mysql_error());
}
}
gives error:
Unknown column 'payday' in 'field list'
here is my form code:
<form action=process.php method=post>
£
<input type=text name=predec size=7>
.
<input type=text name=dec size=4 value=00>
<br />
<select name=category>
<option value=payday>Payday</option>
</select>
<input type=text name=notes size=20>
<input type=submit name=in value=Deposit>
<input type=submit name=out value=Withdraw>
</form>
database table"accounts" contains the following fields:
id, int primary A_I
balancein, decimal 10,2
balanceout, decimal 10,2
current balance, decimal 10,2
category, varchar 50
notes, varchar 255
date, timestamp
...in that order
try this (enclose each variable inside query with single quota):
mysql_query("INSERT INTO accounts(currentbalance, balancein, category, notes)
VALUES ('$balancenew', '$difference', '$category', '$notes')");
Its better to use mysqli or PDO to prevent from SQL injection attack, you could use mysql_real_escape_string() for now:
$balancenew = mysql_real_escape_string($balancenew);
and for other variables.
Thats because you have syntax error in your INSERT query. String and Date values are to passed into single quotes and not double quotes in sql. the . or the String concatenation character is also not required. So based on the data you provided it might be
$query = mysql_query("INSERT INTO accounts(currentbalance, balancein, category, notes)
VALUES ($balancenew, $difference, '$category', '$notes')");
Basically what sql is telling you that you are referencing a column in your insert that is not defined in the database. Provide your table structure or ensure that the column name is exactly as you defined in the db. HTH.
You have missed single inverted commas enclosing $notes and $category I guess. Enclose them in ' and your problem should be solved.

INSERT INTO database table, from form not working. SQL

lets get straight to my problem, the code I have written here does not write to my database and I cannot figue out why. At the moment I am simply trying to get to grips with php and sql so there is no point to this form other than learning. Here is the error i am getting(the first sentence 'connected to database' is from my if statement):
"Connected to databaseError: 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 ''test' ('name') VALUES ('daniel')' at line 1"
The code I have may look a little confusing as some of it is from w3schools and some is from a friend. I cannot figure out why this code isn't working, I have tried many variations of the syntax based on loads of articles I have found online and on stackoverflow but none seem to work. I fear that maybe I am not even connectec to the database, although my if statement tells me otherwise, so that could be a problem?
Hopefully if this gets solved this question will clarify database connection and writing to a database from a form in one hit. Thanks in advance guys and here's my code.
HTML
<form action="insert.php" method="post">
Name: <input type="text" name="namefield" />
<input type="submit" />
</form>
PHP (insert.php)
<?php
$dbhost = 'localhost';
$dbname = 'carbon_db';
$dbuser = 'username';
$dbpass = 'password';
$con = mysql_connect($dbhost, $dbuser, $dbpass);
if($con == FALSE)
{
echo 'Cannot connect to database' . mysql_error();
}
else
{
echo 'Connected to database';
}
mysql_select_db($dbname, $con);
$sql="INSERT INTO 'test' ('name')
VALUES ('$_POST[namefield]')";
if (!mysql_query($sql, $con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>
Drop the quotes around the table name or change them to back ticks:
Change:
$sql="INSERT INTO 'test' ('name') VALUES ('$_POST[namefield]')";
To:
$sql="INSERT INTO test ('name') VALUES ('$_POST[namefield]')";
Or
$sql="INSERT INTO `test` ('name') VALUES ('$_POST[namefield]')";
It's often best to use backticks for MySQL as like any other storage engines it has it's own reserved names and it's own reserved insert practices.
try with
$sql = "INSERT INTO `test` (`name`) VALUES ('".$_POST['namefield']."')";
Change the single quotes surrounding the table name and the column name to backticks. Or get rid of them all together.
$sql="INSERT INTO `test` (`name`) VALUES ('{$_POST['namefield']}')";
Also, don't reference associative arrays ($_POST) directly in a string without using {} syntax or breaking up the string - what you have done there issues an E_NOTICE and should be avoided.
Read this thoroughly - you'd be amazed what you can (and can't) legally do in PHP strings...
try using ` instead of ' when refering to table/column names
$sql="INSERT INTO `test` (`name`)
VALUES ('$_POST[namefield]')";
Remove the single quotes around your sql statement and replace with back-tics (not sure even they are necessary):
$sql="INSERT INTO `test` ('name')
VALUES ('$_POST[namefield]')";

Categories