简体   繁体   中英

How to insert a URL into MySQL database using PHP?

I have a form that submits information into a database. The form includes 3 inputs - a name, a description, and a URL. All three work fine and submit the data into the database, but the URL input only works if the text that is entered DOES NOT include http:// which is not what I want. I NEED it to include the http://

Currently, if I submit the form without the http:// it goes through fine, but if it does include the http:// I get a 406 not acceptable error.

I've read some articles about mysqli_real_escape_string but I haven't had any luck getting it to work. Currently I have the following:

$dbh = new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$code_name = filter_var($_POST['code_name'], FILTER_SANITIZE_STRING);
$code_desc = filter_var($_POST['code_desc'], FILTER_SANITIZE_STRING);
$code_dest = filter_var($_POST['code_dest'], FILTER_SANITIZE_STRING);

$stmt = $dbh->prepare("INSERT INTO qr_codes (code_name, code_desc, code_dest ) VALUES (:code_name, :code_desc, :code_dest )");

$stmt->bindParam(':code_name', $code_name, PDO::PARAM_STR);
$stmt->bindParam(':code_desc', $code_desc, PDO::PARAM_STR, 40);
$stmt->bindParam(':code_dest', $code_dest, PDO::PARAM_STR, 40);

$stmt->execute();

Here is the form:

<form id="newQR" method="post" action="create-qr-code.php" onSubmit="return validateForm();">
    <ul class="new-qr-form">
        <li><label>Name</label><br><input id="code_name" name="code_name" type="text" class="form-control" ></li>
        <li><label>Description</label><br><input id="code_desc" name="code_desc" type="text" class="form-control" ></li>
        <li><label>Destination</label><br><input id="code_dest" name="code_dest" type="text" class="form-control" ></li>
        <li class="img-src-preview"><label>Preview Source</label><br><input value="test" id="code_img_src" name="code_img_src" type="text" class="form-control" ></li>
    </ul>
</form>

Any ideas on why it won't allow a URL?

A simple workaround would be to just remove the http:// onSubmit in validateForm() . Or you can encode it in some way, for example with encodeURIComponent().

$url= filter_var($_POST['url'], FILTER_SANITIZE_URL);

为您的URL使用FILTER_SANITIZE_URL-Constant

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