How to search a database with the name of a var - php

So, I have this code right here, and all it does is error a... 404???? (Just a glitch, but still. Using remote HTTP access it does not work. It should)
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO $user(Username, Password, Membership)
VALUES ($usn, $psw, $membership)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>

Why wouldn't you try:
$sql = "INSERT INTO " . $user . "(Username, Password, Membership) VALUES (" . $usn . "," . $psw . "," . $membership. ")"

You probably meant to write either:
$sql = "INSERT INTO ".$user."(Username, Password, Membership)
VALUES
('".$usn."', '".$psw."', '".$membership."')";
or
$sql = "INSERT INTO user(Username, Password, Membership)
VALUES
('".$usn."', '".$psw."', '".$membership."')";
Escaping your input and adding a real_escape_string() call would be even better.
So I would write it in a way that the values are escaped as strings and the query handles them as strings:
$sql = "INSERT INTO user(Username, Password, Membership)
VALUES
('".$conn->real_escape_string($usn)."',
'".$conn->real_escape_string($psw)."',
'".$conn->real_escape_string($membership)."'
)";
I hope that helped at least a little.

Related

Insert stored procedure in PHP

I have a simple insert statement to save form details in PHP.
I want to convert this into store procedure.
Below is my current code how
$servername = "localhost";
$username = "aaaaaa";
$password = "ppppp";
$dbname = "xxxx_database";
$sName = $_POST["name"];
$sEmail = $_POST["email"];
$sPhone = $_POST["Number"];
$sInterest = $_POST["interest"];
$Comments = $_POST["Inquiry"];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO ContactForm (Name, Email, PhoneNumber,Interest,Comments) VALUES ('$sName', '$sEmail', '$sPhone','$sInterest', '$Comments')";
if ($conn->query($sql) === TRUE) {
echo "New record created";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
And this is my Store procedure
CREATE DEFINER = `xxx`#`localhost` PROCEDURE `SpInsertContactForm` ( IN `Name` TEXT CHARSET armscii8, IN `Email` TEXT CHARSET armscii8, IN `PhoneNumber` TEXT CHARSET armscii8, IN `Interest` TEXT CHARSET armscii8, IN `Comments` TEXT CHARSET armscii8 ) NOT DETERMINISTIC NO SQL SQL SECURITY DEFINER INSERT INTO ContactForm( Name, Email, PhoneNumber, Interest, Comments )
VALUES (
Name, Email, PhoneNumber, Interest, Comments
)
How can i use this store procedure. I am new to php and mysql need pointer in this.
I use SP as
if (!$mysqli->query("CALL SpInsertContactForm($sName, $sEmail, $sPhone,$sInterest, $Comments)"))
{
echo "CALL failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
This doesn't save anything in DB
you cal use this: $mysqli->query("CALL SpInsertContactForm('<your_namevalue>','<your_emailvalue>','<your_phonevalue>','<your_interestvalue>','<your_commentvalue>')
For more please follow the link:
http://php.net/manual/en/mysqli.quickstart.stored-procedures.php

MySql Insert into.....(error)

I'm getting an insert error when I'm trying to insert data from a form to my database. the error is as follows :
Error: INSERT INTO users (firstname) VALUES ('a')
This is the code:
if ( isset($_POST['submit']) ) {
$registerfirstname = $_POST['firstname'];
$query = "INSERT INTO users (firstname) VALUES ('$registerfirstname')";
if(mysqli_query($conn, $query)){
echo "New user created";
}else{
echo "Error: " .$query. "<br>" . mysqli_error($conn);
}
}
You are making a little mistake here. You have to pass the variable data through the mysqli_real_escape_string() through first. An example would be ,
$registerfirstname = mysqli_real_escape_string($registerfirstname);
And after that you can use it in sql like that. This way it is more sanitized. I hope this will solve your problem.
Firstly, you should use Mysql Workbenck to prepare sql statements. If, The statements properly work on workbench.Paste into the php script.
On php side, you should use mysql_real_escape_string() function before set your variable.
Like;
$registerfirstname = mysql_real_escape_string($_POST['firstname']);
Try this:
// Create connection
$connection = new mysqli('localhost', 'username', 'password', 'dbname');
// Check connection
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
$firstname = "John";
$firstname = mysqli_real_escape_string($firstname);
$sql = "INSERT INTO users (firstname) VALUES ('$firstname')";
if ($connection->query($sql) === TRUE) {
echo "New user created";
} else {
echo "Error: " . $sql . "<br>" . $connection->error;
}
// Close connection
$connection->close();
It should work, but if it doesn't just give us what errors are shown.

Text form can't accept apostrophes

My text forms won't allow single " ' " to occur in the input fields. I get an sql syntax error. Is there any good way to allow single apostrophes to be allowed in my text field?
here's my code
html
<input class='what' type='text' name='one' required>
<textarea name='two' required></textarea>
<input type='submit'>
</form>
My database
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO whatsgood (one, two)
VALUES ('$one', '$two')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
any help would be very appreciated. Thank you!
Use addslashes PHP function (It Quote string with slashes)
$sql = "INSERT INTO whatsgood (one, two) VALUES ('".addslashes($one)."', '".addslashes($two)."')";
Example:
<?php
$str = "Is your name O'Reilly?";
// Outputs: Is your name O\'Reilly?
echo addslashes($str);
?>
You can also use mysqli_real_escape_string (Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection)
$sql = "INSERT INTO whatsgood (one, two) VALUES ('".mysqli_real_escape_string($conn,$one)."', '".mysqli_real_escape_string($conn,$two)."')";
Use prepared statements this is much safer against SQL-Injections than just escaping.
Change this:
$sql = "INSERT INTO whatsgood (one, two)
VALUES ('$one', '$two')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
To this:
$stmt = $conn->prepare("INSERT INTO whatsgood(`one` , `two`) VALUES ( ? , ? )");
$stmt->bind_param("ss", $one , $two);
if($stmt->execute()){
echo "New record created successfully";
}
else{
echo "Error: " . $stmt->error;
}
Use mysqli_real_escape_string during INSERT to escape values.
$sql = "INSERT INTO whatsgood (one, two)
VALUES ('".mysqli_real_escape_string($conn, $one)."', '".mysqli_real_escape_string($conn, $two)."')";

PHP / MySQL: How to return info if record already exists (without update)

I am using the below to insert a new row into a MySQL db.
The query for this is stored in a PHP file (ajax.php) and the input values are passed to this via an Ajax call in jQuery.
Everything works as intended but I would like to return a message to the user if an email is already in the db.
I know how to update a db row using ON DUPLICATE KEY but can someone tell me how I can just check for this and echo something if it exists there already (i.e. without updating it) ?
(email is a single primary key so I only need to check for this column.)
My PHP:
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8");
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$email = $_POST["email"];
$dob = $_POST["dob"];
$sql = "INSERT INTO Users (email, dob) VALUES ('" . $email . "', '" . $dob . "')";
if ($conn->query($sql)){
echo 'DB Update successful';
}else{
echo 'DB Update failed';
}
$conn->close();
You just need a simple SELECT call before inserting.
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8");
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$email = $_POST["email"];
$dob = $_POST["dob"];
$sql = "SELECT email FROM Users WHERE email = " .$email;
$query = $conn->query($sql);
if (mysqli_num_rows($query) > 0){
echo "There exists an user with this email";
}
else {
$sql = "INSERT INTO Users (email, dob) VALUES ('" . $email . "', '" . $dob . "')";
if ($conn->query($sql)) {
echo 'DB Update successful';
}
else {
echo 'DB Update failed';
};
}
$conn->close();
The simple way is just to count the occurances of entries in the table with the same email as you are trying to store. Counting rather than SELECTing means it is quicker and only a count is returned not a complete row that you have to then look at or count the rows in the result.
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8");
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$stmt = $Conn->prepare("Select Count(email) as cnt FROM Users WHERE email = ?");
$stmt->bind_param('s', $_POST["email"]);
$stmt->execute();
$stmt->bind_result($cnt)
$stmt->close();
if ( $Cnt > 0 ) {
// its already there so do whatever you want in this case
} else {
$sql = "INSERT INTO Users (email, dob) VALUES (?,?)";
$stmt = $Conn->prepare($sql);
$stmt->bind_param('ss', $_POST["email"],$_POST["dob"]);
if ($stmt->execute(){
echo 'DB Update successful';
}else{
echo 'DB Update failed';
}
}
$conn->close();

MySQLi insert statement to executing

I am writing a simple code in PHP to test my MySql server by , inserting data to my database server
i am executing the file from the internet
URL of executing : Scores2.php?n=asdad&l=345&s=241
PHP Code:
<?php
$servername = "sql3.freesqldatabase.com";
$username = "MY USERNAME";
$password = "MY PASSWORD";
$dbname = "MY DBNAME";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$name = (string)$_GET['n'];
$score = (int)$_GET['s'];
$level = (int)$_GET['l'];
$sql = "INSERT INTO HighScores (name, score, level)
VALUES ($name, $score, $level)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
When i execute the file , the browser shows this error :
Error: INSERT INTO HighScores (name, score, level) VALUES (asdad, 241, 345)
Unknown column 'asdad' in 'field list'
I checked the Control Panel in phpMyAdmin and executed the same statement but without variables , and it worked
Rows Types :
name : text
score : int(11)
level : int (11)
Learn how to prepare the query it's not that difficult.
You will avoid sql injection and missing quotes
Use num_rows to check if the record is inserted
Use $conn->error if the prepare() call return false.
$name = (string)$_GET['n'];
$score = (int)$_GET['s'];
$level = (int)$_GET['l'];
$sql = "INSERT INTO HighScores (name, score, level)
VALUES (?, ?, ?)";
if ($stmt = $conn ->prepare($sql)) {
$stmt->bind_param("s", $name);
$stmt->bind_param("i", $score);
$stmt->bind_param("i", $level);
$stmt->execute();
if($stmt->num_rows > 0){
echo "New record created successfully";
}else{
echo "no rows affected";
}
$stmt->close();
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn ->close();
$sql = "INSERT INTO HighScores (name, score, level)
VALUES ('$name', '$score', '$level')";
change query like this

Categories