online server wont show string values - php

i have this code, where i get an array and make it a string, on my localhost show the values correctly (1,2...) but on my online server shows (,,) no numbers, just the commas. Does someone know what this issue may be?
Heres my code
<?php
error_reporting(E_ALL);
CONECTION
$sql = "select id from table where id=1";
$result = mysql_query( $sql);
$myArray= array() ; //Here you must declare it as array
while($row = mysql_fetch_array($result)){
$popurl = $row['id '];
$myArray[] = $popurl;
}
$string = "" . implode(", ", $myArray) . "" ;
echo $string;
?>
Please need help

It's a simple typo problem:
$row['id '] is not defined. Correct it to $row['id'] and you should be fine.

Related

Get rid of the last comma when echoing a row?

// This gets all the users that are active
// The limit is completely random, it is set to 2 for this example
$sql = <<<SQL
SELECT *
FROM `accounts`
WHERE active = 1
LIMIT 2
SQL;
if(!$getaccounts = $db->query($sql)){
die('There was an error running the query [' . $db->error . ']');
}
while ($row = $getaccounts->fetch_assoc()) {
$getid = $row["id"].',';
$getid = substr($getid, 0, -1);
$getusername = $row["username"];
$getpassword = $row["password"];
echo $getid;
echo $getusername."<br>";
echo $getpassword."<br>";
}
I know this hasn't been prepared but I am not using it for anything other than personal use.
I cannot understand why this is not getting rid of the last comma?
The output may be something like "32,14,"
And I want to get rid of the last comma by using the "substr" function.
But the output that that I get from $getid is "3214" (It gets rid of all the commas instead of just the last one.
I need it to output "32,14" but it's not working?
Could someone please tell me where I am going wrong?
If I do rtrim, it does the same thing and gets rid of all the commas! I am going to update something in the database using the ids, and that is why I need to get rid of the last comma
And I know this code is not secure, I am not using it for anything other than personal use and I was hoping someone could help me figure this out, I have been attempting it for days, it seems really simple and I bet I am missing something really stupid!
You have a XY Problem.
You want to concat all the id's into a comma-seperated string.
Here's a much easier solution by adding the items to an array and then implode().
<?php
// rest of your code
$ids = Array();
while ($row = $getaccounts->fetch_assoc()) {
$ids[] = $row["id"];
$getusername = $row["username"];
$getpassword = $row["password"];
echo $getusername."<br>";
echo $getpassword."<br>";
}
echo "ids: " . implode(",",$ids);
You should write code like..
$getid = "";
while ($row = $getaccounts->fetch_assoc()) {
$getid .= $row["id"].',';
}
$getid = rtrim($getid,',');
$q = " UPDATE accounts SET active = '0' WHERE id IN ($getid) ";

Store multiple rows from mysql database into one single variable

this is really hard for me, i'm trying to store multiple rows from my table in mysql into a single variable
$mysql_statementJc = "SELECT * FROM `dog`.`cat` WHERE `name` = '$name'";
$mysql_commandJc = mysql_query($mysql_statementJc);
while($row = mysql_fetch_array($mysql_commandJc)){
$followI = $row['industry'];
$groupConcat = $followI . " OR ";
echo $groupConcat;
}
This is my appproach, so at the end of it all i can get "sam, john, bob" saved as $groupConcat which can then be used elsewhere.
Many thanks.
you want to create a concatenated string, php has the .= syntax for this:
$groupConcat='';
while($row = mysql_fetch_array($mysql_commandJc)){
$groupConcat .= $row['industry'] . " OR ";
}
echo $groupConcat; //no point echoing inside the loop
sometimes a better approach is to use an array and implode()
$groupConcat=array();
while($row = mysql_fetch_array($mysql_commandJc)){
$groupConcat[] = $row['industry'];
}
echo implode(' OR ',$groupConcat);
Each time through the loop, add the desired value to an array. Then, after the loop, use the implode() function to create your desired output.
while($row = mysql_fetch_array($mysql_commandJc)){
$followI = $row['industry'];
$resultArray[] = $followI;
}
$groupConcat = implode(" OR ", $resultArray);
echo $groupConcat;
Note that you should really stop using the mysql library and instead use mysqli or PDO.
You can also do it as:
$followl = array();
while($row = mysql_fetch_array($mysql_commandJc))
{
$followl[] = $row['industry'];
}
$groupConcat = implode(" OR ",$followl);
echo $groupConcat;
Some Explanation:
Store values into an array $followl and than use implode() function for imploding with OR.
Side note:
Please use mysqli_* or PDO becuase mysql_* is deprecated and no more available in PHP 7.

postgresql select query with variables

I am trying to make a postgresql select query work with php, but can't get past the syntax.
I have a variable and a query that returns the surname of any match.
$name = 'Smith';
$query = 'SELECT surname FROM emploee WHERE name= '.$name.';';
$a = pg_query(connect(),$query );
while($row = pg_fetch_array($a)){ echo "Match"; }
For those who wonder why do I have to declare Smith as a variable, $name is not always equals to Smith. The value of $name is taken correctly from another query. However, this is not working. I read in an article that I should use pg_query_params() but couldn't get that to work neither.
Your help would be highly appreciated
Try this :
$query = "SELECT surname FROM emploee WHERE name= '" . $name . "';";
And the best way without binding :
$query = sprintf("SELECT surname FROM emploee WHERE name = '%s'", pg_escape_string($name));
And if you want to use binding :
$result = pg_query_params(connect(), 'SELECT surname FROM emploee WHERE name = $1', array($name));
As you get a result from other query ' Smith', there is a white space.
To remove white space from $name, you can do : $name = trim($name);
These are the two methods that worked, suggested by Bang and Frank Heikens respectively. Since they only commented, I am posting it as an answer for those who might come up the same situation. However, I would strongly advise them to read the comments too. I learned a couple of stuff on the way, you might as well.
Bang's suggestions->
$a = trim($name);
$query = "SELECT surname FROM employee WHERE name= '" . $a . "';";
$result = pg_query(connect(), $query);
while($row = pg_fetch_array($result)){ echo "Match"; }
Frank Heikens suggestions ->
$n = trim($name);
$s = trim($surname);
$params = array ($n, $s);
$result = pg_query_params(connect(), 'SELECT office FROM emploee WHERE name = $1 and surname = $2', $params);
while($row = pg_fetch_array($result)){ $k = $row['path']." ".$row['office']; echo $k; }
In both cases I have to use trim (not sure if this will be your case too). I added a third field office to demonstrate how can I take several arguments.
If anyone has other critics, suggestions or solutions, be my guest. I will try everyone of them and let you know.
With this code above: you can print "match" for each record matched with query
$a = trim($name);
$query = "SELECT surname FROM employee WHERE name= '" . $a . "';";
$result = pg_query(connect(), $query);
while($row = pg_fetch_array($result)){ echo "Match"; }
But certainly you need to print the values returned:
just make it echo $row['columnName']
Full details here:https://w3resource.com/PostgreSQL/select.php

regex does not work with mysql_fetch_array

How can you perform a search and replace with php on an array returned from mysql_fetch_array()? If I use preg_replace() it will not return a match. Is there something that I'm missing?
This is what I have used without sucess, could anyone pleas take a look and tell me what I'm doing wrong, or possibly a better way to achive this:
mysql_connect(DATABASE_HOST, DATABASE_USERNAME, DATABASE_PASSWORD)
or die("<p>Error connecting to database: " . mysql_error() . "</p>");
mysql_select_db(DATABASE_NAME)
or die("<p>Error selecting the database " . DATABASE_NAME . mysql_error() . "</p>");
$sql = "SELECT product_id,description FROM oc_product_description WHERE product_id >= 97 AND product_id <= 100";
$result = mysql_query($sql);
$pattern = '/^.*\b([0-9]{6}\s\D\d|[0-9]{6}\s\D[0-9]{2}|[0-9]{7}\s\D[0-9]{2})\b.*$/';
$replace = '$1';
while($row = mysql_fetch_assoc($result))
{
$item[] = $row['description'];
}
foreach($item as $items)
{
echo preg_replace($pattern, $replace, $items) . '<br>';
echo '<br>';
}
all that this will do is return the same as it would without the preg_replace(). Now I know the code works because if I output a print_r($item) and copy the results into an array it works just fine. Am i doing something wrong or does preg_replace() just not work with arrays returned from mysql_fetch_assoc or mysql_fetch_array? I could put my example up where i copy the results into an array but dont want to waste space. Here is an example of an item returned from the database and the string I'm trying to match with regex. I need everything removed but the match.
One item returned from $row['description']:
1997 Suzuki VZ800 Marauder, Engine # 5506-111789, Kick stand and spring. Chrome on end is starting to chip. 0121103 S19 <img src = ">http://www.roofis27.com/motorcycle/13_01_21/103.JPG">
Here is what the regex retrurns: 0121103 S19
So therefore I have over 20,000 entry's in a database with descriptions like these and need these codes like the example above removed from them so I can INSERT them into another table column that matches the product_id relational to the descriptions product_id. I am not the best with SQL, but the <img> tag is always after the code so maybe there is a way to do it with SQL that I'm not aware of? My main concern at this point is why preg_replace() doesn't work with an array returned from mysql_fetch_array(), but works fine on any other arrays ( associative, multidimensional or not). Is there something about the values returned from a database that prevent me from being able to do this? Anything would be greatly appreciated, I'm really stuck on this!
After thinking about what jerry had to say(in the comment above) I came up with this resolution, apparently there are characters in the return from mysql_fetch_array() that are invisible and that's why the regexp does not work. I got way better results using preg_match() as follows:
$sql = 'SELECT product_id,description FROM oc_product_description';
$sql1 = 'UPDATE db_product SET model = ';
$sql2 = 'WHERE product_id = ';
$pattern = '([0-9]{6}\s\D[0-9]{2}|[0-9]{6}\s\D\d|[0-9]{7}\s\D[0-9]{2})';
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result))
{
$data[] = $row['description'];
foreach($data as $datas)
{
preg_match($pattern, $datas, $matches, PREG_OFFSET_CAPTURE);
}
foreach($matches as $match)
{
$Q1 = $sql1 . '"'. $match[0] . '"' . ' ';
}
$Q2 = $sql2 . $row['product_id'] .';';
$query = $Q1 . $Q2;
mysql_query($query);
echo 'Product ID' . $row['product_id'] . ': ';
printf("Records updated: %d\n", mysql_affected_rows());
echo '<br>';
}
Yes, I will start using PDO for database cons and querys, did some research on it and look pretty cool. It's just I'm new to php and still in school so I have so much learning going on I hate having to change ( better get used to it though, HUH?) Thank you jerry :)

Combine array elements into single string

So this is what I'm trying to do..
$sql="SELECT * FROM `members";
while($rew = mysql_fetch_array($sql)){
$var[] =",'".$rew['username']."'";
}
print_r ($var)
So I get the result:
Array ( [0] => ",'John'", [1] => ",'Mason'", [2] => ",'Greg'", [3] => ",'Paul'" )
So now I want the variable to display all results when I echo. For example:
<?php echo $var[1] ?>
And the result will be just ,'Mason'.
How do I get it so that I can echo $var[*] and get all the results. "John,Mason,Greg,Paul".
I have been trying to figure this out for a very long time and is getting very frustrating for me. Can someone please help me.
Use PHP's implode function.
<?php echo implode(",", $var) ?>
And change your loop code to:
$var[] = $rew['username'];
You can't use echo on an array directly. You could either loop through the array using a control structure like for or foreach, or you can use a built-in function that is designed to operate on arrays. To get the output you are looking for try:
<?php echo implode(',', $var);?>
Here's a good tutorial: Tizag - MySQL Fetch Array
This should work:
$query = "SELECT * FROM `members`";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo $row['username'];
echo "<br />";
}
You can change your loop to something like:
$var = "";
while($rew = mysql_fetch_array($sql)){
$var .= ",'" . $rew['username'] . "'";
}
Here is a simple one liner that also adds the quotes
<?php echo "'" . implode("','", $var) . "'"; ?>
and if you use pdo, you can get the usernames even easier
<?php
$usernames = $db->query("SELECT username FROM members")->fetchAll(PDO::FETCH_COLUMN);
echo "'" . implode("','", $usernames) . "'";
?>

Categories