简体   繁体   中英

special characters replacement in a php to mysql insert script

I am sorry if this has been asked before but I'm not understanding most of the stuff I've found using google. I'm just learning how to do this all so please bear with me.

I've created a working "INSERT" php script to insert data into a mysql 5.x database, it works without problem, however the issue i AM having is if the user puts a word with a ' or " into the fields the script spits back a "Error inserting new record" at the user. I need to know how to make the script automatically replace the ' with a \\' before it tries to insert the information to a database.

What I have at the moment is....

<?php

if (isset($_POST['submitted'])) {

include('../connect/connect-mysql.php');

$Colorist = $_POST['Colorist'];
$Active = $_POST['Active'];

$sqlinsert = "INSERT INTO colorist (Colorist, Active) VALUES ('$Colorist', '$Active')";

if (!mysqli_query($dbcon, $sqlinsert)) {
    die('error inserting new record');
    }//end of nested if statement
$newrecord = "New record added";

} //end of main if


?>
<html>
<head>
</head>
<body>
<form method="post" action="insertcolorist.php">
<input type="hidden" name="submitted" value="true" />
<fieldset>
<legend>New Colorist Data</legend>
<table border="1" width="100%" style="border-collapse: collapse">
<tr><th colspan="2"><font face="Verdana" size="2">Colorist Data</font></th></tr>
<tr><th><font face="Verdana" size="1"><label>Colorist: </label></font></th><td><font size="1" face="Verdana"><input type="text" size="150" name="Colorist" /></font></td></tr>
<tr><th><font face="Verdana" size="1"><label>Is the Colorist Active: </label></font></th><td><font size="1" face="Verdana"><select size="1" name="Active"><option value="">Select...</option><option value="Yes">Yes</option><option value="No">No</option></option></select></font></td></tr>
</table>
</fieldset>
<br>
<input type="submit" value="add new colorist" />
</form>
<?php
echo $newrecord // New record added statement added at the top
?>

There's a mysqli function for cleaning input string. It's as easy as use

$Colorist = mysqli_real_escape_string($_POST['Colorist']);
$Active = mysqli_real_escape_string($_POST['Active']);

This should be enough for the most common problems of this type

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM