I'm brand new to PHP and just trying to create a very basic registration form but when I click submit it won't create the data in my database.
<form action"signup.php" method="post">
username:<input type="text" name="n"><br />
password:<input type="password" name="p"><br />
id :<input type="text" name="id"><br />
<input type="submit">
</form>
<?php
$conn = mysql_connect("localhost", "root", "");
$db = mysql_select_db("myth", $conn);
?>
<?php
$user = $_POST['n'];
$pass = $_POST['p'];
$id = $_POST['id'];
$sql = "INSERT into phplogin values(" . $id . ",'" . $user . "','" . $pass . "')";
$query = mysql_query();
if(!$query)
echo "failed ".mysql_error();
else
echo "successful";
?>
You're not actually running the query - you need to call mysql_query($sql).
Note that your code is quite vulnerable to things like SQL injection, and mysql_query is a deprecated function in PHP.
First of all, you have not to use mysql_* command as they are deprecated; use mysqli_* or PDO instead.
Second, you have to pass your string at method. In your case: $result = mysql_query($sql);
Remember that $result will return a resource that you have to fetch for obtain your rows
while ($row=mysql_fetch_row($result)) {
// here, you have your rows
}
your script should be like this
<?php
// create connection
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
// check connection
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$user = $_POST['n'];
$pass = $_POST['p'];
$id = $_POST['id'];
$sql = "INSERT into phplogin values('$id','$user','$pass')";
if($mysqli->query($query)) {
printf("New Record has id %d.\n", $mysqli->insert_id);
} else {
printf("Failed ".$mysqli->error);
}
// close connection
mysqli_close($link);
?>
And yes don't use mysql_* as it's deprecated, use mysqli_ or PDO instead.
Try to use mysqli_query as it is better than mysql_query...
<?php
$conn = mysqli_connect("localhost","root","","myth")or die("connection to database problem");
$user = $_POST['n'];
$pass = $_POST['p'];
$id = $_POST['id'];
$sql = "INSERT INTO phplogin VALUES (".$id.",'".$user."','".$pass."')";
$query = mysqli_query($conn, $sql)or die("query error");
if(false===$query)
echo "<br/>".mysqli_error($conn)."<br/><br/><br/>";
else
echo "<br/>done ";
?>
If there is any problem in connection the connection to database problem should occur
Related
So currently, this is the code I have
index.php:
<form action="insert.php" method="post">
Comments:
<input type="text" name="comment">
<input type="submit">
</form>
insert.php:
<?php
include ('index.php');
$user = 'x';
$password = '';
$db = 'comment_schema';
$host = 'localhost';
$port = 3306;
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "x", "", "comment_schema");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$comment = mysqli_real_escape_string($link, $_POST["comment"]);
$sql = "INSERT INTO parentComment(ID, Comment) VALUES('','$comment')";
// attempt insert query execution
if(mysqli_query($link, $sql)){
echo $comment;
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
When I do echo $comment, nothing gets printed out. However, if I do something like echo "hi" it works. I think for some reason the $_POST is not being recognized. Any suggestions to make this work or if I'm doing it wrong.
My goal is to take a user input and insert into a database on phpmyadmin. Currently, it is able to insert, however it inserts an empty value. I only have two columns in my database. An ID and a Comment column. The ID is auto incremented. The comment is what I get from the user.
Check Once what is your data type of comment in database.(I prefer Varchar()).
Try this as it is:-
<form action="insert.php" method="POST">
Comments:
<input type="text" name="comment"/>
<input type="submit" name="submit" value="submit">
</form>
<?php
include ('index.php');
$user = 'x';
$password = '';
$db = 'comment_schema';
$host = 'localhost';
$port = 3306;
$link = mysqli_connect("localhost", "x", "", "comment_schema");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$comment = mysqli_real_escape_string($link, $_POST["comment"]);
$sql = "INSERT INTO parentComment(ID, Comment) VALUES('','$comment')";
if(mysqli_query($link, $sql)){
echo $comment;
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
try this
<?php
$user = 'x';
$password = '';
$db = 'comment_schema';
$host = 'localhost';
$link = mysqli_connect($host, $user, $password, $db);
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$comment = mysqli_real_escape_string($link, $_POST["comment"]);
$sql = "INSERT INTO parentComment(ID, Comment) VALUES(NULL,'$comment')";
// attempt insert query execution
if(mysqli_query($link, $sql)){
echo $comment;
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
Use below code:-
include ('index.php');
$user = 'x';
$password = '';
$db = 'comment_schema';
$host = 'localhost';
$port = 3306;
$link = mysqli_connect("localhost", "x", "", "comment_schema");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if(!empty($_POST["comment"])){
$comment = mysqli_real_escape_string($link, $_POST["comment"]);
// Escape user inputs for security
$sql = "INSERT INTO parentComment(ID, Comment) VALUES('','$comment')";
$result = mysqli_query($link, $sql);
// attempt insert query execution
if($result){
echo $comment;
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
}else{
die('comment is not set or not containing valid value');
}
Hope it will help you :-)
Some debugging suggestions:
var_dump($_POST); // before mysqli_real_escape_string
var_dump($comment); // after mysqli_real_escape_string
mysqli api may not work well! Fix the query like
$sql = "INSERT INTO parentComment(ID, Comment) VALUES('','".$comment."')";
echo $sql; // check your sql syntax
echo mysqli_error($link); // do you have error
Look at your .htaccess file see if you have <Limit POST> tag
Remove this line include ('index.php');. Supposedly, these two files are in one folder. So just run index.php . Tried your code without that line and it worked for me.
New to php and am connecting form attributes to php to connect to a godaddy mysql. Every attempt ends in a blank screen with no error messages. Is there any syntax errors the jump out? My sublime text wont register php syntax, but thats another problem for another time. I may need to call up godaddy support? the password has been removed for privacy.
<?php
$servername = "localhost";
$dbusername = "jaysenhenderson";
$dbpassword = "xxxxx";
$dbname = "EOTDSurvey";
$con = new mysqli ($servername, $dbusername, $dbpassword, $dbname);
mysql_select_db('EOTDSurvey', $con)
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo("Connected successfully");
$_POST['BI1']
$_POST['BI2']
$_POST['BI3']
$_POST['BI4']
$_POST['BI5']
$_POST['BI6']
$_POST['BI7']
$_POST['BI8']
$_POST['BI9']
$_POST['BI10']
$_POST['BI11']
$_POST['BI12']
$_POST['BI13']
$_POST['BI14']
$_POST['BI15']
$sql = "INSERT INTO Survey1(BI1)"
$sql = "INSERT INTO Survey1(BI2)"
$sql = "INSERT INTO Survey1(BI3)"
$sql = "INSERT INTO Survey1(BI4)"
$sql = "INSERT INTO Survey1(BI5)"
$sql = "INSERT INTO Survey1(BI6)"
$sql = "INSERT INTO Survey1(BI7)"
$sql = "INSERT INTO Survey1(BI8)"
$sql = "INSERT INTO Survey1(BI9)"
$sql = "INSERT INTO Survey1(BI10)"
$sql = "INSERT INTO Survey1(BI11)"
$sql = "INSERT INTO Survey1(BI12)"
$sql = "INSERT INTO Survey1(BI13)"
$sql = "INSERT INTO Survey1(BI14)"
$sql = "INSERT INTO Survey1(BI15)"
if ($conn->query<$sql) === TRUE) {
echo "IT FUCKING WORKS.";
}
else{
echo "didnt workkkkkk";
}
$conn->close();
?>
please connect database like this...
$connection = mysqli_connect(DB_SERVER,DB_USER,DB_PASS);
if (!$connection) {
die("Database connection failed: " . mysqli_error());
}
// 2. Select a database to use
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
die("Database selection failed: " . mysqli_error());
}
And Use mysqli_select_db instead of mysql_select_db
And insert semi-colon (;) after every line end according to php code standard.
There are a lot of issues with this code, as mentioned the mysqli_select_db issue. The $_POST['BIx'] will also cause errors because there is no semi-colon after each statement. You're missing a '(' on the line if ($conn->query<$sql) === TRUE) { not to mention that line will not work anyway because you're logically comparing a resource type (I think) to a string.
You're also never executing the insert statements. All around I seriously think you should practice PHP coding some more and read up on how to use mysqli properly: see here.
Regards
EDIT: You also have a closing PHP tag at the end of your script which is generally not a good idea as explained here
EDIT 2: Also using an IDE such as Netbeans is always a good idea as it can highlight syntax errors instead of asking SO to do it for you ;)
<?php
$servername = "localhost";
$dbusername = "jaysenhenderson";
$dbpassword = "xxxxx";
$dbname = "EOTDSurvey";
$con = new mysqli ($servername, $dbusername, $dbpassword, $dbname);
mysqli_select_db('EOTDSurvey', $con);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo("Connected successfully");
############# Function For Insert ##############
function insert($tableName='',$data=array())
{
$query = "INSERT INTO `$tableName` SET";
$subQuery = '';
foreach ($data as $columnName => $colValue) {
$subQuery .= " `$columnName`='$colValue',";
}
$subQuery = rtrim($subQuery,', ');
$query .= $subQuery;
pr($query);
mysqli_query($con,$query) or die(mysqli_error());
return mysqli_insert_id();
}//end insert
#########################################
if(isset($_POST['submit'])){
unset($_POST['submit']);
//print_r($_POST);
$result=insert('Survey1',$_POST);
if($result){
echo '<script>window.alert("Success!");</script>';
echo "<script>window.location.href = 'yourpage.php'</script>";
}
}
$conn->close();
?>
include_once 'dbfunction.php';
getDbConnect();
mysqli_query("DELETE FROM crewlist WHERE id = $_GET[crew_id]") or die (mysqli_error());
echo 'Delete success';
header ('Location: crewlisting.php');
This code doesn't work, however when I replace the crew_id with the actual primary key via hard coding the delete function works
Use this (MySQLi Procedural)
In dbfunction.php should be
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
?>
and insert page should be
<?
include ("dbfunction.php"); //include db connection
$id = $_REQUEST['crew_id'];
$sql = "DELETE FROM crewlist WHERE id = '$id' ";
if (mysqli_query($conn, $sql))
{
echo "Record deleted successfully";
}
else
{
echo "Error deleting record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
Errors are
There is no function define in getDbConnect()
If you are confusing with 'and " then split the functions
$id = $_REQUEST['crew_id'];
$sql = "DELETE FROM crewlist WHERE id = '$id' ";
Use mysqli_query and mysqli_error in correct format
and error in mysqli_query, You are not passing connection to MySQLi
When ever database part is Finished, Close connection mysqli_close($conn);
Correct your query:
mysqli_query("DELETE FROM crewlist WHERE id ='".$_GET['crew_id']."'") or die('Error: ' . mysqli_error());
I have a html form, say example
<form action="form.php" method="post">
First name:<br>
<input type="text" id="fname" name="fname">
<br>
Last name:<br>
<input type="text" id="lname" name="lname">
<br><br>
<input type="submit" value="Submit">
</form>
and form.php
<?php
$servername = "localhost";
$username = "database1";
$password = "xxxxxxxx";
$dbname = "database1";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//escape variables for security
$fname = mysqli_real_escape_string($conn, $_POST['fname']);
$lname = mysqli_real_escape_string($conn, $_POST['lname']);
$sql = "INSERT INTO mytable (fname,lname)
VALUES ('$fname','$lname')";
if ($conn->query($sql) === TRUE) {
echo "Successfully Saved";
} else {
echo "Error: Go back and Try Again ! " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
The form.php is saving that data to database1 .
I want that data to be saved to another database database2 along with database1.
Is it possible ?? If yes then what changes should be made in the code ?
If it is not possible then is it possible to copy data from database1 to database2 automatically? Whenever a new row is added in database1 then it should automatically copied to database2.
I want the same data to be in two different database. How can I achieve any of the above said ??
From php you just have to create new connection to DB.
<?php
$servername = "localhost";
$username = "database1";
$password = "xxxxxxxx";
$dbname = "database1";
$servernameS = "localhost";
$usernameS = "database2";
$passwordS = "xxxxxxxx";
$dbnameS = "database2";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$connS = new mysqli($servernameS, $usernameS, $passwordS, $dbnameS);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($connS->connect_error) {
die("Connection failed: " . $connS->connect_error);
}
//escape variables for security
$fname = mysqli_real_escape_string($conn, $_POST['fname']);
$lname = mysqli_real_escape_string($conn, $_POST['lname']);
$sql = "INSERT INTO mytable (fname,lname)
VALUES ('$fname','$lname')";
if ($conn->query($sql) === TRUE) {
echo "Successfully Saved";
} else {
echo "Error: Go back and Try Again ! " . $sql . "<br>" . $conn->error;
}
if ($connS->query($sql) === TRUE) {
echo "Successfully Saved";
} else {
echo "Error: Go back and Try Again ! " . $sql . "<br>" . $connS->error;
}
$conn->close();
$connS->close();
?>
What it sounds like you need is to setup replication.
Here is the official documentation on replication. Here is a simpler step-by-step guide setting it up.
If replication isn't what you wanted, you could accomplish the same thing by connecting to database2 in addition to database1 then running the query once on both.
You can use something like using mysqli::selectDB method:
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* return name of current default database */
if ($result = $mysqli->query("SELECT DATABASE()")) {
$row = $result->fetch_row();
printf("Default database is %s.\n", $row[0]);
$result->close();
}
/* change db to world db */
$mysqli->select_db("world");
/* return name of current default database */
if ($result = $mysqli->query("SELECT DATABASE()")) {
$row = $result->fetch_row();
printf("Default database is %s.\n", $row[0]);
$result->close();
}
$mysqli->close();
?>
Check out the manual.
Similar question as yours at SO.
<html>
<body>
<?php
$host = 'localhost';
$user = 'users';
$pw = '';
$db = '#######';
$connect = mysql_connect($host,$user,$pw)
or die ("Could not connect.");
mysql_select_db($db);
$sql = mysql_query("INSERT INTO users VALUES ('','l','l','l','l','l','l')");
if(mysql_query($sql)){
print "Item added successfully.<br/>";
}
else{
print "Item addition failed.<br/>";
}
?>
</body>
</html>
I am trying to insert these values into my database into the table users but when I run the code it keeps on saying "item addition failed" but I am not sure why, there is no problem with the database connection as I have already tested that, and I am not sure what's wrong with my insert query?
There are some problems in your code. Firstly you do query twice. Secondly are you sure your db name is $db = '#######'; change it to proper name.
To check if query was ok and if rows were added use mysql_affected_rows() to check errors use mysql_error()
Also change your sql engine to PDO or mysqli which are better.
Please mind that Mysql_* functions are depracated. That is why I've given you example how to use db connection in PDO.
<?php
$host = 'localhost';
$user = 'users';
$pw = '';
$db = '#######'; //CHANGE IT TO PROPER NAME WHERE TABLE users IS!
$connect = mysql_connect($host,$user,$pw)
or die ("Could not connect.");
mysql_select_db($db);
$sql = mysql_query( "INSERT INTO users VALUES('' ,'l','l','l','l', 'l','l')") or die(mysql_error());
if(mysql_affected_rows()>0)
echo "Item added successfully.<br/>";
else
echo "Item addition failed.<br/>";
?>
I'll give you proper example how to do it with PDO cause if you still learn it'll help you :)
PDO example
<?php
$dsn = 'mysql:dbname=YOUR_DB_NAME;host=localhost';
$user = 'users';
$password = '';
try {
$dbh = new PDO($dsn, $user, $password);
$count = $dbh->exec("INSERT INTO users VALUES('' ,'l','l','l','l', 'l','l');");
echo $cout ? "Item added successfully" : "Item addition failed";
} catch (PDOException $e) {
echo 'Failed: ' . $e->getMessage();
}
?>
The secure and good way to insert values is using prepared statements.
To create prepared statement you use
$stmt = $dbh->prepare("INSERT INTO users (name, email) VALUES(?,?)");
$stmt->execute( array('user', 'user#example.com'));
You can learn more here
You are using mysql_query twice. Change your code to:
$sql = "INSERT INTO users VALUES ('' ,'l','l','l','l', 'l','l')";
try this.your called function mysql_query() twice.
on second time you passed it the result_set instead of query.
<html>
<body>
<?php
$host = 'localhost';
$user = 'users';
$pw = '';
$db = '#######';
$connect = mysql_connect($host,$user,$pw)
or die ("Could not connect.");
mysql_select_db($db);
$sql = mysql_query( "INSERT INTO users
VALUES('' ,'l','l','l','l', 'l','l')");
if($sql){
print "Item added successfully.<br/>";
}
else { print "Item addition failed.<br/>"; }
?>
</body>
</html>
This should help you debug, you should look into PDO instead though... And of course remember to use the correct credentials, i presume you have removed them for safety :-)
mysql_select_db($db);
$sql = mysql_query("INSERT INTO users VALUES ('','l','l','l','l','l','l')", $connect) OR die(mysql_error());
if($sql)
{
print "Item added successfully.<br/>";
}
else{
print "Item addition failed.<br/>";
}
?>