PHP variable not updating in to MYSQl field - php

I have a piece of code which takes the keywords out of a url from a database. The code then updates a field within the database with the keywords. The code gets the keywords from the url successfully and then echo's them out on to the page perfectly.
However when I try and update them in to the database, the field doesn't update. If i swap out the variable $c for a word such as test this works perfectly and so the issue is with the variable $c, however i have tried to do this several different ways but i just can not get the field to update.
$result = mysql_query("SELECT * FROM ip_stats1 WHERE page LIKE 'http://www.google.com/uds/afs?q=%' AND id='44'")
or die(mysql_error());
$row = mysql_fetch_array( $result );
$keyword = $row['page'];
$id = $row['id'];
$a = "$keyword";
$b = substr($a, strpos($a, '=') + 1);
print $b;
$c = substr($b, 0, strpos($b, '$'));
echo "$c";
$result2 = mysql_query("UPDATE ip_stats1 SET string1 = '$c' WHERE id = '44'")
or die(mysql_error());
UPDATE
ok, so if I echo $c i get the keywords, so it would simply be for example something like Dough Maker, so that works perfectly. i have also tried writing it like this.
$test = $c;
and then test returns the same result. Originally this was a loop and i took all of the results fro the database to produce a long list, but in an effort to try and find the error i removed the loop to just return one result.

OK, firstly thanks for all your suggestions, I tried various things and then in the end simply realised that actually this was a silly error. the variable $b holds the information i want and as soon as i inserted this to the database everything worked fine.

Related

PHP variable is not working with WHERE clause

My query is not working when I use the variable in the WHERE clause. I have tried everything. I echo the variable $res, it shows me the perfect value, when I use the variable in the query the query is not fetching anything thus mysqli_num_rows is giving me the zero value, but when I give the value that the variable contains statically the query executes perfectly. I have used the same kind of code many times and it worked perfectly, but now in this part of module it is not working.
Code:
$res = $_GET['res']; // I have tried both post and get
echo $res; //here it echos the value = mahanta
$query = "SELECT * FROM `seller` WHERE `restaurant` = '$res'"; // Here it contains the problem I have tried everything. Note: restaurant name is same as it is in the database $res contains a value and also when I give the value of $res i.e. mahanta in the query it is then working.
$z = mysqli_query($conn, $query);
$row2 = mysqli_fetch_array($z);
echo var_dump($row2); // It is giving me null
$num = mysqli_num_rows($z); // Gives zero
if ($num > 0) {
while ($row2 = mysqli_fetch_array($z)) {
$no = $row2['orders'];
$id = $res . $no;
}
}
else {
echo "none selected";
}
As discussed in the comment. By printing the query var_dump($query), you will get the exact syntax that you are sending to your database to query.
Debugging Tip: You can also test by pasting the var_dump($query) value in your database and you will see the results if your query is okay.
So update your query syntax and print the query will help you.
$query = "SELECT * FROM `seller` WHERE `restaurant` = '$res'";
var_dump($query);
Hope this will help you and for newbies in future, how to test your queries.
Suggestion: Also see how to write a mysql query syntax for better understanding php variables inside mysql query
The problem is the way you're using $res in your query. Use .$res instead. In PHP (native or framework), injecting variables into queries need a proper syntax.

PHP variable is not usable - Script stops when trying to assign/use it

I just came across a bug in my code that I wasn't able to fix for the last few hours. I am querying something from the database and then I am trying to use the results. However, whenever I try to access the content of the query result, the script just stops.
$recordcount = $db->query("SELECT optin_mail FROM games WHERE id = $game_id");
$result = $db->getrec();
echo "This will be executed without a problem";
if (isset ($result) && $result != null) echo $result;
echo "This won't be executed. The script stops in the line above";
I did a lot of testing and found out that everytime I try to assign $result, for example $newVariable = $result; or I try to access the content $content = $result["name"]; it stops. Even echoing it or using print_r($result); will let the script crash instantly.
I really don't know what to do anymore. I checked the query and the result_count is 1. The function getrec() is basically just mysqli_fetch_assoc($queryResult); and works perfectly fine, I am using it multiple times in the same file.
Okay, first of all, it's difficult to say what's wrong without seeing the insides of getrec() method. My guess is that you're trying to echo the wrong type of data. Function mysqli_fetch_assoc returns an array, thus echoing $result won't work.
Try
$recordCount = $db->query(sprintf('SELECT optin_main FROM games WHERE id = %s', $game_id));
$results = $db->getrec();
if ($results ?? null) {
echo $results[0]['optin_main'];
}

PHP Function is only called once in for loop

I am sure that this question has been asked before, but I am unable to come up with the proper keywords (especially in english).
I am using PHP and I am trying to for loop through a parameter of a function. So the function should be called, store the retrieved data in some variables and these variables should then be inserted into a database.
However, the loops only runs once! If I substitute $id with any number it works fine, but only once.
This is a simplified version of my code:
for ($i=0; $i<9; $i++) {
$id = $rows[$i][1];
$values = getDetails($id); // This function (from another file) returns an array
$title = $values["Title"];
$year = $values["Year"];
$query= " INSERT INTO database
VALUES ('','$title','$year')";
$result = $mysqli->query($query);
}
* EDIT This is part of the getDetails function:
function getDetails($id) {
$url = "http://www.something.de/". $id . "/";
$html = file_get_html ( $url );
$title = $html->find('span[itemprop=name]');
$title = explode('>',$title[0]);
$title = explode('</span',$title[1]);
... // This might look weird and is definatly not perfect, but it works :)
$details = array("Title" => $title[0], "Year" => $year[1]);
return $details;
}
* EDIT
WOW! I found the reason ... I had a function within my function which was never used. I just commented it out and my code works just fine. I assume it is not a good idea to so anyways.
I think your $query is wrong.
Change this:
$query= " INSERT INTO database
VALUES ('','$title','$year')";
To something like this:
$query= " INSERT INTO database (field1,field2,field3)
VALUES ('','$title','$year')";
Is your ID field autoincrementing? If so you do not need the "field1" entry at all.
Happy Coding!
I had this problem also.
I could print to a table without a problem the parameters I was feeding into a function in a loop. But the function calls in the loops would only call once.
SOLUTION: Remove the location redirects and the exit(); from the function.
Hope this helps someone else.

UPDATE not updating via script yet variables exist

I have the following code which should result in an UPDATE occuring yet I see no change on the table row. Any clues as to why? Below the code I list what I have tried. I've stared at this code for hours!
if (in_array( $topicid , $allowed )) {
$query = $db->query("SELECT lastpost FROM table_topics WHERE forumid=$forumid AND topicid=$topicid");
$thelpost = $db->fetch_array($query);
$db->free_result($query);
$lastpost = explode("|", $thelpost['lastpost']);
$initialtime = $lastpost[2];
$timerightnow = time();
$db->query("UPDATE table_topics SET lastpost='$timerightnow|$loginname|$initialtime' WHERE topicid=$topicid AND forumid=$forumid");
}
Tried printing the query:
$query = $db->query("UPDATE table_topics SET lastpost='$timerightnow|$loginname|$initialtime' WHERE topicid=$topicid AND forumid=$forumid");
print $query;
which resulted in output of 1 which I figure is true.
Tried echoing out variables and they all have the expected output. $loginname and other variables were set in preceeding code not shown.
Tried running the UPDATE manually through phpmyadmin with preset variables. Worked.
Yes, CSV delimiting is bad. It's a legacy app that needs overhauling in the long term.

How to make loop

This would helps me a lot to understand how does loop works
Let say i've database table my_table (id,words) and here is example of database
INSERT INTO `my_table` VALUES (1,'hello manal');
INSERT INTO `my_table` VALUES (2,'nice manal');
INSERT INTO `my_table` VALUES (3,'pretty manal');
now imagine for 100,000 entries (huge) and i want to replce the word manal to jack and giving me results every line changed one by one
i'll use
$conn = mysql_connect('localhost','USER','PASS') or die(mysql_error());
mysql_select_db('my_table',$conn);
$sql = "SELECT * from my_table";
$result = mysql_query($sql,$conn);
while ($row = mysql_fetch_array($result)){
$old = $row['words'];
$id = $row['id'];
$new="jack";
$new = str_replace("manal", "$new", $old);
echo $new;
}
The loop
by that code it will works all at once which is impossible to my hosting server to apply all so i want to make it as loop ! i mean it will change the 1st database line then gives me the results echo $new; then change the 2nd database line then gives the results echo $new; and so on with no stop till last line.
so my important part is getting the results one by one ~thanks
The problem will be that your output is being buffered which is why you see all the results at the same time (at the end of the execution of the script).
You could add ob_flush(); flush(); within the loop before echo $new; an see if that helps. Regardless, the above example is going to execute pretty quickly so it isn't exactly going to be easily readable!
You better do this replace in the database itself and then you just print it out.
$sql = "UPDATE my_table SET words = REPLACE(words, 'manal', 'jack')";

Categories