Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am following a project for creating spell checker. However, rather than using regular mysql, i decided to go with PDO. So i converted code to PDO. I am stuck at one point and not sure why i can't call PDO inside any function even after declaring global variable. What i am doing wrong?
Purpose: I have loaded 100k+ words in a table and want to find similar words by searching one word.
<?php
include "db.inc.php";
function spellcheck($word){
global $db;
$output = array();
$word = $db->quote($word);
$words = $db->prepare("SELECT words FROM english WHERE SUBSTRING(word, 0, 1) = '.substr ($word, 1, 2)'");
$words->execute();
while (($words_row = $words->fetch(PDO::FETCH_ASSOC)) !== false){
echo $words_row['word'];
}
}
if (isset($_GET["word"]) && trim($_GET["word"]) !== null){
$word = $_GET["word"];
$spellcheck = spellcheck($word);
}
?>
<form action="" method="GET">
Please type word to check: <input type="text" name="word">
<input type="submit" value="Check">
</form>
Try the following:
function spellcheck($word){
$db = new PDO ("mysql:host=localhost;dbname=splcheck", "root", "");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$query = "SELECT words FROM english WHERE SUBSTRING(word, 0, 1) = :word";
$stmt = $db->prepare($query);
$stmt->execute(array(':word'=> substr ($word, 1, 2)));
$output = array();
while ($words_row = $stmt->fetch(PDO::FETCH_ASSOC)){
$output[] = $words_row['words'];
}
return $output;
}
Don't use global, pass the connection as argument instead
Make sure you prepare your query properly
Your function was not returning the output
Remove !== false from the while loop its redudant
Avoid typos you forgot s on $words_row['words'];
Using like statement:
$query = "SELECT `words` FROM english WHERE `word` = LIKE :word";
$stmt = $db->prepare($query);
$stmt->execute(array(':word'=>'%'.$word.'%'));
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I have a mySQLi prepared statement and a function I want to pass it to to check to see if the input meets the right format before executing it. I have determined in my actual code that if I move the $stmt->execute() statement just outside of the function that it works, but inside the function it does not. I know that an old school concatenated SQL string can be passed like this, but what is the right way to handle this with prepared statements?
function validateForm($stmt, $inputType){
// A bunch of stuff here to validate for $inputType.
$stmt->execute();
}
$editSQL = "UPDATE mytable SET input1 = ?, input2 = ?, input3 = ? WHERE thisID = ?";
$stmt = $conn->prepare($editSQL);
$stmt->bind_param('sibi', $input1, $input2, $input3, $thisID);
$input1 = $vPara[1][5];
$input2 = $vPara[2][5];
$input3 = $vPara[3][5];
$thisID = $_SESSION['thisID'];
validateForm($stmt, $inputType);
The specific error I get is:
Fatal error: Call to a member function execute() on a non-object
I don't see why it could potentially not work.
You mentioned that if you use execute outside of this function it works. So leave it the way it works because That's recommended due to Single responsibility principle.
Your validator should not be responsible for executing statements but
only for what its name says = validation.
The only thing that validator should do is to return true or false
and upon that decision, you should make execution or not
so change your code to the following:
<?php
function isFormValid($inputType)
{
// A bunch of stuff here to validate for $inputType.
if (//test cases) {
$validationResult = true;
} else {
$validationResult = false;
}
return $validationResult;
}
$editSQL = "UPDATE mytable SET input1 = ?, input2 = ?, input3 = ? WHERE thisID = ?";
$stmt = $conn->prepare($editSQL);
$stmt->bind_param('sibi', $input1, $input2, $input3, $thisID);
$input1 = $vPara[1][5];
$input2 = $vPara[2][5];
$input3 = $vPara[3][5];
$thisID = $_SESSION['thisID'];
if(isFormValid($inputType)) {
$stmt->execute();
} else {
//do error processing echo, trow exception etc
}
?>
Note that I changed the validator name, so now it really expresses what it does, instead of being called validateForm but actually doing also a statement execution.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$follow = strip_tags($_POST["follow"]);
$follow = addslashes($follow);
$follow = mysqli_real_escape_string($conn, $follow);
$sesid = $_SESSION["id"];
$rowid = $row['id'];
$followers = $conn->query("INSERT INTO followers (forid, fromid) VALUES ('$rowid', '$sesid'");
echo "<h3><center>Sucessfully followed!</center></h3>";
}
It doesn't seem to work. It doesn't throw any errors. I'm a new(er) PHP developer. Thank you!
STOP this madness... Do not insert values into a query, that's how bad things happen.
Also, add some error checking here and there, it's impossible to know what's wrong with the piece of code (or is it?):
Try something more like this:
$conn = new mysqli('localhost', 'root', 'password', 'db_name');
if ($conn->connect_errno) {
throw new Exception('Connection Error' . $conn->connect_err);
}
Now let's deal with the post data:
if(isset($_POST)) {
$follow = $_POST["follow"];
$sesid = $_SESSION["id"];
$rowid = $row['id']; // don't know where this is coming from
if($stmt = $conn->prepare("INSERT INTO followers (forid, fromid) VALUES (?, ?)") {
$stmt->bind_param('si', $follow, $sesid);
if(!$stmt->execute()) {
throw new Exception('Error! Could not execute query.');
}
$stmt->close();
} else {
throw new Exception('Could not prepare query!');
}
} else {
// Add a error checking here
throw new Exception('No post data');
}
Prepared statements will help you avoid anyone trying to insert undesired content into your query (SQL injection).
The way it works,
Prepare the query ($conn->prepare())
Note here that there are simple ? where the values would otherwise be. That's for our next step.
Bind the parameters of your query with $stmt->bind_param(). This will tell PHP where each value should go, starting at the second parameter position.
The documentation for the bind_param function: bool mysqli_stmt::bind_param ( string $types , mixed &$var1 [, mixed &$... ] )
A little explanation for the first param:
s - stands for string (the $follow, I assume is a string)
i - stands for integer. The session ID
Then, finally, execute the query ($stmt->execute()). That will do the hard work of adding the values to your database.
Explicitly close the connection to your database ($conn->close());
Read more on PHP's official documentation.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am trying to build a shopping cart using PHP, I get a list of IDs from the products added to the basket, I then want to query my database with these IDS using a WHERE IN SQL statement to get the details of the items added to the basket.
At the moment my query just comes back with false.
if(isset($_SESSION["cart"])) {
foreach ($_SESSION["cart"] as $id => $value) {
$ids .= $id . ',';
$count += $value['quantity'];
}
$query = $database->find_item_db($ids);
EDIT I have now changed my function to use the PDO syntax.
function find_item_db($product_code) {
$query = substr($product_code, 0,-1);
$product_codes = explode(",", $query);
$product_code_new = "(".implode("', '", $product_codes).")";
//we need to get product name and price from database.
$sql = "SELECT * FROM `Sweets` WHERE `Sweet_ID` IN :id";
$statement = $this->connection->prepare($sql);
$statement->bindParam(':id', $product_code_new);
$statement->execute();
return $done = $statement->fetchAll();
}
However this is still returning nothing, I get this error in my logs.
/var/www/html/sweetshop/partials/categories-nav.php(32): Database_Functions->find_item_db('1,10,6,23,')\n#2 /var/www/html/sweetshop/category.php(17): include('/var/www/html/s...')\n#3 {main}\n thrown in /var/www/html/sweetshop/classes/class-database-functions.php on line 139, referer: http://localhost/sweetshop/category.php?type=Chocolate
I know my connection works fine as all my other queries work perfectly.
1. Incorrect syntax
If $ids is something like:
$ids = "1,2,3,4,5";
Then the query is:
SELECT * FROM `Sweets` WHERE `Sweet_ID` IN (1,2,3,4,5)
Which is incorrect because each value needs to be wrapped in single quotes:
function find_item_db($product_code){
$query = substr($product_code, 0,-1);
//Wrap each product id
$product_codes = explode("," $product_code);
$product_codes = "'".implode("', '", $product_codes)."'";
//.......
}
That way the query will read:
SELECT * FROM `Sweets` WHERE `Sweet_ID` IN ('1', '2', '3', '4', '5')`
2. Mixing SQL APIs
mysqli_* syntax and PDO syntax are not interchangeable. bind_param() is for PDO, however your query is using mysqli.
When you are using $statement->bind_param(':id', $new);, what are you binding? There is no :id value in the query, and therefore the line is unnecessary as well as incorrect SQL query format!
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I'm trying hard to learn how to create functions, and I don't know what I'm doing wrong here. Could someone explain it to me please?
I'm not using strip_tags(), why it's getting me this error?
I don't need it to return, I just to need to update database if
$xp is bigger than $row['basenumber']
Thank you!
$xp = $row['userxp'];
$lvl = $row['userlevel'];
contXP($xp, $lvl);
function:
function contXP ($xp, $lvl) {
$query = "SELECT
number, basenumber
FROM levels
WHERE number = '$lvl'";
$result = $conn ->query($query);
if (!$result) die ($conn->error);
$rows = $result->num_rows;
while ($row = $result->fetch_array (MYSQLI_ASSOC));
if ($xp >= $row['basenumber'])
{
// up level
$level = "UPDATE users
SET userlevel = userlevel + 1
WHERE idusers = '$iduser';";
$re_level = $conn ->query($level);
if (!$re_level) die ($conn->error);
$re_rows = $re_level->num_rows;
$re_row = $re_level->fetch_array (MYSQLI_ASSOC);
$re_level->close(); //close query
}
$result->close(); //close query
}
result:
Warning: strip_tags() expects parameter 1 to be string, array given in on line 32
strilp_tags() is definitely somewhere in your code to throw the error. Try posting all the codes involved so we can find out where your problem is coming from.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have a Database class which has multiple functions to execute queries. One of them is the simplest of them all:
public function query($query) {
return $this->_link->query($query);
}
$this->_link->query works in other cases, so it should work here. From a file that has an instance of a class, I do this:
function createLineChart() {
$query = "select * from tags";
$result = $db->query($query);
// do something with result
}
createLineChart();
but it breaks on the $result line. The query is also valid, I've testid it. Am I missing something?
Your problem is $db is out of scope of the createLineChart() function. You can either use the global method:
function createLineChart() {
global $db; // <-- make the db var become available
$query = "select * from tags";
$result = $db->query($query);
// do something with result
}
Or pass the $db object to the function as an argument:
function createLineChart($db) {
$query = "select * from tags";
$result = $db->query($query);
// do something with result
}
createLineChart($db);
More info about Variable Scope on the Manual.
function createLineChart() {
var_dump($db);
// this should probably return 'undefined'
global $db;
// so globalize it!
$query = "select * from tags";
$result = $db->query($query);
// do something with result
}
If $db is a class variable, then you need to refer it as:
$result = $this->db->query($query);