How do I resolve this error? - php

Please help me solve this problem:
if($_POST["keyword"]) {
$keyword = $_POST["keyword"];
$keyword = trim($keyword);
$keyword_array = explode(" ",$keyword);
$numberofwords = (integer)count($keyword_array);
require("server.php");
$link = open_koneksi();
$tbl_name = "author";
$query = "SELECT COUNT(*) as num FROM $tbl_name WHERE " ;
for ($x = 0; $x<= $numberofwords; $x++) {
$query .= "author LIKE '%$keyword_array[$x]%'";
if ( $x < $numberofwords ) {
$query .= " AND ";
}
}
echo("<SCRIPT>document.location.href='?p=result';</SCRIPT>");
}
If the code in the program segment is executed, there will be a warning as follows:
Notice: Undefined offset: 1 in C:\xampp\htdocs\bijang\result.php on line 111
Location of faults refer to this code:
$query .= "author LIKE '%$keyword_array[$x]%'";
How do I fix this?

Your problem is probably this:
for ($x = 0; $x<= $numberofwords; $x++) {
##
You are counting indexes 0 till 1, because the previous count() gave you 1. But that's the total number of indexes, the last index is still 0.
Change it into:
for ($x = 0; $x < $numberofwords; $x++) {
#
Better yet, just use an foreach:
foreach ($keyword_array as $x => $kw) {
That counts the indexes in $x implicitly.
You probably still have to change your last entry detection for the AND fillers. (Commonly you first make an array of substrings, then implode() with the filler " AND ".)
YadaYada: Also take care about unfiltered input. Use the database escaping function for text strings. It's heaps easier to use PDO and prepared statements though.

Cause the $keyword_array array don't have the $x key.

turns out, to overcome, just one word:
error_reporting(0);
the question, whether the notice was included as part of the error?

Related

Convert a search query into 1's and 0's and use as a variable

Hello everyone and thanks for the time you will spend on this question.
Problem
I am trying to convert my search query into 1's and 0's to check for a match inside my database.
Basically, I fill my form input with this query: SF12345
The code checks for each chars if it's numeric. If it is, it outputs a 1 if not it outputs a 0. So my code (SO's code :) ) so far will output 0011111. So far, so good:
$s = "SF12345";
for ($i = 0; $i < strlen($s); $i++){
$char = $s[$i];
if (is_numeric($char)) {
echo "1";
} else {
echo "0";
}
}
Question
How do I "implode" or "regroup" all these echo's to use as one variable inside my search query below
$dbConn->query("SELECT * FROM products WHERE code = '".$s.'");
I want it to look like this
$dbConn->query("SELECT * FROM products WHERE code = '0011111'");
If anyone has any idea on how to approach or solve this issue, you'll make one (very) happy man.
If it is important to know why I want to convert it to 1's and 0's I'll be glad to explain.
Thank you very much, all help is much appreciated.
You could append to a string in PHP with the concatenating assignment operator .=. (See https://www.php.net/manual/en/language.operators.string.php for more information). Then you could do this:
$s = "SF12345";
$output = ""; // This will store the result.
for ($i = 0;$i < strlen($s);$i++)
{
$char = $s[$i];
if (is_numeric($char))
{
$output .= "1";
}
else
{
$output .= "0";
}
}

PHP Nested for loops

I basically want to scan a load of comments for illegal words and then replace those illegal words with a clean version.
I have two arrays, one array has all the comments to check, the other array has all of the illegal words to look for.
The first for loop gets the comments, the nested for loop then scans the comments for each of the illegal words and replaces them. The thing is though - it doesn't actually seem to work. Could you please advise if it is a problem with my loop structure, or the actual update logic?
$numComments = count($commentsToCheck);
$numIllegalWords = count($illegalWords);
for($i = 0; $i <= $numComments; $i++)
{
$message = $commentsToCheck[$i]['message'];
$commentId = $commentsToCheck[$i]['id'];
//error_log($message.'-'.$commentId);
for($j = 0; $j <= $numIllegalWords; $j++)
{
//Get word to replace with
$word = $illegalWords[$j]['word'];
//error_log($word);
$length = strlen($word);
$first = substr($word,0);
$last = substr($word,-1);
$starLength = $length - 2;
$replacement = $first.str_repeat('*',$starLength).$last;
$newMessage = preg_replace('/\b'.$word.'\b/i', $replacement, $message);
//Update the comment
$sql = "UPDATE ow_base_comment SET message = $newMessage WHERE id = $commentId LIMIT 1";
OW::getDbo()->query($sql);
}
}
Shouldnt your query not be what I placed below, since it wont see now the actual variables in the query. It will technincally just update nothing, cause there is no actual variable set.
$sql = "UPDATE ow_base_comment SET message = '".$newMessage."' WHERE id = '".$commentId."' LIMIT 1";
It's a common error to forget the quotes within PHP.

Can you help me get this PHP explode/array/numrows/etc block working?

Ok, so here's my code:
if ($_GET['send'] === "yes") {
$name = $_POST['msg-to'].", ";
$nameParts = explode(", ", $name);
$recipients = array();
for ($x = 0; $x >= 10; $x++) {
$name_query = mysql_query("SELECT * FROM users WHERE username='".$nameParts[$x]."'");
while($value = mysql_fetch_array($name_query)){ $name_numrows = mysql_num_rows($name_query); }
if ($name_numrows = 1) {
$recipients[$x] = $nameParts[$x];
$msgError .= '<span class="success">'.$nameParts[$x].' is a valid user.</span><br>';
} else {
$msgError .= '<span class="warning">'.$nameParts[$x].' is not a valid user, message did not send.</span><br>';
break;
}
}
}
But when a user enters a username for this message to be sent to, it doesn't seem to work AT ALL. It doesn't echo either of the two error messages, and doesn't return an error. It doesn't do anything.
Any feedback at all would be absolutely wonderful :D
I tried to help in the comments above but I think a more clear explanation is needed so I'm resorting to posting an answers. Your code:
for ($x = 0; $x >= 10; $x++) {
This code block declares $x = 0 as the first part of the statement, this is the initialisation.
The second part $x >= 10 is the condition. It states that while $x is greater than or equal to 10 you want to execute an iteration of the loop.
The final part $x++ is the afterthought. It states that on each successful iteration of the loop you want to increment the value of $x.
Because you initialise $x to be 0 and then set the condition that it has to be greater than or equal to 10 >= 10 the condition will fail first time, every time. 0 can't be great than or equal to 10. I imagine what you probably want for your condition is something like while $x is less than or equal to 10 $x <= 10.

error using compare code

If i've database my_table (id,word) as following
and i've some posted text called $name then i want to know if $name have any word like words i've stored in my database my_table (id,word)
so i'm using this code
$name = "Hello lovely world"; // no bad words
$sql = "SELECT * FROM my_table";
$result = mysql_query($sql);
$commentArray = explode(" ", $name);
$counter = count($commentArray);
$check = 0;
while ($row = mysql_fetch_assoc($result)) {
for ($i == 0; $i < $counter; $i++) {
if (strcasecmp($commentArray[$i], $row['word'])) {
$check = 1;
}
}
}
if ($check == 1) {
echo "banned";
exit;
}
else {
echo "passed";
}
however it always results in echo "banned"; even if i $name is clear of any bad words i've stored in my_table so there might be something wrong here !
anyhelp
strcasecmp returns 0 when it matches (PHP manual), so you should edit your code:
if (strcasecmp($commentArray[$i], $row['word']) == 0)
Furthermore, you have a syntax error in your for loop. It should be for ($i = 0; ...
You have a syntax error.
for ($i = 0...
And not
for ($i == 0...
Also, you should indent your code properly, it looks better and it'll help you later on.
The thing is strcasecmp returns 0 if the strings are equal. You ought to change it to if (strcasecmp($var1, $var2) == 0).
As a starting point, I'd suggest storing only lowercased words in the table, lowercasing the input text first, and then replacing the whole strcasecmp loop with an in_array($row['word'], $commentArray);. And break; after the first match.
But this entire approach doesn't scale - you're selecting all the entries in the table. If your table grows beyond a certain size, that will be a serious bottleneck and you'll need to look into matching on the DB side.

PHP variable additions

Hey does anyone know a reason why this is not working? its not calculating any of the additions and just entering 0 into the database. Any help would be great, thank you!.
$member_id = //users member id in database//
$track = //the track results being updated//
$engine = //the engine id from the members table in database//
$engine_points_system = array();
$engine_points_system["qualpos1"] = 30;
$engine_points_system["qualpos2"] = 20;
$engine_points_system["qualpos3"] = 18;
$engine_points_system["qualpos4"] = 17;
$engine_points_system["qualpos5"] = 16;
$enginepoints = 0;
$qualifyingpoints = 0;
$results_query = mysql_query("SELECT pos_1, pos_2, pos_3, pos_4, pos_5
from engine_qualifying_results WHERE track_id = '$track'")
or die ("Failed to update" . mysql_error());
$row = mysql_fetch_array($results_query);
$enginequalifying = array();
for ($i = 1; $i <= 5; $i++) {
$enginequalifying["pos$i"] = $row['pos_$i'];
}
for($i = 1; $i <=5; $i++) {
if($engine == $enginequalifying["pos$i"]){
$enginepoints += $engine_points_system["qualpos$i"];
$qualifyingpoints += $engine_points_system["qualpos$i"];
}
}
$results_query = mysql_query("INSERT INTO member_results (member_id, engine_points)
VALUES ('$member_id', $enginepoints')")
or die ("Failed to update" . mysql_error());
$enginequalifying["pos$i"] = $row['pos_$i'];
In this line you have 'pos_$i'. This is the literal string 'pos_$i'. You should use "pos_$i" instead.
$enginequalifying["pos$i"] = $row["pos_$i"];
UPDATE:
In your code $enginequalifying is redundant, and not needed. You can just use $row in its place.
for($i = 1; $i <=5; $i++){
if($engine == $row["pos_$i"]){
$enginepoints += $engine_points_system["qualpos$i"];
$qualifyingpoints += $engine_points_system["qualpos$i"];
}
}
Also, as #ax. points out, you have an extra ' (or a missing ') in your INSERT.
$results_query = mysql_query("INSERT INTO member_results (member_id, engine_points)
VALUES ('$member_id', '$enginepoints')")
or die ("Failed to update" . mysql_error());
Look at this code:
<?php
$i = 5;
print "i is $i";
print "\n";
print 'i is $i';
?>
You'd expect it to print:
i is 5
i is 5
But instead, it will print:
i is 5
i is $i
This happens because when the string is wrapped in single quotes, $i is not evaluated. It is just the string $i.
To fix the code, try replacing this line:
$enginequalifying["pos$i"] = $row['pos_$i'];
With this line:
$enginequalifying["pos$i"] = $row["pos_$i"];
Quotes make a difference.
And by the way, ESCAPE YOUR SQL!!!. Please?
Not an answer, but too ugly to put into a comment: You could bypass the entire loop to build the enginequalifying array by simply doing:
SELECT pos_1 AS pos1, pos_2 AS pos2, etc...
for your query, then simply having:
$enginequalifying = mysql_fetch_assoc($result);
It's a waste of CPU cycles to have PHP fetch/rename database fields for you when a simple as alias in the original query string can accomplish the exact same thing.
And incidentally, this will also remove the string-quoting error you've got that Rocket pointed out in his answer.
I dont think it is possible to say without knowing what you have in your database.
But I can tell you that you have a syntax error in the last SQL query ($enginepoints ends with a quote).

Categories