PHP not Inserting into MySQL database all statements are there - php

I was wondering if anyone had input as to why this statement isn't inserting into my MySQL database. It's not showing any errors and when I enter the SQL statement in manually it inserts the info.
<?php
$host="mysql16.000webhost.com";
$user_name="a1611480_akaash";
$pwd="*****";
$database_name="a1611480_akaash";
$db=mysql_connect($host, $user_name, $pwd);
$sql = "INSERT INTO mydata VALUES ('dude1', 'dude2', 'dude3', 'dude4', 'dude5')";
mysql_query($sql);
?>

This is due to the fact that mysql does not know which database to use for this SQL statement.
Include mysql_select_db.
mysql_select_db($database_name);
To get any type of error in php (except fatals) enclose your code with a try block
try{
// db code
}catch(Exception $e){
// something is wrong
echo "Oh God! I got this ". $e->getMessage();
}

To see the error do this:
mysql_query($sql) or die("Error:".mysql_error());
And from your query i am assuming that you have one column and you want to add multiple values
So this maybe the format:
$sql = "INSERT INTO mydata VALUES
('dude1'), ('dude2'), ('dude3'), ('dude4'), ('dude5);";

That's because you don't mention the column names - see http://www.w3schools.com/php/php_mysql_insert.asp
Also you forgot to select the database - mysql_select_db("my_db");
So your query would have to be something like "INSERT INTO mydata (column1, column2, column3, column4, column5) VALUES ('dude1', 'dude2', 'dude3', 'dude4', 'dude5')";
Edit: Of course Corey is right. It's just a better practice I think - I always do it :)

You are connecting to a remote host, are you sure you have the rights to do so? Where is this code executed?
Outputting the result of mysql_error() would be useful!

Related

PHP MySQL Inserting data in a database table using PHP script

Using the given below php script, I connect to database and insert data in it. But the data is not getting inserted in my database table. It is also not throwing any error. Where is my code wrong?
<?php
$host = '127.0.0.1';
$uname='root';
$pswd='';
$myDB='portal';
if($myConn = new mysqli($host,$uname,$pswd))
echo 'Connected to MySQL server successfully.</br>';
else
echo 'Unable to connect to server</br>';
$database = mysqli_select_db($myConn,$myDB);
if($database)
echo 'Connected to database...</br>';
else
echo 'Database not found!</br>';
$var1='string1';
$var2='string2';
$query= "INSERT INTO users VALUES ($var1,$var2)";
$result = mysqli_query($myConn,$query) or die(mysqli_error($myConn));
?>
You have to add single quotes around the values:
$query= "INSERT INTO users VALUES ('$var1','$var2')
Or better use prepared statements. See this for an example.
In your statement, you must define the names of the target tables in your database, that the values should be inserted into, like this:
$query= "INSERT INTO users (Name,Age) VALUES ('$name','$age')";
if users table have only two columns, or two plus an auto-incrementing id the query is:
INSERT INTO users VALUES ('$var1','$var2')
if there are more columns or a non primary id the query is:
INSERT INTO users (col1,col2) VALUES ('$var1','$var2')
You also miss a parameter in the connection instantiation:
$mysqli = new mysqli($host, $uname,$pswd, $myDB);

PHP post limit? Other mysql issue?

I've been searching around for a solution, but each one I've found seems to not be helpful, I'm not actually sure whats causing the issue.
If I run the below mysql, this inserts a record into the database.
INSERT INTO cust_v_lists (Customer_name, Customer_ref) VALUES ('wouldja', 133)
What my program is currently doing is creating the above statement using parameters from page 1, then posting the mysql to page 2. On page 2 my code is simple.
$mysqli = $_POST['sqli'];
echo $mysqli; #this echo's out the above SQL insert line.
$result = mysqli_query($conn, $mysqli);
$updated = mysqli_affected_rows($conn);
$message = "You have inserted $updated row to the 'cust_v_lists' table.";
echo $message;
if (!mysqli_query($conn, $mysqli))
{
echo("Error description: " . mysqli_error($conn));
}
If I hard code the below:
$sqli = ;INSERT INTO cust_v_lists (Customer_name, Customer_ref) VALUES ('wouldja', 133)';
This works fine, but when I post it I get the 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 '
INSERT INTO cust_v_lists (Customer_name, Customer_ref) VALUES ('w' at line 1
I first thought this was a post limit or something to 40 chars, but when I echo out the mysqli posted it seems ok, I changed the limits in php.ini just in case but this didn't help. I then updated this to a string using $mysqli = (string)$mysqli but this also didn't help. Has anyone seen this before? I don't want to hard code this, I need the query to be completely dynamic and readable from $_POST.
$sqli = ;INSERT INTO cust_v_lists (Customer_name, Customer_ref) VALUES ('wouldja', 133)';
needs to be
$sqli = "INSERT INTO cust_v_lists (Customer_name, Customer_ref) VALUES ('wouldja', 133)";
Try this insert statement
$sqli = "INSERT INTO cust_v_lists (Customer_name, Customer_ref)
VALUES ('wouldja',133)";

Inserting a variable with a comma in it to SQL database?

I've been trying to insert a variable that has a comma in it to a SQL database for 30 minutes or so. I've echoed the variable, and the comma is there, but when it inserts, there's no comma!
Example (some code like mine):
$variable1 = "test";
$variable2 = "$variable1,";
$sql1 = "INSERT INTO table (`column`) VALUES ('$variable2')";
$query1 = mysqli_query($con,$sql1); //I dont think I need to put a con variable up there for an example code
And when I do:
echo $variable2;
The result is test, with the comma, but the data in the column is just test WITH NO COMMA.
Help please.
Thanks.
Edit:
Your Common Sense fixed it, apparently I needed brackets around '$variable2' so it's like:
$sql1 = "INSERT INTO table (`column`) VALUES (('$variable2'))";
Thanks Your Common Sense and everyone else who tried!
Well, the answer is simple.
It's your own code does remove this comma, either before insert or after fetch.
If you care to write a reproduceable test case, you will see that noone is taking your comma.
Test case means code that involves the behavior in question and nothing else. Not a single line of code beside insert and fetch:
$variable1 = "test";
$variable2 = "$variable1,";
$sql1 = "INSERT INTO users (username) VALUES ('$variable2')";
mysqli_query($db,$sql1);
$sql2 = "SELECT username FROM users WHERE username ='$variable2'";
$res = mysqli_query($db,$sql2);
$row = mysqli_fetch_row($res);
var_dump($variable1, $variable2, $sql1, $sql2, $row[0]);
run it, see it all with comma in place, and then search your own code for the comma trimming code
or may be you have just test without comma in your table, ans select this one all the time, instead of one with comma.
or whatever silly error of the like
Try it like this:
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');
$stmt = $mysqli->prepare("INSERT INTO table ('column') VALUES (?)");
$stmt->bind_param($variable2);
/* execute prepared statement */
$stmt->execute();
This is more safe and will not trigger such strangeties. (Is that a word?)
What happens here is, that the query is send to the sql database and this returns a statement. The statement has some holes, these are the ?, in it.
When using bind_param you fill the holes and then you can execute.
This has a couple of advantages:
It is safe
You can reuse your statement
It is easier than string interpolation stuff
Try "INSERT INTO table ('column') VALUES ('" . $variable2 . "');"

php query to insert string into database

<?php
$username = $_POST['username'];
$password = $_POST['password'];
if($username&&$password)
{
$connect = mysql_connect("CiniCraftData.db.55555555.hostedresource.com", "CiniCraftData", "*********") or die("Couldn't Connect");
mysql_select_db("CiniCraftData") or die ("Couldn't Find Database");
$query = "INSERT INTO CiniUsers ('username.CINIDAT') VALUES('$username')";
$result = mysql_query($query) or die("Error occurred.");
}
else die("Please enter a username and password.");
?>
For this part of the code:
$query = "INSERT INTO CiniUsers ('username.CINIDAT') VALUES('$username')";
The VALUES seem to not be working properly, I need whatever the string value of $username is to be inserted into my CiniUsers database. What do I need to do to make the code above work? I'm very new to php and sql syntax and the guides I'm finding online are all completely different from each other as if they keep updating php.
Try reviewing this part:
$query = "INSERT INTO CiniUsers ('username.CINIDAT') VALUES('$username')";
The syntax is:
$query = "INSERT INTO table (column) VALUES ('$strvar')";
What is the column name you wanted to insert into?
If it is username.CINIDAT then try removing the qoutes.
Like this:
$query = "INSERT INTO CiniUsers (username.CINIDAT) VALUES ('$username')";
or maybe your column is named username so:
$query = "INSERT INTO CiniUsers (username) VALUES ('$username')";
UPDATE
The query from your comment, change it to this:
$query = "INSERT INTO CiniUsers (username.CINIDAT) VALUES ('$username')";
The format for the SQL statement is as so:
INSERT INTO nameOfTable (column1, column2, column3, etc) VALUES ('column1', 'column2', 'column3', 'etc')
You MUST make sure that you are using the field names exactly as they are stored in MySQL.
Your SQL could appear like so:
$query = "INSERT INTO CiniUsers (username) VALUES('$username')";
OR
$query = "INSERT INTO CiniUsers (username) VALUES('{$username}')";
Another thing that may help is that your die() statement is not very helpful. Yes, it is a bummer when your php program quits early, but it will save you a lot of time and frustration if you know why it quit. Although you may still be learning PHP and MySQL and may not know what the errors mean, they will start to make sense the more you see them and can tell you whether your query was bad, the connection failed or many more things. Change to something like this:
$connect = mysql_connect("CiniCraftData.db.55555555.hostedresource.com", "CiniCraftData", "*********") or die("Couldn't Connect: mysql_error()");
mysql_select_db("CiniCraftData") or die ("Couldn't Find Database: mysql_error()");
...
$result = mysql_query($query) or die("Some kind of error occurred...Query failed: mysql_error()");
You find that seeing the mysql_error() will help you solve problems like this much faster.
USE phpMyAdmin to test your query out, your query may be working perfectly. It is really the only way to know for sure. Use the suggested SQL and replace the PHP variable with some dummy data like "testUsername_1". If the query works, you will have manually added the username to the db, if not, the problem lies in SQL statement.
Here is some documentation on SQL INSERT INTO statements if you need more details:
http://www.w3schools.com/sql/sql_insert.asp
I think you should use mysqli or pdo. This liberary you are using is deprecated.
That said, what is username.CINIDAT? I think this is where your problem is. It should be something like this
$query = "INSERT INTO CiniUsers (username) VALUES('$username')";
I am assuming that CiniUsers is the table name and username is the column name.
The simplest way is to build the query by concatenating the statement with the value.
$query = "INSERT INTO CiniUsers ('username.CINIDAT') VALUES('".$username."')";
Without validation, this is not a very good idea, or something like this is very easy.

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