PHP insert query not working - php

<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/>";
}
?>

Related

Mysql & Php Database connection error

When ever I use php to connect to my database I get a sudden error saying "database connection failed" is there anyway to fix this its for a login and register screen. Thanks to anyone who help...
<?php
$connection = mysqli_connect('localhost', 'root','','test');
if (!$connection){
die("Database Connection Failed" . mysqli_error($connection));
}
$select_db = mysqli_select_db($connection, 'test');
if (!$select_db){
die("Database Selection Failed" . mysqli_error($connection));
}
<?php
//
require('database.php');
$connection = mysqli_connect('localhost', 'root','','test');
// If the values are posted, insert them into the database.
if (isset($_POST['Register'])){
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$query = "INSERT INTO `user` (username, email, password) VALUES ('$username', '$email', '$password')";
//echo $query;
$result=mysqli_query($connection,$query);
if($result){
$smsg = "User Created Successfully.";
}else{
$fmsg ="User Registration Failed";
}
}
?>
Connection to a database with php requires 4 parameters (host, data base user, password, data base name, passwd), it's better nowadays to use db object instead of procedural "old" behaviour:
function connection(){
try{
//host, user, passwd, DB name)
$mysqli = new mysqli("localhost", $dbUser, $passwd, $dbName);
if (!$mysqli->set_charset("utf8")) $msg = "error charset mySQLi"; else $msg = "Set UTF-8 ok";
return $mysqli;
}
catch (Exception $mysqlin){
echo "Error stablishing connection with database ".$mysqlin->getMessage();
}
}
then you can connect easily as follows:
$sql = "SELECT * FROM users;";
if(!$result = connection()->query($sql)) echo "db query error"; else "query ok";
$rs = mysqli_fetch_assoc($result);
//do whatever and, to get next line of results:
if($rs!=''){
$rs = mysqli_fetch_assoc($result);
}
So you get a row of the results on $rs[] array.
EDIT: You'll need to apply security, this is a simple connection without regarding on it. Check mysqli bind params on php official webpage for it:
http://php.net/manual/en/mysqli-stmt.bind-param.php
Hope it helps

Updating data in DataBase with PHP

I have a simple script that should Update variable in a column where user login equals some login.
<?PHP
$login = $_POST['login'];
$column= $_POST['column'];
$number = $_POST['number'];
$link = mysqli_connect("localhost", "id3008526_root", "12345", "id3008526_test");
$ins = mysqli_query($link, "UPDATE test_table SET '$column' = '$number' WHERE log = '$login'");
if ($ins)
die ("TRUE");
else
die ("FALSE");
?>
but it doesn't work. It gives me - FALSE. One of my columns name is w1 and if I replace '$column' in the code with w1 it works fine. Any suggestions?
Simply remove quotes: '$column' = should be $column =
Your code is open for SQL Injection, use prepared statements.
change this "UPDATE test_table SET '$column' = '$number' WHERE log = '$login'"
to this "UPDATE test_table SET '".$column."' = ".$number." WHERE log = '".$login."'"
It's possible that your error is to do with the $column being set as a string with single quotation marks? Because it returns false, it suggests that you have a MySQL error of some sort.
To find out what the error message is, on your else block, rather than dying with a "FALSE" message, try use mysqli_error($link) - this should give you your error message
If removing the quotes surrounding the $column doesn't work, you could try the PDO method. Here's the snippet:
function insertUser($column, $number, $login) {
try
{
$connect = getConnection(); //db connection
$sql = "UPDATE test_table SET $column = '$number' WHERE log = '$login'";
$connect->exec($sql);
$connect = null;
} catch (Exception $ex) {
echo "EXCEPTION : Insert failed : " . $ex->getMessage();
}
}
function getConnection() {
$servername = "localhost";
$dbname = "my_db";
$username = "root";
$password = "12345";
try {
$connection = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $ex) {
echo "EXCEPTION: Connection failed : " . $ex->getMessage();
}
return $connection;
}
Regarding $number, I'm not sure the datatype for the $number whether quotes or not is needed so experiment with or without quotes to see which one works.
And the getConnection() function is in separate PHP file where it will be included in any PHP files that calls for database connection.

Cant connect php to mysql

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();
?>

not response for database

This is the code for database connection in php:
<?php
$connection = mysql_connect("localhost", "root", "root"); // Establishing Connection with Server
$db = mysql_select_db("fimos", $connection); // Selecting Database from Server
if(isset($_POST['submit'])){ // Fetching variables of the form which travels in URL
$gender = $_POST["gender"]; //declare gender
$race = $_POST["race"];
$ic = $_POST["icno"];
$name = $_POST["name"];
$old_ic = $_POST["oldic"];
$add1 = $_POST["add1"];
$add2 = $_POST["add2"];
$add3 = $_POST["add3"];
$postcode = $_POST["postco"];
$town = $_POST["tow"];
$state = $_POST["state"];
$home_con = $_POST["homep"];
$fax_contact = $_POST["fax"];
$hp_con1 = $_POST["mobi1"];
$hp_con2 = $_POST["mobi2"];
$email = $_POST["email"];
if($ic !=''||$email !=''){
//Insert Query of SQL
$query = mysql_query("INSERT INTO customer_info(cust_gender, cust_race, cust_ic,
cust_name, cust_old_ic, cust_add1, cust_add2, cust_add3, cust_postcode,
cust_town, cust_state, cust_home_con, cust_fax_contact, cust_hp_contact1,
cust_hp_contact2, cust_email)
VALUES ('$gender', '$race', '$ic' , '$name', '$old_ic', '$add1', '$add2',
'$add3', '$postcode', '$town', '$state', '$home_con', '$fax_contact',
'$hp_con1', '$hp_con2', '$email')");
echo "<br/><br/><span>Data Inserted successfully...!!</span>";
}
else{
echo "<p>Insertion Failed <br/> Some Fields are Blank....!!</p>";
}
}
mysql_close($connection); // Closing Connection with Server
Hi guys, I want to ask about the database connection, is it my code wrong somewhere?
Because I cant found any error in the code.
I click button register should come over this page to store the data.
when I come to this page display all blank.
I try to change the database name also no response.
I hope you guys can help me.
Thanks.
It should be:
$connection = mysql_connect("localhost", "root", ""); //empty the third parameter. If you have password then insert that in your third parameter
Paste this code inside your if condition so that it will return error from your sql query.
if (!$query) {
die('Invalid query: ' . mysql_error());
}
Try to use the PDO extension instead of mysql & mysqli function. The mysql_* functions are no longer maintained and community has begun the deprecation process. Instead you should learn about prepared statements and use either PDO or MySQLi there are lots of benefits of using PDO over mysqli.
Add the above code
if($ic !=''||$email !=''){
$query = mysql_query("your query");
if (!$query) {
die('Invalid query: ' . mysql_error());
} else {
echo "<br/><br/><span>Data Inserted successfully...!!</span>";
}
}

PHP won't send the data to my mysql database

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

Categories