Search code examples
phpmysqlmysqlibindparam

Bind Param Error


I'm having a MySQL/MySQLi/PHP Error with my link shortener the error is:

Fatal error: Call to a member function bind_param() on a non-object in
/home/exabit/public_html/9ui/index.php on line 50

here is the problematic line.

$reslove->bind_param("ss",$link, $short_url);

here is the rest of the code

<?php
$data_base = new mysqli ("http://host38.qnop.net/~exab","exab_ml","MKnOz3A]h~aw","exab_ml");
function generateRandomString($length = 3) {
$key = 'abcdefghijklmnopqrstuvwxyz1234567890';
$keyLength = strlen($key);
$string = '';
for ($i = 0; $i < $length; $i++) {
$string .= $key[rand(0, $keyLength - 1)];
}
return $string;
}
if (isset($_GET['title'])) {
$reslove = $data_base->prepare("SELECT * FROM links WHERE title=?");
$reslove->bind_param("s", $_GET['title']);
$reslove->execute();
$goto = $reslove->get_result()->fetch_array();
$goto1 = $goto[1];
header("Location: $goto1");
}
if (isset($_POST['submit'])) {
$short_url = generateRandomString();
if (!preg_match("/^(http|https):/", $_POST['long_url'])) {
$_POST['long_url'] = 'http://'.$_POST['long_url'];
}
$link = $_POST['long_url'];
$reslove = $data_base->prepare("INSERT INTO links VALUES('',?,?)");
$reslove->bind_param("ss",$link, $short_url);
$reslove->execute();
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<center>
<form>
<p style="color:#05ff19;font-family:Tahoma;font-size:16px;text-align:center">Shortened Link: </p><input id=shortenedurl style="background-color:#000;color:#05ff19;font-family:Tahoma;font-size:16px;vertical-align:middle;border:1px solid #05ff19" type="text" value=<?php echo "9ui.co/$short_url";}?>'>
</form>
</center>

The misspelling of resolve has nothing to do with it.
Thanks in advance,
Zack Davies


Solution

  • The error "Call to a member function bind_param() on a non-object" implies that $reslove is not an object, therefore you cannot call a member function (aka a method) on something that is not an object. How can $resolve not be an object? Well, the ->prepare method call on line 49 will return false if an error occurs preparing the SQL statement and, of course, false is a "non-object" so that'll cause the error message you got.

    Looking at line 49, where $resolve gets set, hmmmm that SQL statement looks funny. The syntax for an INSERT command is normally ...

    INSERT INTO table_name (column1,column2,column3,...)
    VALUES (value1,value2,value3,...);
    

    You have left out the (column1,column2,column3,...) which explicitly states the column names and their order. Leaving this out, if it ever does work, is risky and/or fragile because you'd be assuming the columns match your values, which may not always be the case. Much safer to explicitly state the (column1,column2,column3,...).