Basically i've been scratching my head at this and I still can't figure out why it's not inserting.
I'm 100% sure the database is connected as it's fetching information just fine, however the following code fails to insert anything into the database. I've checked for spelling mistakes, i've checked from deprecated php code etc, and have used mysqli and mysql.
<?php
include_once "settings.php";
if (isset($_POST['sendMessage']) && isset($_POST['messageTo']) && isset($_POST['messageBody'])){
$messageTo = mysql_real_escape_string($_POST['messageTo']);
$messageBody = mysql_real_escape_string($_POST['messageBody']);
$query= "INSERT INTO inbox (`msgTo`, `msgFrom`, `msgBody`)
VALUES('$messageTo', '$username', '$messageBody')";
if(mysql_query($query))
echo "done.";
else
echo "Problem with Query";
}
?>
<form method="POST">
<div class="searchContain">
<input name="textfield" type="text" name="messageTo" class="input search"><br />
<textarea placeholder="Your message..." name="messageBody" class="input sendmsg" ></textarea><br />
<button class="input" name="sendMessage">Send Message</button>
</div>
</form>
Settings.php:
<?php
session_start();
include_once "../more/config/connect.php";
// Settings //
function logincheck(){
if (!isset($_SESSION['username'])){
header("location: ../index.php");
}
}
logincheck();
$username=$_SESSION['username'];
$gatherInfo=mysql_query("SELECT * FROM users WHERE username='$username' LIMIT 1");
$fetch=mysql_fetch_object($gatherInfo);
?>
connect.php:
<?php
// Connect to the server //
date_default_timezone_set('Europe/London');
mysql_connect("localhost", "root", "connected") or die (mysql_error ());
mysql_select_db("ts") or die(mysql_error());
?>
If anyone could help me fix this rather basic rookie error I'd be very grateful!
UPDATE:
Basically after changing the code. I've gone through the MAMP panel and changed the errors so they display. It's giving me the following error message:
Warning: mysql_connect(): Can't connect to local MySQL server through socket '/Applications/MAMP/tmp/mysql/mysql.sock' (2)
in I've never come across this error before, any ideas? It seems to fetch data from the database just fine, so I'm not sure why.
try changing your query to
$query= "INSERT INTO `inbox` (`msgTo`, `msgFrom`, `msgBody`)
VALUES('$messageTo', '$username', '$messageBody')";
you can try the following
if (isset($_POST['sendMessage']) && isset($_POST['messageTo']) && isset$_POST['messageBody'])){
$messageTo = mysql_real_escape_string($_POST['messageTo']);
$messageBody = mysql_real_escape_string($_POST['messageBody']);
$query= "INSERT INTO inbox ('msgTo', 'msgFrom', 'msgBody')
VALUES('$messageTo', '$username', '$messageBody')";
if(mysql_query($query))
echo "done.";
else
echo "Problem with Query";
}
Column names should be in single inverted commas
You should check for the mysql_query to give success response.
do not call the same function again and again i.e mysql_real_escape_string was called 2 times for the same thing. Alternatively assign that to a variable, although you need not have escaped the values to check in if condition
Related
I am creating a users database where there are 4 fields: ID, username, password, and occupation. This is a test database. I tried querying the db table and it worked but i have a lot of trouble having a user input and a MySQL query based off of it. I run an Apache server in Linux (Debian, Ubuntu).
I have 2 pages. The first one is a bare-bone test index page. this is where there are textboxes for people to input easy info to register their info in the db. Here is the code for it:
<html>
<form action="reg.php" method="POST">
Username:
<input type="text" name="u">Password:
<input type="password" name="p">Occupation:
<input type="text" name="o">
<input type="submit" value="register">
</form>
</html>
After the submit button is clicked. It goes to the reg.php file. This is where it gets complicated. The page goes blank!!! Nothing is displayed or inputted in the db. Normal queries work well, but when user interaction is added, something is wrong. Here is the code for reg.php:
<?php
$un = $_POST["u"]
$pk = $_POST["p"]
$ok = $_POST["o"]
$u = mysql_real_escape_string($un);
$p = mysql_real_escape_string($pk);
$o = mysql_real_escape_string($ok);
$link = mysql_connect('localhost', 'root', 'randompassword');
if (!$link){
die(' Oops. We Have A Problem Here: ' . mysql_error());
}
if ($link){
echo 'connected succesfully';
}
mysql_select_db("forum") or die(' Oops. We Have A Problem Here: ' . mysql_error());
$data = mysql_query("INSERT INTO users (username, password, occupation) VALUES ('{$u}', '{$p}', '{$o}')");
?>
Can anyone hep me to correct this code to make this work?
Thank you so much for your time. Much appreciated.
EDIT:
I noticed that i did not add semicolons in the first 3 lines. after doing so i got this error: "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 '{'', '', '')' at line 1." Can someone explain why?
EDIT: the website is just on my local machine...
on an apache server on linux
You are missing semi-colons in the first three lines.
$un = $_POST["u"];
$pk = $_POST["p"];
$ok = $_POST["o"];
mysql_real_escape_string() requires a db connection.
Try this ....
<?php
$un = $_POST["u"];
$pk = $_POST["p"];
$ok = $_POST["o"];
$link = mysql_connect('localhost', 'root', 'randompassword');
if (!$link){
die(' Oops. We Have A Problem Here: ' . mysql_error());
}
if ($link){
echo 'connected succesfully';
}
mysql_select_db("forum") or die(' Oops. We Have A Problem Here: ' . mysql_error());
$u = mysql_real_escape_string($un);
$p = mysql_real_escape_string($pk);
$o = mysql_real_escape_string($ok);
$sql = "INSERT INTO users (username, password, occupation) VALUES ('$u', '$p', '$o')";
$ins_sql = mysql_query($sql);
IF($ins_sql) {
echo 'Inserted new record.';
}ELSE{
echo 'Insert Failed.';
}
?>
Try adding this to the top of your script:
error_reporting(E_ALL);
ini_set("display_errors", 1);
This way you will see all errors that you made syntactically or even within your SQL.
Okay, Here's my problem. I am trying to make a posting script for my website. However this script is not working; the script is below:
<?php
// Make sure the user is logged in before going any further.
if (!isset($_SESSION['user_id'])) {
echo '<p class="login">Please log in to access this page.</p>';
exit();
}
else {
echo('<p class="login">You are logged in as ' . $_SESSION['username'] . '. Log out.</p>');
}
// Connect to the database
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (isset($_POST['submit'])) {
// Grab the profile data from the POST
$post1 = mysqli_real_escape_string($dbc, trim($_POST['post1']));
$query = "INSERT INTO ccp2_posts ('post') VALUES ('$post1')";
$error = false;
mysqli_close($dbc);
?>
<form enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<legend>Posting</legend>
<label for="post">POST:</label>
<textarea rows="4" name="post1" id="post" cols="50">Write your post here...</textarea><br />
<input type="submit" value="submit" name="submit" />
</form>
</div>
<?php
include ("include/footer.html");
?>
</body>
</html>
Nothing shows up in the database when I submit the form. Help would be amazing. Thanks.
You haven't executed the query. All you've done is opened a connection, defined the query string and closed the connection.
Add:
if(msyqli_query($dbc, $query)) {
// Successful execution of insert query
} else {
// Log error: mysqli_error($dbc)
}
after this line:
$query = "INSERT INTO ccp2_posts ('post') VALUES ('$post1')";
Update:
Started editing but had to leave... As other answerers have pointed you need to either quote the post column with a backick or remove the single quote that you currently have altogether. The only case where you need to use backticks to escape identifiers that are one of the MySQL Reserved Words.
So the working version of your query would be:
$query = "INSERT INTO ccp2_posts (post) VALUES ('$post1')";
You may have other problems, but your SQL is bad. You can't use single quotes around 'post'. You want backticks or nothing:
INSERT INTO ccp2_posts(post) VALUES ('$post1')
You missed
mysqli_query($dbc,$query);
In your code,
$query = "INSERT INTO ccp2_posts ('post') VALUES ('$post1')";
mysqli_query($dbc,$query);
Your query is not quite right:
$query = "INSERT INTO `ccp2_posts` (`post`) VALUES ('$post1')";
Note that those are backticks `, not single-quotes. This is very important! Backticks are used to name databases, tables and column names, and in particular it means you don't have to remember the extensive list of every single reserved word. You could call your column `12345 once I caught a fish alive!` if you want to!
Anyway, more importantly, you aren't actually running your query!
mysqli_query($dbc,$query);
You are not submiting to the database using, for example, the mysql_query() function.
i want to call $query somewhere inside the html and this returns undefined. Even after declaring the variable as GLOBAL i still get that error.
<?php
if($query){
echo "Nice";
}
else {
echo "Bad";
}
?>
The Full PHP
<?php
if(isset($_POST["Name"])) {
$con = mysql_connect("localhost","root","pwd", "DB");
if (!$con){
die(mysql_error());
}
$db_selected = mysql_select_db("DB", $con) or die (mysql_error());
$Name = preg_replace ('#[^a-z, 1-9 ]#i', '', $_POST['Name']);
$Slog = preg_replace ('#[^a-z ]#i', '', $_POST['Slog']);
$GLOBAL['query'] = mysql_query("INSERT INTO profiles (Name, Slog)
VALUES('$Name', '$Slog')") or die (mysql_error());
mysql_close($con);
}
?>
Here's the html with php and the $query im calling.
<form style="width:100px" action="insert.php" method="post">
<input type="text" name="Name">
<input type="text" name="Slog">
<input type="submit">
</form>
<p>
<?php
if($query){
echo "Nice";
}
else {
echo "Bad";
}
?>
</p>
are your php tags and html file located on the same document? if not. then you need to include your php file together your html codes. in .php filetype.
edit: I see a problem. you're saying "or die()" so if there's an error, it will STOP the script. if you don't want that , then you can echo the error instead of die. die will stop everything, so then query won't be defined. specifically, if the query returns false, then the "or die" happens before anything gets assigned to query.
what are you expecting query to be? it's an insert query so it should be true or false. but it has to be in the same file with the html, and what you posted is clearly not the full html.
first, try adding $con, as the second parameter of your query, eg "insert ....",$con) then, ensure you're actually getting that name parameter in the post, by adding an else or something.
I've tried looking for the problem but I can't seem to figure it out. The form shows with no errors, but on google chrome it just says "Server Error" when I try and submit the form.
<?php
if (empty($_GET["entries"])) //check if the admin entered # of weeks
{
?>
<p>How many weeks do you want to make? </p>
<form action="" method="get">
<input type="text" name="entries" placeholder="Number of weeks" />
<br/>
<input type="submit" name="submit_entries" />
</form>
<?php
}
else
{
//Second form
if (isset($_POST["submit"])) //check if submitted
{
//Process form
$entries=$_GET['entries'];
$newWeeks=$_POST['week'];
$db= mysql_connect("localhost", "root", "root");
if(!$db) die("Error connecting to MySQL database.");
mysql_select_db("onlineform", $db);
$sql = "INSERT INTO onlineformdata (numberOfWeeks, newCampSessions) VALUES (" . PrepSQL($entries) . "," . PrepSQL($newWeeks) . ")";
mysql_query($sql);
if (mysql_query($sql) === FALSE) {
die(mysql_error());
}
mysql_close();
}
else //if not submitted yet, show the form
{
echo '<form action="" method="post">';
for ($count = 0; $count < $_GET["entries"]; $count++)
{
echo 'Enter a beginning to ending date for the week: <input type="text" name="week"><br/>';
}
echo '<input type="submit" name="submit"></form>';
}
}
?>
Maybe it's because I can't have the first form having an action pointing to itself (Where I'm using a method="get".
You don't appear to have defined the PrepSQL() anywhere. If that's the case you should be getting a fatal error, something like
Fatal error: Call to undefined function PrepSQL ...
Once that's fixed, if you're insert query is failing, it will probably be because of the values lacking enclosing quotes.
For future debugging you can turn errors on:
error_reporting(E_ALL);
ini_set('display_errors', '1');
Or you can just observe your server's error log. How that is done depends on the server setup so I suggest asking your host for directions.
Side note:
The mysql_* library is deprecated, consider upgrading to PDO or MySQLi
The use of a Prepared Statement is preferred to concatenating variables into your SQL.
I have been trying for two days now to figure this one out. I copied verbatim from a tutorial and I still cant insert data into a table. here is my code with form
<font face="Verdana" size="2">
<form method="post" action="Manage_cust.php" >
Customer Name
<font face="Verdana">
<input type="text" name="Company" size="50"></font>
<br>
Customer Type
<font face="Verdana">
<select name="custType" size="1">
<option>Non-Contract</option>
<option>Contract</option>
</select></font>
<br>
Contract Hours
<font face="Verdana">
<input type="text" name="contractHours" value="0"></font>
<br>
<font face="Verdana">
<input type="submit" name="dothis" value="Add Customer"></font>
</form>
</font>
<font face="Verdana" size="2">
<?php
if (isset($_POST['dothis'])) {
$con = mysql_connect ("localhost","root","password");
if (!$con){
die ("Cannot Connect: " . mysql_error());
}
mysql_select_db("averyit_net",$con);
$sql = "INSERT INTO cust_profile (Customer_Name, Customer_Type, Contract_Hours) VALUES
('$_POST[Company]','$_POST[custType]','$_POST[contractHours]')";
mysql_query($sql, $con);
print_r($sql);
mysql_close($con);
}
?>
This is my PHPmyadmin server info:
Server: 127.0.0.1 via TCP/IP
Software: MySQL
Software version: 5.5.27 - MySQL Community Server (GPL)
Protocol version: 10
User: root#localhost
Server charset: UTF-8 Unicode (utf8)
PLEASE tell me why this wont work. when I run the site it puts the info in and it disappears when I push the submit button, but it does not go into the table. There are no error messages that show up. HELP
I have improved a little bit in your SQL statement, stored it in an array and this is to make sure your post data are really set, else it will throw a null value. Please always sanitize your input.
in your Manage_cust.php:
<?php
if (isset($_POST['dothis']))
{
$con = mysql_connect ("localhost","root","password");
if (!$con)
{
die ("Cannot Connect: " . mysql_error());
}
mysql_select_db("averyit_net",$con);
$company = isset($_POST['Company'])?$_POST['Company']:NULL;
$custype = isset($_POST['custType'])?$_POST['custType']:NULL;
$hours = isset($_POST['contractHours'])?$_POST['contractHours']:NULL;
$sql = "INSERT INTO cust_profile(Customer_Name,
Customer_Type,
Contract_Hours)
VALUES('$company',
'$custype',
'$hours')
";
mysql_query($sql, $con);
mysql_close($con);
}
?>
First of all, don't use font tags...ever
Secondly, because of this line:
if (isset($_POST['dothis'])) {
It looks like your HTML and PHP are combined into one script? In which case, you'll need to change the action on the form to something like this:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" >
Plus, you can kill a bad connection in one line:
$con = mysql_connect("localhost","root","password") or die("I died, sorry." . mysql_error() );
Check your posts with isset() and then assign values to variables.
var $company;
if(isset($_POST['Company']) {
$company = $_POST['Company'];
} else {
$company = null;
}
//so on and so forth for the other fields
Or use ternary operators
Also, using the original mysql PHP API is usually a bad choice. It's even mentioned in the PHP manual for the API
Always better to go with mysqli or PDO so let's convert that:
//your connection
$conn = mysqli_connect("localhost","username","password","averyit_net");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$sql = "INSERT INTO cust_profile (Customer_Name, Customer_Type, Contract_Hours)
VALUES ($company,$custType,$contractHours)";
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Assuming you set these
$stmt = mysqli_prepare($conn, $sql);
$stmt->execute();
$stmt->close();
Someone tell me if this is wrong, so I can correct it. I haven't used mysqli in a while.
Change the $sql to this:
$sql = "INSERT INTO cust_profile (Customer_Name, Customer_Type, Contract_Hours) VALUES ('".$_POST[Company]."','".$_POST[custType]."','".$_POST[contractHours]."')