php array to string not working online server - php

I have a problem. I have an array of values from database, when I try to pass it to a string with commas, it works fine on my localhost, but when I upload it to my online server, the string doesn't show any values. For example: select from table where in (,,) only shows the commas and in my xampp server it works excellent. Any ideas what this can be?
Here's the code:
<?php
$sql = "select id from users where gid = 1";
$result = mysql_query( $sql);
$cat_titles=array();
while( $row=mysql_fetch_assoc($result) )
{
$cat_titles[] = $row['id '];
// do stuff with other column
// data if we want
}
mysql_free_result( $result );
echo "<p>\n";
foreach($cat_titles as $v)
{
$cat_titles[]= $row['id'];
}
echo "</p>\n";
$cat_titles = implode(',',$cat_titles);
$cat_titles = substr($cat_titles,0,-2);
echo $cat_titles;
echo "select * from users where IN (".$cat_titles.")";
?>

A number of potential issues here:
You are not handling error conditions around you database access, so if you are having issue with your queries you would never know.
Your second select query doesn't specify a field in the WHERE clause, so it will never work
This section of code does absolutely nothing and is in fact where you problem likely lies.
foreach($cat_titles as $v)
{
$cat_titles[]= $row['id'];
}
Here $row['id'] won't have a value, so you are basically looping throguh your existing array and appending empty value to new indexes.
In all likelihood you could do this with a single query, it might help if you explain what you are actually trying to do.
You should not be using mysql_* functions. They are deprecated. Use mysqli or PDO instead.

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.

Moving Query to MySQLi

I'm updating some old code that has deprecated MySQL functions. But for some reasons I cannot get all the results from the column. The strange part is that if I run the query directly on the server I get all results fine. So this is an issue with PHP getting the results, not the MySQL server or my query.
Here is the new and old code:
My current updated code:
$sql = "SELECT user, monitor FROM users WHERE `status` = 'y'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
// This works. It shows all results
echo $row["user"];
// This does not work! Only shows one result:
$account= $row["user"];
}
else {
echo 'No results';
}
When I use that query directly on DB server, I get all results. So the SQL query is correct. I actually also get all results as well in PHP if I echo the row directly like:
echo $row["user"];
But for some reason when I try to use it with a PHP with variable it only lists one user result.
In the past I used this but the mysql_fetch_array function is now deprecated
while ($row = mysql_fetch_array($result)) {
array_push($data, $row["user"]);
}
foreach($data as $value) {
$account = $value
}
I cannot use my previous code anymore as those MySQL functions are obsolete today. I need to write the results into a file and my old method worked fine. The new one using mysqli does not.
Any suggestions?
You just need to add one of these [, and one of these ].
$account[] = $row["user"];
// ^^ right here.
$account= $row["user"]; means you're storing the value of $row["user"] in $account each time the loop executes. $account is a string, and it gets a new value each time.
$account[] = $row["user"]; means you're appending each value of $row["user"] to an array instead.
You should not use array_push for this. It's overkill for appending a single value to an array. And if the array isn't defined beforehand, it won't work at all.

Displaying users with a php, sql count?

I have a database with users input and was wanting to output a user table (id, username) as a count on a page. The following piece of code is what I've been trying to work with but I've been having no luck and it keeps getting more and more complex - the SQL works perfectly so I'm not sure what's wrong.
mysqli_select_db($db);
$result = $_POST ['$result'] ;
$result = mysqli_query("SELECT COUNT( * )
FROM users");
$row = mysqli_real_escape_string($result,$db);
$total = $row[0];
echo "Total rows: " . $total;
I'm still learning how to properly link SQL in with PHP. The warnings tell me to add an extra parameter however when I do so it still complains.
I originally wanted a simple COUNT but will change the count to a table array if need be. I understand this maybe a little basic and I may have been going about it the wrong way, but I've hit a wall with it and any help on fixing the COUNT would be greatly appreciated
Replace the call to mysqli_real_escape_string to mysqli_fetch_array and your code will works.
mysqli_real_escape_string is only useful for string escaping when you INSERT or UPDATE data to MySQL.
$row = mysqli_fetch_array ($result);
Please try this code:
$sql="SELECT * FROM users";
$result=mysqli_query($con,$sql);
// Numeric array
$row=mysqli_fetch_array($result,MYSQLI_NUM);
$number = count($rows);
Hope this works.

echo statement not showing result after getting variable from $_post in php mysql

I am unable to understand why I am unable to use echo statement properly here.
Link which passes get value to script
http://example.com/example.php?page=2&hot=1002
Below is my script which takes GET values from link.
<?php
session_start();
require('all_functions.php');
if (!check_valid_user())
{
html_header("example", "");
}
else
{
html_header("example", "Welcome " . $_SESSION['valid_user']);
}
require('cat_body.php');
footer();
?>
cat_body.php is as follows:
<?php
require_once("config.php");
$hot = $_GET['hot'];
$result = mysql_query( "select * from cat, cat_images where cat_ID=$hot");
echo $result['cat_name'];
?>
Please help me.
mysql_query returns result resource on success (or false on error), not the data. To get data you need to use fetch functions like mysql_fetch_assoc() which returns array with column names as array keys.
$result = mysql_query( "select
* from cat, cat_images
where
cat_ID=$hot");
if ($result) {
$row = mysql_fetch_assoc($result);
echo $row['cat_name'];
} else {
// error in query
echo mysql_error();
}
// addition
Your query is poorly defined. Firstly there is not relation defined between two tables in where clause.
Secondly (and this is why you get that message "Column 'cat_ID' in where clause is ambiguous"), both tables have column cat_ID but you did not explicitly told mysql which table's column you are using.
The query should look something like this (may not be the thing you need, so change it appropriately):
"SELECT * FROM cat, cat_images
WHERE cat.cat_ID = cat_images.cat_ID AND cat.cat_ID = " . $hot;
the cat.cat_ID = cat_images.cat_ID part in where tells that those two tables are joined by combining rows where those columns are same.
Also, be careful when inserting queries with GET/POST data directly. Read more about (My)Sql injection.
Mysql functions are deprecated and will soon be completely removed from PHP, you should think about switching to MySQLi or PDO.

Possible to use php tag inside query string?

I have multiple values passed through a POST form (from multiple check boxes of previous page) and I stored them into an array $vals. Now I want to write a query string (in a while loop) that generates a slightly different query depending on how far in the loop it has been.
<?php
$vals=($_POST['selectedIDs']);
$i=0;
while($vals[$i] != NULL){
$query = "SELECT * FROM List foo WHERE foo.fooID = echo $vals[$i]";
$result = mysqli_query($link, $query);
if($result) echo "YES IT WORKS!";
$i += 1;
}?>
But it doesn't seem to work this way? I thought that by having double quotes for query, the
echo $vals[$i]
would generate the actual value of the current index in $vals[$i] and not the literal string? Is this what's happening? Can I not have php inside a query string that the mysql servers would accept?
lets just say i have a fooID in my server table that is '12345'. Even if I set $vals='12345' and write:
$query = "SELECT * FROM List foo WHERE foo.fooID = $vals";
$result = mysqli_query($link, $query);
if($result) echo "YES IT WORKS!";
it still doesn't work. I guess my general question would be: is it possible to write/get values of variables in a query string, and if not, is there another way around my situation? Any help is appreciated. Thanks!
You should not be placing the un-sanitized $_POSTed values into a SQL query. Look into using paramaterized arguments and mysqli.
You can output variables using the syntax:
$myVar = 'toast';
$combined = "I like $myVar";
However, this will not work as you would like for an array.
For an array, you'll want to look into using something like php's implode() to convert your array into a string first.
first of all never do queries in loop.
Second of all never use straight $_POST or $_GET or whatever client is passing in queries because you can be harmed by sql injections.wiki and also clearing data for mysql in php
ok so how it should be done (i am saying only about first one. second one i dont know how to make it without oop ).
<?php
$vals=($_POST['selectedIDs']);
$vals = implode(',',$vals);
$query = "SELECT * FROM List foo WHERE foo.fooID IN ($vals)";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_row($result)) {
echo "YES IT WORKS!";
var_dump($row); //you will see all the data in one row
}
}?>
You have an extra echo in your SQL string:
$query = "SELECT * FROM List foo WHERE foo.fooID = echo $vals[$i]";
It should be:
$query = "SELECT * FROM List foo WHERE foo.fooID = $vals[$i]";
Generally, it's a BAD idea to construct SQL strings from user input. Use prepared statements instead. Check here for more info on prepared statements:
http://php.net/manual/en/pdo.prepared-statements.php
Thanks you guys for the advice but it turned out, my code didn't execute correctly because of a syntax error (and the extra echo statement). my original code was missing quotation marks around $vals[$i]. This is a mysql syntax mistake because it didn't accept foo.fooID=12345 but did for foo.fooID='12345'. Here is the final code that solved it
<?php
$vals=($_POST['selectedIDs']);
$i=0;
while($vals[$i] != NULL){
$query = "SELECT * FROM List foo WHERE foo.fooID = '$vals[$i]'";
$result = mysqli_query($link, $query);
if($result) echo "YES IT WORKS!";
$i += 1;
}?>

Categories