Database linking using php - php

I am getting an error in my php code for database linking.I am trying to link my website login page with my database hosted on server.Here is the code
init.php
<?php
define('HOST','##########');
define('USER','##########');
define('PASS','##########');
define('DB','##########');
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
?>
<?php
require "init.php";
$username = $_POST["username"];
$password = $_POST["password"];
$fullname = $_POST["fullname"];
$sex = $_POST["sex"];
$country = $_POST["country"];
$address = $_POST["address"];
$contact = $_POST["contact"];
$email = $_POST["email"];
$dob = $_POST["dob"];
$flag = $_POST["flag"];
$sql = "insert into signup('".$username."','".$password."','".$fullname."','".$sex."','".$country."','".$address."','".$contact."','".$email."','".$dob."','".$flag."');";
if(mysqli_query($con,$sql))
{ echo"<br><h3>One row inserted....</h3>"; }
else
{ echo "Error in insertion...." . mysqli_error($con);
}
?>
ERROR
Error in insertion....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

Your insert query should be like:
$sql = "insert into signup values('".$username."','".$password."','".$fullname."','".$sex."','".$country."','".$address."','".$contact."','".$email."','".$dob."','".$flag."');";

You missed VALUES in insert query. And use bind_param() to bind the values in query instead of directly including.
$sql = "insert into signup VALUES('".$username."','".$password."','".$fullname."','".$sex."','".$country."','".$address."','".$contact."','".$email."','".$dob."','".$flag."');";

Related

Cant insert specific row into the database PHP MySQL JSON

I pulled the json into the php object and started putting data from that object into the database. I have 20 users in json and everyone succeded to go into the database except one which surname is O'Carolan. I think that error is in that single quote, smth about that. I read everything about sql injection and tried everything i found here on stackoverflow with the similar errors and still doesnt work. I tried with the PDO also and prepared statements and still doesnt work. Here I always get an 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 ' 'male')' at line 2. Also, when printing out the users from json it prints them properly and everything is ok there, just that 3rd user O'carolan wont go into to database.
My json is at http://dev.30hills.com/data.json and my code is:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$db = "30hills";
// Create connection
$conn = new mysqli($servername, $username, $password, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$json_string = 'http://dev.30hills.com/data.json';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata, false);
$elementCount = count($obj);
for ($x = 0; $x < $elementCount; $x++) {
$id = $obj[$x]->id;
$firstname = $obj[$x]->firstName;
$surname = $obj[$x]->surname;
//if (preg_match('/'.$special_chars.'/', $surname)){
// $surname = str_replace("'","",$surname);
//}
$age = $obj[$x]->age;
$gender = $obj[$x]->gender;
echo $id;
echo " ";
echo $firstname;
echo " ";
echo $surname;
echo "<br>";
mysqli_query($conn, "INSERT INTO user (`id`, `firstName`, `surname`, `age`, `gender`)
VALUES($id, '$firstname', '" . $surname . "', $age, '$gender')")
or die(mysqli_error($conn));
?>
The answer is that age = null in json wont insert into database, must make that nullable into the table

No Registration but no error too

The Signup page is not registering the details and details are not being saved in table called members and also it's showing no error in the signup page post submit
<?php
include_once 'header.php';
if(isset($_POST["submit"])) {
$mysql_hostname = "localhost";
$mysql_user = "root";
$mysql_password = "root";
$mysql_database = "database";
$prefix = "";
$fname = $_POST['fname'];
$pass = $_POST['pass'];
$user = $_POST['user'];
$lname = $_POST['lname'];
$college = $_POST['college'];
$gender = $_POST['gender'];
$number = $_POST['number'];
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Could not connect database");
mysql_select_db($mysql_database,$bd) or die("Could not select database");
$query=mysql_query("SELECT * FROM members WHERE user='".$user."'");
$numrows=mysql_num_rows($query);
echo"<br><br><br><br><br><br><br>";
if($numrows==0) {
$sql="INSERT INTO members(user, pass, fname, lname, number, gender, college) VALUES('$user', '$pass', '$fname', '$lname', '$number', '$gender', '$college')";
$result=mysql_query($sql);
if($result) {
echo "Success";
} else {
echo "Failure!";
};
} else {
echo"<center>This email is already registered , Please login to Continue</center>";
}
}
?>
The only answer i can suggest you that instead of using MYSQL just use MYSQLI/ PDO because MYSQL is deprecated.
In your current code if you have error reporting on so you will sure not get error message but MYSQL deprecation warning message will be there.
The Signup page is not registering the details and details are not
being saved in table called member and also its showing no error in
the signup page post submit
The table name is called "member" right ? . And your sql query says "members"
$sql="INSERT INTO members(user,pass,fname,lname,number,gender,college) VALUES('$user','$pass','$fname','$lname','$number','$gender','$college')";
hence it will not work. But yeah, important things you need to know, Like ec45 said...
1.mysql_...() is deprecated. Use PDO instead and if you really love the mysql function, use mysqli...()
2.Never ever directly use values gotten from a form in an SQL query as it leaves you vulnerable to SQL injection. Use prepared statements .
3.Please write clean PHP code. Stuff like this is why people abuse PHP . Best regards.
Okay, i tried to quickly write a PDO version of your script . Here it is. Test it and it should work, also check that the correct column names in your databse are represented in your SQL query. Best regards
<?php
//let's ensure we can see all the errors
error_reporting( E_ALL );
ini_set("display_errors",1);
include_once "header.php";
if(isset($_POST["submit"])){
$dsn="mysql:host=localhost;dbname=database";
$user="root";
$password="root";
//this is PDO . Easier, and better.
try{
$db=newPDO($dsn,$user,$password);
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}catch(PDOException $e){
echo " Couldn't connect to the database because of ".$e;
}
//get the values from the form
$fname = $_POST['fname'];
$pass = $_POST['pass'];
$user = $_POST['user'];
$lname = $_POST['lname'];
$college = $_POST['college'];
$gender = $_POST['gender'];
$number = $_POST['number'];
//function to insert user into the database
function createUser($fname,$pass,$user,$lname,$college,$gender,$number){
//first check to ensure its a new user. If its a new user, we carry normal activities else, echo error message
if(checkUser($email)===false){
$sql=" INSERT INTO members(user,pass,fname,lname,number,gender,college) VALUES (?,?,?,?,?,?,?)";
$data=array($user,$pass,$fname,$lname,$number,$gender,$college);
$db->prepare($sql);
$inserted=$db->execute($data);
//if it returns true and its inserted, then show a success message
$output=(($inserted)?"<section style='color:green; font-weight:bold;'> <h4> You were registered succesfully</h4> </section>":" ");
echo $output;
}else{
echo "<section style='color:red; font-weight:bold;'> <h4> Someone's already registered with that name </h4> </section>"
}
}
//helps to check if a user has already been registered
function checkUser($email){
//watch the next few lines. Showcases the prepared statements
$sql="SELECT * FROM members WHERE user = ?";
$data=array($email);
$db->prepare($sql);
$prepared=$db->execute($data);
$result=(($prepared->rowCount() > 0) ? true :false );
return $result;
}
}
?>

User information not getting into MYSQL db

m making this user signup form and linking the user email name and password tot he table in mysql DB, but it's not showing any row in mySQl DB.
Here is the code:
if(isset($_POST['submit']))
{
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$query_input = mysql_query($connect,"INSERT INTO user_basic_info(username,email,password)VALUES('$username','$email','$password')");
if($query_input){
echo "done and dope";
}
else{
echo "no";
}
}
You have a error in your mysql_query function
$query_input = mysql_query("INSERT INTO user_basic_info(username,email,password) VALUES('$username','$email','$password')",$connect);
see http://php.net/manual/en/function.mysql-query.php
BTW please use mysqli
mysqli_query("INSERT INTO user_basic_info(username,email,password)VALUES('$username','‌​$email','$password')‌​",$connect);
Firstly you should try to use MySQLi or PDO (tutorial here)
$connect = mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['submit']))
{
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$query_input = mysqli_query($connect,"INSERT INTO user_basic_info(username,email,password)VALUES('$username','$email','$password')");
if($query_input){
echo "done and dope";
}
else{
echo "no";
}
//close db connection
mysqli_close($connect);
}

PHP INSERT INTO localhost not working

After running a SELECT * FROM users, there is no difference to the table.
$firstName = $_POST["firstName"];
$lastName = $_POST["lastName"];
$dateOfBirth = $_POST["dateOfBirth"];
$gender = $_POST["gender"];
$fitnessLevel = $_POST["fitnessLevel"];
$number = $_POST["number"];
$address = $_POST["address"];
$password = $_POST["password"];
$user = 'root';
$pass = 'root';
$db = 'gymmembers';
$db = new mysqli('localhost',$user,$pass,$db) or die("Error, try again");
mysqli_query($db, "INSERT INTO users(`firstName`,`lastName`,`dateOfBirth`,`gender`,`fitnessLevel`,`number`,`address`,`password`)
VALUES('$firstName','$lastName','$dateOfBirth','$gender','$fitnessLevel','$number','$address','$password')" or die(mysqli_error()));
I can echo any of the variables and they show, so the data from the form is being passed to here.
Thanks :-)
Actually you putted die(mysqli_error()) inside mysqli_query() which is not correct, do like below:-
mysqli_query($db, "INSERT INTO users(`firstName`,`lastName`,`dateOfBirth`,`gender`,`fitnessLevel`,`number`,`address`,`password`)
VALUES('$firstName','$lastName','$dateOfBirth','$gender','$fitnessLevel','$number','$address','$password')") or die(mysqli_error($db));
Note:- add $db in mysqli_error() so that if any error occur you will come to know.

data not inserting I am using php mysql [duplicate]

This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 8 years ago.
<?php
error_reporting(0);
//connection
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "visionci";
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//file properties
//if (isset($_POST['image']))
$file = $_FILES["image"]["tmp_name"];
if (!isset($file))
{//echo "Please Select an Image";
}
else
{ $name = $_POST["name"];
$rollno = $_POST["rollno"];
$address = $_POST["address"];
$duration = $_POST["duration"];
$course=$_POST["course"];
$fname = $_POST["fname"];
$mname = $_POST["mname"];
$image=addslashes(file_get_contents($_FILES["image"]["tmp_name"]));
$image_name= addslashes($_FILES["image"]["name"]);
$image_size= getimagesize($_FILES["image"]["tmp_name"]);
if($image_size==FALSE)
{echo "That's not an Image";}
else
{
$sql = "INSERT INTO insert (rollno,name,image,address,duration,fname,mname,course)VALUES('$rollno','$name','$image','$address','$duration','$fname','$mname','$course')";
if ($conn->query($sql) === TRUE)
{
//$lastid= mysqli_insert_id($conn);
echo "Record Inserted Successfully!";
}
else
{
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
}
Above is my code. I am getting some garbage value followed by an 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 (rollno,name,image,address,duration,fname,mname,course)VALUES('','','ÿØ' at line 1]
Let me know where I am getting problem I am Stuck.
Change your table name from insert. That can't be distinguished from the command insert, and you couldn't select from a table named insert without escaping
INSERT INTO something_else
or
INSERT INTO `insert`
$sql = "INSERT INTO insert (rollno,name,image,address,duration,fname,mname,course)VALUES('$rollno','$name','$image','$address','$duration','$fname','$mname','$course')";
Here you have used a "insert" as a table name. It is a Reserved key word in MySQL so change that name in to another value and try again.

Categories