Error when saving to MySQL when field contains ' character - php

I have a form with PHP that saves a variable to a MySQL database. That form worked on a VPS, but when trying it on another VPS it gives an error when trying to write to the database when the field contains a ' character. So the same PHP code works on 1 VPS when the field contains a ' character, but not on the other VPS.
Here it works: http://www.zoekmachineoptimalisatie.us/test.php
and here (it's the other VPS) it gives an error: http://www.onzebruidsfotograaf.nl/test.php
My form:
<?php
$hostname = "localhost"; //host name
$dbname = "xxxxxxxx"; //database name
$username = "xxxxxxxx"; //username you use to login to php my admin
$password = "xxxxxxxx"; //password you use to login
$conn = new MySQLi($hostname, $username, $password, $dbname);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Untitled Document</title>
</head>
<body>
<?php
if (isset($_POST['Submit'])) { //if the submit button is clicked
$title = $_POST['updatetitle'];
$bookid = 1;
$update = "UPDATE test SET Title='$title' WHERE BookID = " . $bookid;
$conn->query($update) or die("Cannot update"); //update or error
}
?>
<?php
$bookid = 1;
$sql = "SELECT * FROM test WHERE BookID = '" . $bookid . "'";
$result = $conn->query($sql) or die(mysql_error());
$query = getenv(QUERY_STRING);
parse_str($query);
?>
<h2>Update Record <?php echo $bookid;?></h2>
<form action="" method="post">
<?php
while ($row = $result->fetch_assoc()) {
?>
<textarea name="updatetitle" cols="100" rows="30"><?php echo $row['Title']; ?></textarea>
<table border="0" cellspacing="10">
<tr>
<td><INPUT TYPE="Submit" VALUE="Update the Record" NAME="Submit"></td>
</tr>
</table>
<?php
}
?>
</form>
<?php
if ($update) { //if the update worked
echo "<b>Update successful!</b>";
}
?>
</body>
</html>

An unescaped quote in your query will produce a syntax error. Instead of building the SQL fully your own, make use of SQL variables for your PHP variables with a Prepared Statement:
if (isset($_POST['Submit'])) { //if the submit button is clicked
$title = $_POST['updatetitle'];
$bookid = 1;
$update = $conn->prepare('UPDATE test SET Title = ? WHERE BookID = ?;');
$update->bind_param('sd', $title, $bookid);
$update->execute();
}
One of your servers has Magic Quotes enabled and the other doesn't. Magic Quotes is now considered undesirable and is deprecated, it automatically escapes input. You should turn off Magic Quotes and use a parameterised query/prepared statement instead - then there is no need to escape anything and it prevents SQL Injection.
Paramterised queries are supported by the MySQLi and PDO APIs.

because the single quote breaks the query statement. In order to prevent from it or from SQL Injection you need to use PDO or MySQLI extension. For more infor, see the article below
How can I prevent SQL injection in PHP?

Related

How do you use php to insert into mysql database?

So i am having trouble connecting or inserting data into my database. i am using a form to gather information that i need. And then i try to insert into my database. i'm not sure what the problem is but i think i having trouble with the connection. i am using two files to try and accomplish this.
addQuite.html file
<!DOCTYPE html>
<html>
<head>
<title>AddQuote</title>
<link href="styles.css" type="text/css" rel="stylesheet" />
</head>
<body>
<h2> Add a Quote <h2>
<form action="index.php" method="get">
<div>
Quote:<br>
<textarea rows="6" cols="60" name="quote" id="quote">
</textarea>
<br>
Author: <input type="text" name="author" id="author"/> <br>
<input class = "input2" type="submit" value="Save Quotation"/>
</div>
</form>
</body>
</html>
And this is my index.php file which is where i am trying to connect and insert into my database
<!DOCTYPE html>
<html>
<head>
<title>Quotes</title>
<link href="styles.css" type="text/css" rel="stylesheet" />
</head>
<body>
<h1> Quotes </h1>
<form action="addQuote.html">
<input class="input1" type="submit" value="Add Quote"/>
</form>
<?php
//connet to server
$db = new PDO("mysql:host=server;dbname=quotes", "root" , "");
//check connections
if($db===false){
die("ERROR: Could not connect. ");
}
//get name and quote
$name = $_GET['author'];
$quote = $_GET['quote'];
//attemp insert query execution
$sql = "INSERT INTO quotations (name, quote, rating ) VALUES
('$name', '$quote', 0)";
?>
</body>
</html>
have a look in following example
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
Your query is never executed, add " $db->exec($sql); " to your code.
<?php
//connet to server
$db = new PDO("mysql:host=server;dbname=quotes", "root" , "");
//check connections
if($db===false){
die("ERROR: Could not connect. ");
}
//get name and quote
$name = $_GET['author'];
$quote = $_GET['quote'];
//attemp insert query execution
$sql = "INSERT INTO quotations (name, quote, rating ) VALUES
('$name', '$quote', 0)";
$db->exec($sql);
?>
To insert data into MySQL with PDO you need to use prepared statements. exec() SHOULD NOT be used for inserting data. SQL query needs to be parameterized and data passed separately.
<?php
//connet to server
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$db = new PDO("mysql:host=server;dbname=quotes;charset=utf8mb4", "root", "", $options);
//attempt insert query execution
$db->prepare('INSERT INTO quotations(name, quote, rating ) VALUES(?,?,0)')
->execute([
$_GET['author'],
$_GET['quote']
]);
?>
You should also enable exceptions in PDO with PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, use utf8mb4 charset, and never use root without password in PHP.

Php page with html form inside execute php code before form is completed

This might be a stupid problem but i'm new to this (this is a homework ^^) and i can't find a solution :)
i have a .php file with an html form plus some php code to execute a query and insert the values from the form in my DB. And it works, but every time the page is loaded the php code is executed and this insert in the DB a "blank" line, because obviously the form was not filled yet. This is the code
<html>
<head>
<meta charset="utf-8">
<meta name="generator" content="AlterVista - Editor HTML"/>
<title></title>
</head>
<body>
<form action="myPage.php" method="post">
ID: <input type="text" name="id" /> <br />
<input type="submit" name="Submit" value="Go" /> <br />
</form>
<?php
$user = "DB";
$password = "";
$host = "";
$database = "my_DB";
$connessione = mysql_connect($host, $user, $password);
#mysql_select_db($database, $connessione) or die( "Unable to select database");
$id = $_REQUEST['id'];
$query = "INSERT INTO myTable (ID) VALUES ('".$id."')";
mysql_close();
?>
</body>
</html>
Is there a way to execute the php code only once the "Go" button on the form is executed?
Try:
if(isset($_POST['Submit'])) {
$user = "DB";
$password = "";
$host = "";
$database = "my_DB";
$connessione = mysql_connect($host, $user, $password);
#mysql_select_db($database, $connessione) or die( "Unable to select database");
$id = $_REQUEST['id'];
$query = "INSERT INTO myTable (ID) VALUES ('".$id."')";
mysql_query($query, $connessione);
mysql_close();
}
PHP will work before the page is rendered. You need to set up a condition to stop the PHP you don't want running until you submit the form.
if(isset($_POST['myform'])) {
// process the form
}else{
// html for form goes here
}
Hope that helps.
Assuming the form points to the script itself, there are numerous options :) Among others:
This first example just checks if a form was posted. If a normal (GET) request is received, it will do nothing, because it will not fall into your if-clause
// your form here
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// your php code
}
And this example checks if a variable with the name 'Submit' has been posted, and if so, if it has the value 'Go' in it. It is a slightly stricter check, but in your current example behaviour is exactly the same (so you can pretty much choose which one you like most ;))
// your form here
if(array_key_exists('Submit', $_POST) && $_POST['Submit'] == 'Go') {
// your php code
}

PHP and MySQL Login Form

Hello on my first post!
Here I am trying to make a very simple login form because in a few weeks I have an assignment where I need to create something similar and I wanted to know the basics first. Now I figured this question might make you slap your head by it's easy solution but I just can't seem to figure it out myself.
So what I tried to do was just put my POST values in a MySQL query, and when a user is found display it in a while loop or else display the a warning but my code only result in an empty space.
I will spare you the details about the index.php because it really is just a POST form.
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="wrapper">
<?php
include "connect.php";
$query = "SELECT * FROM members WHERE username = '".mysql_real_escape_string($_POST['username'])."' AND password = '".mysql_real_escape_string($_POST['password'])."'";
$result = mysql_query($query);
if (mysql_fetch_assoc($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$username = $row['username'];
$password = $row['password'];
?><h3>Username - <?php echo $username; ?></h3><?php
?><h3>Password - <?php echo $password; ?></h3><?php
unset($_POST['username']);
unset($_POST['password']);
} // endwhile
} // endif
else {
?><h3>Wrong Username of Password. Try again.</h3><?php
unset($_POST['username']);
unset($_POST['password']);
}
?>
<input type="button" name="back" value="Back" onclick="location.href='index.php'">
</div>
</body>
</html>
You should avoid using the mysql_* functions as they are deprecated and will not be supported any more! Please consider using PDO instead, as it provides a common way to connect to all types of databases. Mysqli is also an option, but that limits you to just MySQL.
In your code example, I see you're using plaintext passwords. This is considered to be extremely bad practice - it provides an easy way of people who have access to your database to know the passwords of all users of the application. You should consider using a hash of some kind, i.e md5 or sha1 to secure your user's passwords. It is a good idea to add a password salt to the equation to make things a bit harder for hackers to crack.
Here is an example of how your code should look using PDO
// connect.php
$db_host = '127.0.0.1';
$db_user = 'user';
$db_pass = 'pass';
$db_name = 'database_name';
$db = new PDO('mysql:host='.$db_host.';dbname='.$db_name, $db_user, $db_pass);
// login.php
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="wrapper">
<?php
include('connect.php');
// Using prepared statements almost eliminates the possibility of SQL Injection.
$preparedQuery = $db->prepare("SELECT * FROM members WHERE username = :username AND password = :password");
$preparedQuery->bindValue(":username", $_POST['username']);
$preparedQuery->bindValue(":password", sha1($_POST['password']));
$preparedQuery->execute();
// Retrieve the results from the database
$user = $preparedQuery->fetch(PDO::FETCH_ASSOC);
// If there is a user record print the user & pass...
if($user != ""){
$message = "<h3>Username - ".$user['username']."</h3>";
$message .= "<h3>Password - ".$user['password']."</h3>";
// start user session?
} else {
$message = "<h3>Wrong Username of Password. Try again.</h3>";
unset( $_POST[ 'username' ] );
unset( $_POST[ 'password' ] );
}
?>
<?php echo $message; ?>
<input type="button" name="back" value="Back" onclick="location.href='index.php'">
</div>
</body>
</html>
you need to use mysql_num_rows(), Try this,
if (mysql_num_rows($result) > 0) {
instead of
if (mysql_fetch_assoc($result) > 0) {
NOTE: Use mysqli_* functions or PDO instead of mysql_* functions(deprecated)

MySQLi mysqli fech array assoc replacement NO working

here is what I want but cannot make it work with the new MySQLi just because my host does not have all new php etc...
But there must be some kind of solution or thats all MYSQLI can do ?
Please dont talk about PDO because even the ugly name sounds like PEDO and I am only interested in MySQLI and a solution for this simple thing. Please dont change the structure of my script. The question is only is if there is something to make it work with MySQL or if I maybe switch back to MySQL procedure instead of statements
<?php
$sql = new mysqli('localhost','user','pass','db');
$who = $_GET['user'];
$query = $sql->prepare("SELECT * FROM profiles WHERE user=?");
$query->bind_param("s",$who);
$result = $query->execute();
while($row = $result->fetch_array(MYSQLI_ASSOC)) // << HERE IS THE PROBLEM //
// I GET ERROR Fatal error: Call to a member function fetch_array() on a non-object in ... //
"" but there must be some way to make it work like we do with while($row = mysqli_fetch_array($sql)) //
{
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>title</title>
</head>
<body>
CUSTOM HTML FOR A NICE DESIGN I WANT TO KEEP THE SAME DESIGN LAYOUT ETC...
HELLO <?php echo "$row[USERNAME]"; ?>
YOUR INFO IS <?php echo "$row[JUST_SOME_INFO]"; ?>
</body>
</html>
<?php
}
?>
Here is your solution
You don't have to use fetch_array() but use fetch()
also you will have to bind result using bind_result before fetch
$query->execute();
$query->bind_result($col1);
while($row = $query->fetch()){
printf("%s \n", $col1);
}
You can use $col1 directly also, no need to use it with printf()
My working example according to my db is given below if you want more assistance,
$sql = new mysqli('localhost','user','pass','dbname');
$who = 'php';
$query = $sql->prepare("SELECT * FROM job WHERE skill=?");
$query->bind_param("s",$who);
$query->execute();
$query->bind_result($col1);
while($row = $query->fetch()){
printf("%s \n", $col1);
}
Comment this string:
$result = $query->get_result();
you don't need this.
Try this one.
<?php
$sql = new mysqli('localhost', 'user', 'pass', 'db');
$who = $_GET['user'];
$query = $sql->prepare("SELECT * FROM profiles WHERE user=?");
$query->bind_param("s", $who);
$result = $query->execute() or die($query->error);
while ($row = $result->fetch_array()) {
$username = $row[USERNAME];
$info = $row[JUST_SOME_INFO];
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>title</title>
</head>
<body>
CUSTOM HTML FOR A NICE DESIGN I WANT TO KEEP THE SAME DESIGN LAYOUT ETC...
HELLO <?php echo $username; ?>
YOUR INFO IS <?php echo $info; ?>
</body>
</html>
This is what happens when you start copying and pasting php together without knowing what it means.
the solution here is:
create a class for $sql or declare $sql a global imediately after calling the variable.
try
global $sql;
but if you actually want to fix the problem(by making your $sql variable an object)
try
$sql = array();
$sql['host'] = 'host';
$sql['user'] = 'user';
$sql['pass'] = 'password';
$sql['db'] = 'database';
global $sql;
$db = new mysqli($sql);
Now when you wanna do something with the db connection.
$db->action();
this is just the basics and probably won't work. you probably should instead read more on php/mysqli before attempting to write your own classes.

MySQL server version issue

i building simple WebService for my web app which contain only two php files connecttodatabase.php contain the code of mysql connection and index.php contain the code of my webService but i got sql 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 'desc, cat, price FROM itmes' at line 3
connecttodatabase.php
<?php
$requesturi = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$pos = strpos($requesturi, "localhost:99/self/index.php");
$hostname = "localhost";
$database = "self";
$username = "root";
$password = "";
$self = mysql_pconnect($hostname, $username, $password) or trigger_error(mysql_error(),E_USER_ERROR);
index.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<?php
//get data
require_once('connecttodatabase.php');
mysql_select_db($database, $self);
//build query
$query =
"SELECT
name,
desc,
cat,
price
FROM itmes";
$rsPackages = mysql_query($query, $self) or
die(mysql_error());
$arRows = array();
while ($row_rsPackages = mysql_fetch_assoc($rsPackages)) {
array_push($arRows, $row_rsPackages);
}
header('Content-type: application/json');
echo json_encode($arRows);
?>
</body>
</html>
It is because you used command DESC in selection, which throws an Exception. Use special symbols to prevent these problems:
`something`
So your code will have this form:
$query =
"SELECT
`name`,
`desc`,
`cat`,
`price`
FROM `itmes`";
and it should be working.

Categories