Can't add LIKE to my SQL query - php

include("config.php");
$page_number = filter_var($_POST["page"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);
if(!is_numeric($page_number)){
header('HTTP/1.1 500 Invalid page number!');
exit();
}
session_start();
$position = (($page_number-1) * $item_per_page);
if(!empty($_SESSION['type'])){
$typesql = $_SESSION['type'];
$results = $mysqli->prepare("SELECT name, location, score, img, id, type FROM artists WHERE type = ? ORDER BY score DESC LIMIT ?, ?");
$results->bind_param("sii", $typesql, $position, $item_per_page);
$results->execute();
$results->bind_result($name, $location, $score, $img, $id, $type);
} else {
$results = $mysqli->prepare("SELECT name, location, score, img, id, type FROM artists ORDER BY score DESC LIMIT ?, ?");
$results->bind_param("ii", $position, $item_per_page);
$results->execute();
$results->bind_result($name, $location, $score, $img, $id, $type);
}
// Le fetch
while($results->fetch()){
//my cards here
}
?>
I'm looking for ultimately hooking my search box to this query which is not working, I've tried to add alter the query to the below for testing purpose:
SELECT name, location, score, img, id, type FROM artists WHERE name LIKE '%etc%' ORDER BY score DESC LIMIT ?, ?
and I do have a name that has "etc" in it but the result I get is:
Call to a member function bind_param() on boolean in
How do I change this query to bind the $_GET result from the searchbox to it, the website is Setch.me

As in this question you can use LIKE with a bound parameter in mysqli:
$param = "%{$_POST['searchphrase']}%";
$stmt = $mysqli->prepare("SELECT name, location, score, img, id, type FROM artists WHERE name LIKE ?");
$stmt->bind_param("s", $param);
$stmt->execute();
$stmt->bind_result($name, $location, $score, $img, $id, $type);

Related

PHP MySQL SELECT Statement with bindparam doesn't work

This is my code:
function getUsers($connection ,$username) {
$sql = "SELECT * FROM users where username = ?";
$stmt = $connection->prepare($sql);
$stmt->bindParam("s", $username, PDO::PARAM_STR);
return $stmt->fetchAll();
}
$voornaam = "dave";
$users = getUsers($connection, $voornaam);
print_r($users);
When I open my webpage, I get an empty Array.
I checked, and there is a user with the username "dave" in my database.
This should work, however, it doesn't...
Anyone knows what I did wrong?
Thanks in advance.
First is, you have to execute it before using fetchAll():
$stmt->execute();
$result = $stmt->fetchAll();
This is the correct way:
$stmt = $connection->prepare('SELECT * FROM users where username = :username');
$stmt->bindParam(':username', $username);
If you want to user ? it will determine the order of ? in bindParam, use it like this:
$sql = "SELECT * FROM users where username = ?";
$stmt = $connection->prepare($sql);
$stmt->bindParam(1, $username, PDO::PARAM_STR);
More example:
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < ? AND colour = ?');
$sth->bindParam(1, $calories, PDO::PARAM_INT);
$sth->bindParam(2, $colour, PDO::PARAM_STR, 12);
Instead of using
$stmt->bindParam("s", $username, PDO::PARAM_STR);
you need to use
$stmt->bindParam(1, $username, PDO::PARAM_STR);
Check this link for details https://www.php.net/manual/en/pdostatement.bindparam
You need to check this Example #2 Execute a prepared statement with question mark placeholders
This is the correct way
$sql = "SELECT * FROM users where username = ?";
$stmt = $conn->prepare($sql);
$stmt->bindParam(1, $username, PDO::PARAM_STR);
$stmt->execute();
return $stmt->fetchAll();

how to get the $id and matched data as result of unique id check?

I am trying to make a unique id check for email and phone. I just don't know how to fetch the result... I mean if something (email or phone) already exists then I want to get the details of which data already exists (found/matched) and in which id (like $mail already exist on $id == 2). I need to know the script thanks.
private function isUserExist($mail, $phone){
$stmt = $this->con->prepare("SELECT id FROM user_data AS t WHERE mail = ? or phone = ?
UNION
SELECT id FROM emp_data AS u WHERE mail = ? or phone = ?");
$stmt->bind_param("ssss", $mail, $phone, $mail, $phone);
$stmt->execute();
$stmt->store_result();
return $stmt->num_rows > 0;
}
more: i am going to use it in update script... so if email or phone is found on the id i am currently updating it won't abort update process but if the id is different it will stop update process. and return which data(mail/phone) is already available.
This is my Update script
public function updateUser($name, $surname, $address, $pin, $mail, $phone, $id, $old_mail){
$stmt = $this->con->prepare("UPDATE `user_data` SET `name` = ?, `surname` = ?, `address` = ?, `pin` = ?, `mail` = ?, `phone` = ? WHERE `user_data`.`id`= ? AND `user_data`.`mail`= ?;");
$stmt->bind_param("ssssssis", $name, $surname, $address, $pin, $mail, $phone, $id, $old_mail);
$stmt->execute();
if (mysqli_affected_rows($this->con) > 0) {
return 1;
}else{
return 2;
}
}
Fetch results into variable and return it if array is not empty.
private function isUserExist($mail, $phone){
$stmt = $this->con->prepare("SELECT id FROM.
user_data AS t WHERE mail = ? or phone = ?
UNION
SELECT id FROM emp_data AS u WHERE mail = ? or phone = ?");
$stmt->bind_param("ssss", $mail, $phone, $mail, $phone);
$stmt->execute();
$stmt->store_result();
$res = $stmt->fetch_all();
if(count($res)===0){
return false;
}
return $res;
}

Transfer a text value from a drop down list into it's respective database ID - sql insertion and php

I'm having trouble converting a drop down list value (:Artist, text) into its respective ID (Artist_ID, num) and inserting it into the event table. Same problem with Venue_ID.
<?php
$artist =
'SELECT Artist_ID
FROM artist
WHERE :Artist = Artist_Name
';
$venue =
'SELECT Venue_ID
FROM venue
WHERE :Venue = Venue_Name
';
$stmt = $pdo->prepare(
'INSERT INTO event(Event_Date, Artist_ID, Venue_ID, Price)
VALUES (:Event_Date, $artist, $venue, :Price)');
$stmt->bindparam('Artist_ID', $_POST[$artist], PDO::PARAM_STR);
$stmt->bindparam('Venue_ID', $_POST[$venue], PDO::PARAM_STR);
$stmt->bindparam('Date', $_POST[':Date'], PDO::PARAM_STR);
$stmt->bindparam('Price', $_POST[':Price'], PDO::PARAM_STR);
$stmt->execute();
$newId = $pdo->lastInsertId();
exit;
?>
This is the code for the drop down list:
<select name='Artist' id=':Artist'>
<?php
$stmt = $mysqli->prepare(
'SELECT Artist_Name
FROM artist
ORDER BY Artist_Name');
$stmt->execute();
$stmt->bind_result($Artist);
$stmt->store_result();
while($stmt->fetch())
echo("<option> {$Artist} </option>");
?>
</select>
The artist and venue tables have text values that are assigned a primary key ID which is stored into the event table with the artists date and price.
Any help would be appreciated, thanks.
try this, select the artist id as well and pass it in your dropdown as the value like this:
<select name='Artist' id=':Artist'>
<?php
$stmt = $mysqli->prepare(
'SELECT Artist_Name, Artist_ID
FROM artist
ORDER BY Artist_Name');
$stmt->execute();
$stmt->bind_result($Artist, $ID);
$stmt->store_result();
while($stmt->fetch())
echo("<option value=\"$ID\"> {$Artist} </option>");
?>
</select>
I think you also need to update the POST elements in your code, but I'm not sure what you're doing with the :Artist type vars in the first part. If you use the id's as the value (as i did here) then the posted value will be the id of the name they chose, you don't need to query it.
<?php
$artist = $_POST['Artist'];
$venue = $_POST['venue'];
$stmt = $pdo->prepare(
'INSERT INTO event(Event_Date, Artist_ID, Venue_ID, Price)
VALUES (:Event_Date, :Artist, :Venue, :Price)');
$stmt->bindparam(':Artist', $artist, PDO::PARAM_STR);
$stmt->bindparam(':Venue', $venue, PDO::PARAM_STR);
$stmt->bindparam(':Event_Date', $_POST['Date'], PDO::PARAM_STR);
$stmt->bindparam(':Price', $_POST['Price'], PDO::PARAM_STR);
$stmt->execute();
$newId = $pdo->lastInsertId();
exit;
?>

Replacing "?" in a string by values from array

I'm trying to replace every "?" in string by values from array. Each "?" is the next value from array.
I was wondering if there is a better way to do the following:
$query = 'SELECT * FROM pages WHERE id = ? AND language = ?';
$values = array('1', 'en');
foreach ($values as $value) {
$query = preg_replace('/\?/', '\''.$value.'\'', $query, 1);
}
echo '<pre>'.print_r($query, true).'</pre>';
Would like to do that with native PHP (not a PDO extension).
Use binding
in PDO
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour');
$sth->bindValue(':calories', $calories, PDO::PARAM_INT);
$sth->bindValue(':colour', $colour, PDO::PARAM_STR);
$sth->execute();
http://php.net/manual/pl/pdostatement.bindvalue.php
in mysqli
$stmt = $mysqli->prepare("INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
$stmt->bind_param('sssd', $code, $language, $official, $percent);
http://www.php.net/manual/en/mysqli-stmt.bind-param.php
if you want to do it in STUPID way you can use loop or recursion
$select = "SELECT * FROM pages WHERE id = ? AND language = ?";
$params = array('param', 'param2');
while(preg_match('/\?/', $select)) $select = str_replace("?", array_shift($params), $select);
but it's stupid
Mysqli and PDO are as native as it gets with PHP.
You can use bind_param from mysqli to accomplish this. Example:
$stmt = $mysqli->prepare("SELECT * FROM pages WHERE id = ? AND language = ?");
$stmt->bind_param('is', 1, "en");
In this case the i and s are referencing the type of the parameter, as seen in this table (available in link):
i corresponding variable has type integer
d corresponding variable has type double
s corresponding variable has type string
b corresponding variable is a blob and will be sent in packets

php mysqli prepared statement

Hey, I have a quick one. Is there any way to include a variable into a prepared query? example:
$sql = "SELECT id, title, author, LEFT(description, 40) AS excerpt,
image_small, image_med, date
FROM posts
ORDER BY id DESC
LIMIT $start, $postsPerPage";
$result = $connect->prepare($sql) or die ('error');
$result->execute();
$result->bind_result($id, $title, $author, $excerpt, $image_small, $image_med, $date);
Thanks!
you want the following:
$start = 1; $postsPerPage = 1;
$sql = "SELECT id, title, author, LEFT(description, 40) AS excerpt,
image_small, image_med, date
FROM posts
ORDER BY id DESC
LIMIT ?, ?";
$stmt = $connect->prepare($sql) or die ('error');
$stmt->bind_param('ii', $start, $postsPerPage);
$stmt->execute();
$stmt->bind_result($id, $title, $author, $excerpt, $image_small, $image_med, $date);
while($stmt->fetch()) {
printf('<h1>%s</h1><p>%s <small> by %s on %s</small></p>',
htmlspecialchars($title),
htmlspecialchars($excerpt),
htmlspecialchars($author),
htmlspecialchars($date)
);
}
this binds both question marks to integer (i) values of $start and $postsPerPage. do NOT use variables directly in prepared statements, because that would defeat the whole purpose of prepared statements (apart from eliminating parsing time)
Use question marks as placeholders in the SQL where you want the value of the variable to be.
Use mysqli_stmt::bind_param to bind values to the placeholders.
If I'm not mistaken you have to use bindParam and replace the variables in your query with a question mark
$sql = "SELECT id, title, author, LEFT(description, 40) AS excerpt,
image_small, image_med, date
FROM posts
ORDER BY id DESC
LIMIT ?, ?";
$result = $connect->prepare($sql) or die ('error');
$result->bindParam(1, $start);
$result->bindParam(2, $postsPerPage);
you can find more examples at http://php.net/manual/en/pdo.prepared-statements.php

Categories