Output variable does not work as expected - php

I am trying to learn PHP, but I am stuck on something. Was wondering if any of you could help me out.
The thing is, I've got a variable like this:
$sql = "SELECT * FROM `settings` WHERE `key` LIKE 'signing_key'";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result)){
$key = $row['value'];
}
mysqli_free_result($result);
}
}
$Settings['SIGNING_KEY'] = $key;
As you can see the $key variable get's it's contents from a while loop and outputs - let's just say - '12345'.
Everything looks correct, when I:
echo $Settings['SIGNING_KEY'];
it does output the '12345' on screen, as expected.
The weird thing is: when I enter:
$Settings['SIGNING_KEY'] = '12345';
in my file, the module that I am trying to modify seems to work correctly. But when I enter:
$Settings['SIGNING_KEY'] = $key;
for some reason the module cannot get the right signing key.
Can someone please explain to me what I am doing wrong?
Thanks in advance and sorry for not understanding PHP that much yet!
Edit:
Just a little extra explanation:
I am trying to get a string ($key) from the database instead of putting it hardcoded in a PHP file, so it (the $key variable) can be edited by everyone that has access to my website's control panel.

Is is possible $key isn't assigned probably? If you only want the first matching row change the while to an if. Also try dumping the value of $key and adding some error handling to your queries (as in: mysqli_query($link, $sql) or die(mysqli_error($link))).

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 probletm with appending new property into object?

I am starting to learn php for interaction with mysql db.
I have to fetch data from two unrelated tables and form an array of stdClass objects then dump it as json array.
I have so far managed to fetch data from table1 and added some columns from it into an
myobjects[], as follows..
Here $array is an array of primary keys , also i pass a reference to myobjects array
function load_from_table1($array , &$myobjects)
{
foreach($array as $num)
{
$obj=(object)null;
$obj->prop1 = $num;
$sql="SELECT * FROM `table1` WHERE col1=".$num;
$result = mysqli_query($con, $sql);
if($result!=null)
{
$row = mysqli_fetch_assoc($result);
//inserting data into object
$obj->prop2 = $row['col2'];
$obj->prop3 = $row['col3'];
$obj->prop4 = $row['col4'];
}
$myobjects[]=$obj;
}
}
It is fine so far now i need add two more properties to all items in myobjects array obtained from table2.
function load_from_table2(&$data)
{
for($i=0;$i<sizeof($data);$i++)
{
$obj=(object)$data[$i];
$id=$obj->prop1;
$sql="SELECT * FROM `table2` WHERE col1=".$id;
$result = mysqli_query($con, $sql);
if($result!=null)
{
$row = mysqli_fetch_assoc($result);
//$temp=$row['name'];
//echo $temp;
//$obj->name = "test1";
$obj->name = $row['name'];
//$temp=$row['description'];
//echo $temp;
//$obj->description = "test2";
$obj->description = $row['description'];
}
}
When i dump myobjects as json there is no output. But $temp echos properly , also when i us direct values every thing seems to work fine.
Can some one help me with this, also an explanation on what i am doing wrong would be greatly appreciated. Thank You.
Some Details on the working Environment , Because of the answer i provided ,
I am using wampserver 2.5 64 bit , and for now executing the php file off firefox browser.
The situation is quiet confusing as i can read the value and print it or save to variable , but not save it as object property.
I got it to work, But the problem was not with the code. It seems that the column in the table that i was reading has collation set to ' utf8_general_ci ' not sure what that means. But when i removed that setting , it all worked as expected. But i feel the collation is not the actual underlying reason. So i will keep this question open in hopes some might provide an explanation.
It seems i was looking for the wrong issues. Reading up on collation i found that some character sets are not supported fully , so i tried to echo the contents of the object array instead of json_encode and found it printed.
searching to that end i found another qst here on stackoverflow that solved my problem.
Simply added this line :: mysqli_set_charset($con,'utf8'); before i started any queries on that table and json_encode started working.

Blank result for some columns when php mysql_query, works in phpmyadmin

I've run into a problem that is making me go a bit crazy. I have imported some csv data into a table in my phpadmin database and am now using a php script with mysql_query() to run a simple select query on the database and convert the result into json format - e.g. SELECT clients FROM TABLE 29.
Basically, some of the columns in the table result in a json string after passing them through mysql_query() but others simply return a blank. I have fiddled for hours now and can't figure out why this is. The last bit of my code looks like this:
$myquery = "SELECT `clients` FROM `TABLE 29`";
$query = mysql_query($myquery) or die(mysql_error());
if ( ! $query ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
echo json_encode($data);
mysql_close($server);
Any help would be greatly appreciated. Could it be something about the data in the table? I'm at a loss.
thank you!
UPDATE: the length of the strings in the column clients seems to be having an effect. When I replace all the text with something shorter (e.g. aaa instead of something like company name 111 - 045 - project name - currency - etc) it works. However, I need it to be able to handle long strings as I want it to just take whatever users happen to import into it... what am I doing wrong?
No, its not about the table, its about how you loop them. Example:
$data = array();
while($row = mysql_fetch_assoc($query)) { // While a row of data exists, put that row in $row as an associative array
$data[] = $row;
}
echo json_encode($data);
mysql_close($server);
exit;
Note: mysql is depreacted and no longer maintained. Use the improved version of the mysql extension which is mysqli or use PDO instead.
After checking all the rows of the data I discovered that the source of the problem was a 'é' - yes, an 'e' with an accent. Once I replaced it with a regular 'e' the problem went away. So much lost time for something so tiny :(

Removing item using unset() from shopping cart creates mysql error

Hello everyone this is my first post on stack overflow.com
I am trying to create shopping cart. Values are being stored in a session in two dimension table. First value represents item id in database, second - quantity of item.
foreach($cart_array as $row){
$sql = "SELECT * FROM prod_table WHERE id=".$row['0']."";
$cart_result = mysql_query($sql, $conn);
while ($array = mysql_fetch_array($cart_result)) {
echo "<tr><td>". $array[manufacturer] . "</td>";
echo "<td>". $array[model]."</td>";
echo "<td>".$row['1']."</td>";
$cart_value = $array[price]*$row['1'];
//sum and store value of all products
$total_cart_value += $cart_value;
echo "<td>£" .$cart_value. "</td>";
echo "<td><a href='search.php?kick_id=".$row['0']."'>Remove</a></td></tr>";
OK, to remove item form cart user clicks remove and then he is being send back to the same page ( for some reason I had difficulty to use $_SERVER['PHP_SELF'} with GET method... )
and then different part of code is being triggered which is going to remove pair of values from $cart_array, using unset function.
if(isset($_GET['kick_id'])) {
$t = count($cart_array);
for( $u = 0; $u < $t; $u++){
if ($cart_array[$u]['0'] == $_GET['kick_id']){
unset($cart_array[$u]['0']);
unset($cart_array[$u]['1']);
echo " Item has been removed from your cart";
$cart_array = array_values($cart_array);
And it actually removes pair of values but, now instead of running smoothly it displays error message :
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource ...
I assume that there must be some "trace" of deleted values in session array which is causing error.
How to fix code ?
Is there any other method/approach to delete values ??
You don't appear to have unset($cart_array[$u]), just the two keys it contains. Don't bother unsetting $cart_array[$u]['0'] and '1', just unset $cart_array[$u].
I assume that...
that is what you are doing wrong.
A programmer should never "assume". A programmer can (and should) be certain.
Assumptions will lead you astray and waste your time (as well as other people's time when you ask a question).
So, you have to do some debugging - an investigation to find the actual cause of the problem.
supplied argument is not a valid MySQL result resource error means there was an error in the query. So, you have to see what error it was. So, run all yoiur queries in the manner which let you to see any error occurred. A simplest way would be
$cart_result = mysql_query($sql, $conn) or trigger_error(mysql_error()." in ".$sql);
and run your code again.
you will find an sql error in their usual place - a screen or a log file.
If you'll be unable to get the meaning of the error and correct your code yourself - it's time to ask a question. A certain and direct question, not vague question out of some assumptions. Gotcha?
There are two ways to solve this:
1) on your first part:
foreach($cart_array as $row){
if(empty($row[0])
continue;
$sql = "SELECT * FROM prod_table WHERE id=".$row['0']."";
[...]
2) when you remove the item, instead of unset($cart_array[$u]['0']); why don't you do unset($cart_array[$u]); ?
Probably this
while ($array = mysql_fetch_array($cart_result)) {
is causing the problem. based on error you see. before you try fetch result check if there is any results available by
if(mysql_num_rows($cart_result)>0){
while ($array = mysql_fetch_array($cart_result)) {
//rest code here
}

Categories