PHP - Compare exploded word with mysql varchar in PHP - php

How can I compare exploded word with mysql varchar in PHP?
This code produce what i want but it also give this error
veranderenwachtwoordjij
Fatal error: Call to a member function fetch_assoc() on a non-object......
$word = "Also, to be safe, change your password regularly... you don't have to be obsessive about it: every three hours or so should be enough. And because erring on the side of caution is always a good idea, fake your own suicide and change your identity at least once a year.";
$pieces = explode(" ", $word);
$x = 0;
while($x < word_count($word)) { // word count function returns int (51)
$aPiece = $pieces[$x]; // change $pieces[$x] to 'you' and then it works
$result = $conn->query("SELECT * FROM dict WHERE english='$aPiece'");
$z = 0;
while($z < $num_result) // $num_result returns amount of rows in database
{
$row = $result->fetch_assoc(); //error line is here
echo stripslashes($row['dutch']);
$z++;
}
$x++;
}

I guess the problem comes from the don't in your test sentence : you forgot to escape quotes with a function like mysql_real_escape_string.
For example :
$aPiece = mysql_real_escape_string($pieces[$x]);
$result = $conn->query("SELECT * FROM dict WHERE english='$aPiece'");

I think
$row = $result2->fetch_assoc();
should be
$row = $result->fetch_assoc();
since you don't seem to have a $result anywhere.

$result2 in $result2->fetch_assoc(); is not the correct variable, it should be
$result->fetch_assoc();
by the way you have to delete the punctuation marks in order to find the words in your database (I think) one of your first lines should (before the explode) be similar to this:
$words = strtr($words, ',.:!','');

Related

Select MySQL column/row with comma separated values

Suppose I have the following table information
+-------------+---------------+
+ id + letters +
+-------------+---------------+
+ 1 + a, b, c, d, e +
+-------------+---------------+
I am trying to capture the values of the column and store them in variables:
$result = mysql_query("SELECT letters FROM tbl WHERE id=1");
while ($data = mysql_fetch_array($result)) {
// Declare captured db variables
$letter1 = ** what comes here? **;
$letter2 = ** what comes here? **;
}
You can try this way:
$result = mysql_query("SELECT letters FROM tbl WHERE id=1");
$letters = explode(',',mysql_fetch_array($result));
Now you can access any letter using an array, like this $letters[0]; //a.
Instead of having
$letter1
$letter2
I would make an' array with explode.
$letter = explode(',', $data['letters']);
That way you can acccess your letters with a simple $letter[0] or $letter[1]
Now the above code works from the assumption that you only run through the while loop ONCE.
If you run through the while loop more than once, I'd do it like this:
$letter[] = explode(',', $data['letters']);
which is accessed by $letter[0][0] - The first [] being the instance of number when it was fetched, the second [] being the letter you want to fetch.
Another thing
Mysql is outdated / not gonna be used / very unsecure so I would advice you to find another alternative to mysql, such as mysqli or PDO - It is better to use these while you are learning because that way you avoid getting stuck with bad routines.
How about this?
$result = mysql_query("SELECT letters FROM tbl WHERE id=1");
while ($data = mysql_fetch_array($result)) {
// Declare captured db variables
/* list($letter1,$letter2,$letter3,$letter4,$letter5) = explode(',' , $data['letters']);
*/
$letters = array();
// letters array will have the exploded letters
$letters = explode(',' , $data['letters']);
}
Your question is unclear. Please provide more details for a better answer :)

PHP and MySQL string comparison failing

Okay, so I'm having a pretty annoying little problem with my php code. Basically I pull two variables from two seperate sources. One's a cookie and the other is from a MySQL database.
$data = explode("|", $_COOKIE['login']);
$sql = "SELECT session_id FROM users WHERE username='user1'";
$result = $data->query($sql);
$row = $result->fetch_assoc();
$test1 = $data[0];
$test2 = $row['session_id'];
If($test1 == $test2) {
// Do some stuff
}
else {
// Don't do some stuff
}
The actual string is:
x6vkYu6Ep^lm(1Rdm)5Gj5Hj7ilL6FsDL88JC#n#iTyBUqYgJ48#9Ow%*2ZdGs1rA8bc)JoCD7dywcZgg7soV0D#!DpR^pjQwF#QpBt#HRKe$JEtQ*3LhFXsjmkzWNpt
The string is randomly generated before being stored from the following character set:
1234567890!##$%^&*()abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
for($i = 0; $i < 128; $i++) {
$string .= $char_set[rand(0, strlen($char_set)-1)];
}
$sql = "UPDATE users SET session_id='$string' WHERE user='user1'";
$data->query($sql);
setcookie('login', $string . "|" . $username);
If I just set the two variables equal to the above string and evaluate, it works out just fine. Also, if I echo both $data[0] and $row['session_id'] the entire string will display, and they look indentical.
The if() statement will work if I use basic strings, like a number, or basic word, so I'm guessing it's due to special characters, but I don't know where in the proccess it goes wrong. As I said, if I set two variables to that string value, it evaluates, but when I pull from MySQL and the cookie, despite that both strings look the same, it won't evaluate.
Any thoughts?

possible limitation of implode function in PHP

I have the following code that is not returning as I expected. I was hoping the final result would be a string:
$organizers = array_unique($organizers); // this returns correctly
$organizers = implode(', ', $organizers); // this returns nothing
var_dump($organizers); // no data appears here
exit;
The array_unique() function is returning data correctly and I can see the array it returns. To start, the $organizers array is a simple 1-D array of strings that all have small lengths under 20 chars. I think the issue might be that $organizers is more than 10,000 indices long. Are there limitations on the length of an array that can be imploded? Are there work-arounds for that? I cannot find anything in the manual, but I have tested this code thoroughly and I believe the error must be on implode().
I dont' know if there is a limitation, but what comes to my mind is taht you are also transforming an array into a string. This shouldn't be the problem in PHP, but try calling it a different variable for the result of implode?
$organizers = array_unique($organizers); // this returns correctly
$organizers_string = implode(', ', $organizers); // this returns nothing
// This gives it a different space
Edit: And if for some reason implode() is still problematic.
$organizers = array_unique($organizers);
$neworganizers = "";
for($i = 0; $i < sizeof($organizers); $i++)
{
$neworganizers .= $organizers[$i];
if($i != sizeof($organizers) - 1)
{
$neworganizers .= ", ";
}
}
//$neworganizers is now the equivalent of what .implode() should return when called on $organizers
$organizers = array();
$organizers[0] = "value1";
$organizers[1] = "value2";
$organizers[2] = "value3";
$organizers[3] = "value3";
$organizers = array_unique($organizers); // strips out last index
$organizers = implode(', ', $organizers); // returns string of "value1, value2, value3"
echo $organizers;
This seemed to work on writecodeline.com/php/
I've also experienced issues with older php builds when I've tried to explode/implode by a string with special characters in it and they were encapsulated by single quotes. I know it sounds crazy, but the double quotes might be necessary on some servers.
Reference: personal experience doing work on older production servers.
I'd hate to think I'm stating the obvious, but doesn't implode only take a string as an argument? Maybe it should be something more like this...
$organizers = array_unique($organizers);
//I'm guessing what you wanted was an array of arrays?
$neworganizers = array();
for($i = 0; $i < sizeof($organizers); $i++)
{
$neworganizers[$i] = implode(", ", $organizers);
}
print_r($neworganizers);

Check a created string against database, and if found, create new string?

Pretty simple, however, I've yet to find a real straight and appropriate solution;
I've currently got my own function that creates a random string, by running two mt_rand() functions from 1 to maximum integers, then wrapping the results in two dechex() functions, and concatenating them into a single string.
I haven't done the stats on it, but, the chances of two of these strings being the same is pretty low.
However, I'll obviously need a backup solution which is why I want to perform a query against a database, and see if it exists as an entry, and if it does, re-invoke my own function to create a random string, query again, and loop until a non-existent string is found.
I've had a look at a ton of forum threads, and a few SO questions, but have yet to found a concise answer.
Any help would be greatly appreciated, thanks!
$int_affected = 0;
while(!$int_affected) {
/* Set $integer */
mysql_query("INSERT IGNORE INTO table (value) VALUES ({$integer})");
$int_affected = mysql_affected_rows();
}
Is this something you're looking for?
You need a recursive function. Something like:
function makeString() {
// Create our random string
$string = "";
$characters = array('a', 'b', 'c', 'd');
for ($i = 0; $i < 4; $i++) {
$string .= $characters[mt_rand(0, 4)];
}
$query = "SELECT COUNT(*)
FROM myTable
WHERE string = '{$string}'";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
if ($row['COUNT(*)'] > 0) { // if it already exists, do it again
$string = makeString();
}
return $string;
}
This isn't the most elegant solution, but it will work:
$result = queryForUnique();
$unique_string = your_described_function();
$how_many_times = 0;
while(in_array($unique_string, $result) !== false){
if($how_many_times > 10){
throw new Exception("Failed to find a unique string! Aborting!");
}
$unique_string = your_described_function();
$how_many_times++;
}
Where queryForUnique($string) is a wrapper for a SELECT statement
Edit:
Took the query out of the loop, it is bad practice to have a SELECT query in a loop.
Might want to review your control structures:
http://php.net/manual/en/language.control-structures.php

PHP mysql query judge and not echo the repeart part

I want to make a php search query. First, I put a sentence and explode every word get $name,Then I put $name make a query to match all the name which is exist in my database. Then echo part $row['name'][$i] has some word repeat.
for example: the sentence is :Marc Gasol is the brother of Pau Gasol and Gasol in my database, so the match words Gasol apearl 2 times. how to echo $row['name'][$i]; and get only one Gasol? thanks,
$query = mysql_query("SELECT * FROM books WHERE name like '$name[0]' OR name like '$name[1]' OR name like '$name[2]' OR name like '$name[3]' ");
$i = 0;
while($row = mysql_fetch_array($query)) {
echo $row['name'][$i];
$i++;
}
$sentence = "Marc Gasol is the brother of Pau Gasol";
$words = preg_split("/\s+/", $sentence);
//this will uniqueify your value set
$uniqueWords = array_keys(array_flip($words));
foreach($uniqueWords as $word){
$parts[] = "name like '%".mysql_real_escape_string($word)."%'";
}
$where = implode(" OR ", $parts);
$query = mysql_query("SELECT * FROM books WHERE $where ");
$i = 0;
while($row = mysql_fetch_array($query)) {
echo $row['name'][$i];
$i++;
}
You could run another quick loop through your array and remove all duplicate words before you proceed to executing your sql query that way you don't search the name twice in the first place. That should work if I am understanding what you are wanting to do.

Categories