Select MySQL column/row with comma separated values - php

Suppose I have the following table information
+-------------+---------------+
+ id + letters +
+-------------+---------------+
+ 1 + a, b, c, d, e +
+-------------+---------------+
I am trying to capture the values of the column and store them in variables:
$result = mysql_query("SELECT letters FROM tbl WHERE id=1");
while ($data = mysql_fetch_array($result)) {
// Declare captured db variables
$letter1 = ** what comes here? **;
$letter2 = ** what comes here? **;
}

You can try this way:
$result = mysql_query("SELECT letters FROM tbl WHERE id=1");
$letters = explode(',',mysql_fetch_array($result));
Now you can access any letter using an array, like this $letters[0]; //a.

Instead of having
$letter1
$letter2
I would make an' array with explode.
$letter = explode(',', $data['letters']);
That way you can acccess your letters with a simple $letter[0] or $letter[1]
Now the above code works from the assumption that you only run through the while loop ONCE.
If you run through the while loop more than once, I'd do it like this:
$letter[] = explode(',', $data['letters']);
which is accessed by $letter[0][0] - The first [] being the instance of number when it was fetched, the second [] being the letter you want to fetch.
Another thing
Mysql is outdated / not gonna be used / very unsecure so I would advice you to find another alternative to mysql, such as mysqli or PDO - It is better to use these while you are learning because that way you avoid getting stuck with bad routines.

How about this?
$result = mysql_query("SELECT letters FROM tbl WHERE id=1");
while ($data = mysql_fetch_array($result)) {
// Declare captured db variables
/* list($letter1,$letter2,$letter3,$letter4,$letter5) = explode(',' , $data['letters']);
*/
$letters = array();
// letters array will have the exploded letters
$letters = explode(',' , $data['letters']);
}
Your question is unclear. Please provide more details for a better answer :)

Related

PHP Replace specific values inside formula

I have a formula where some of the data needs to be replaced by MYSQLI query results.
The formula can look like:
100+400-600-700
The numbers in the formula will match a specific table line in the DB and output correct value, for example:
121000+1000-8000-2000
I've tried to extract all the special characters from the original string in order to get the correct DB result via MYSQLI using formula:
preg_match_all('!\d+!', $rf, $matches);
foreach ($matches as $key1 => $value) {
//Declare summarization of TOT rows
$TOT = 0;
foreach ($value as $single) {
$querymatch = mysqli_query($mysqli, "SELECT rowMainAccount FROM reportTable_rowDefinitions WHERE rowCode = '$single' AND reportID = $rowDefinition");
$arraymatch = mysqli_fetch_array($querymatch);
$TOTaccount = $arraymatch['rowMainAccount'];
//Fetch values from FinancialTransactions
//Fetch values
$queryTOT = mysqli_query($mysqli, "SELECT SUM(debit) AS debitTOT, SUM(credit) AS creditTOT FROM FinancialTransactions WHERE mainAccount = $TOTaccount AND entity = $org AND date BETWEEN '$newStartDate' AND '$newEndDate'");
$arrayTOT = mysqli_fetch_array($queryTOT);
$TOTcred += $arrayTOT['creditTOT'];
$TOTdeb += $arrayTOT['debitTOT'];
}
$TOT += $TOTdeb - $TOTcred;
}
echo $TOT; //Returns values
This will only replace the numbers in the original string giving result as
121000100080002000
from foreach loop.
How can I put the returned values from DB into the original formula to acieve the correct output as
121000+1000-8000-2000
?
Use preg_replace_callback and in the callback you can get the appropriate value and return it to place it in the original string.

Remove comma From the last value in a While loop

My main motive is to remove the comma ',' from the last value of the array.
$Followingcount = mysqli_query($con,"SELECT * from followers where follower_id = '$idnow'");
if (mysqli_num_rows($Followingcount) > 0) {
while ($ids = mysqli_fetch_assoc($Followingcount)) {
$followedids = $ids['acc_id'].',';
$array = array($followedids);
$arraystr = implode("','",$array);
}}
If I echo $followerdids the result comes like this with commas like:
5, 7, 8,
To remove the comma at the last value I tried to place the values inside an array and then I imploded it.
When I echo $arraystr it still contains the comma at the last value.
All you need is:
$followedIds = [];
$followingCount = mysqli_query($con,"SELECT * from followers where follower_id = '$idnow'");
while ($ids = mysqli_fetch_assoc($followingCount )) {
$followedIds[] = $ids['acc_id'];
}
echo implode(',', $followedIds);
...and take care of SQL Injection
The solution to your problem is quite simple. There is a function called rtrim(), which removes all characters on the right side.
$followedids = rtrim($followedids, ',');
There is also a trim() function, which does the same on both sides, and ltrim() which does it for the left side.
You can use rtrim to remove the last comma after the while loop.
$followedids = rtrim($followedids, ',');
You could use the substr-function (more information here)
The last parameter is the length of the substring you want, but you can also use negative values, which means "remove this many characters", in your case: 1.
In your case:
$followedids = substr($followedids, 0,-1);

PHP and MySQL string comparison failing

Okay, so I'm having a pretty annoying little problem with my php code. Basically I pull two variables from two seperate sources. One's a cookie and the other is from a MySQL database.
$data = explode("|", $_COOKIE['login']);
$sql = "SELECT session_id FROM users WHERE username='user1'";
$result = $data->query($sql);
$row = $result->fetch_assoc();
$test1 = $data[0];
$test2 = $row['session_id'];
If($test1 == $test2) {
// Do some stuff
}
else {
// Don't do some stuff
}
The actual string is:
x6vkYu6Ep^lm(1Rdm)5Gj5Hj7ilL6FsDL88JC#n#iTyBUqYgJ48#9Ow%*2ZdGs1rA8bc)JoCD7dywcZgg7soV0D#!DpR^pjQwF#QpBt#HRKe$JEtQ*3LhFXsjmkzWNpt
The string is randomly generated before being stored from the following character set:
1234567890!##$%^&*()abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
for($i = 0; $i < 128; $i++) {
$string .= $char_set[rand(0, strlen($char_set)-1)];
}
$sql = "UPDATE users SET session_id='$string' WHERE user='user1'";
$data->query($sql);
setcookie('login', $string . "|" . $username);
If I just set the two variables equal to the above string and evaluate, it works out just fine. Also, if I echo both $data[0] and $row['session_id'] the entire string will display, and they look indentical.
The if() statement will work if I use basic strings, like a number, or basic word, so I'm guessing it's due to special characters, but I don't know where in the proccess it goes wrong. As I said, if I set two variables to that string value, it evaluates, but when I pull from MySQL and the cookie, despite that both strings look the same, it won't evaluate.
Any thoughts?

Picking numbers in an order

I had a task to slide images from a mysql database using jquery slide and not the animation scripts. The slide is supposed to show at least the most recent ten images that was uploaded. With that I first of all wrote a random query
mysql_query("select * from tblname order by rand() limit 1);
But as expected, it picks the images at random irrespective of when it was posted and of course it wasn't the most recent ten. After some thought I now had to first run a query to get the most recent ten
mysql_query("select * from tblname order by ID limit 10);
while($row=mysql_fetch_array($sql){
$slideid=$slideid.",".$row['recordid'];
}
this of course results to a variable of this order
$var="23,22,24,34,27,78,56,87,98,55";
I tried handling it like an array but it wasn't giving any positive result, hence I had an issue of how to pick this numbers and use it for the slide
$myArr=explode(',',$var);
sort($myArr);
for($i=0;$i<count($myArr);$i++)
{
echo $myArr[$i];
}
Edit: For better efficiency use:
$myArr=explode(',',$var);
sort($myArr);
foreach ($myArr as $val)
{
echo $val;
// Or do whatever else you want with each one.
}
Edit 2: See comments below on efficiency vs for loops vs unexpected results. :)
Based on your comments I will offer my 2p into the mix
this is what I did $slideid="23,22,24,34,27,78,56,87,98,55"; $arr =
explode(',',$slideid); foreach ($arr as $val) { //lets get the
variables from the form post $rs = mysql_query("SELECT * FROM tblname
WHERE id='$val'") or die(mysql_error());
while($row=mysql_fetch_array($rs)){ echo "<img src='image/$image'>"; }
} the images are displayed one by one using jquery slide
Now I think we are wasting time dealing with exploding this variable because mysql has the nifty IN() function (possibly in other db's I don't know)
$slideid = "23,22,24,34,27,78,56,87,98,55";
$rs = mysql_query("SELECT * FROM tblname WHERE id IN({$slideid})") or die(mysql_error());
while ($row = mysql_fetch_assoc($rs))
{
echo "<img src='image/{$row['image']}' />";
}
I hope this helps
$var="23,22,24,34,27,78,56,87,98,55";
$arr = explode(',',$var);
foreach ($arr as $val) {
// work with $val
}
explode splits the string to an array
1) Explode the string into an array, splitting on the comma.
2) You didn't say whether you wanted to re-order the numbers into numerical order, or process them in the order they're already in. If the former, sort the array with sort($arr);
3) Loop over the array in sequence and do something with each number
$str = '1,2,3,4,5,6';
$arr = explode(',', $str);
foreach($arr as $num) echo $num.'<br />';
Note if there is any change of spaces after commas, a better choice would be preg_split rather than explode, as this is more dynamic.
$arr = preg_split('/, ?/', $str);
You can achieve this using php explode function
$pieces = explode(",", $var);
echo $pieces[0]; // piece1
echo $pieces1; // piece2
.
.
.
echo $pieces[n]; // piece n
I think you need to get result of order with respect to order of variable here
$slideid = "23,22,24,34,27,78,56,87,98,55";
$rs = mysql_query("SELECT * FROM tblname WHERE id IN({$slideid}) ORDER BY FIELD(id, {$slideid}) ") or die(mysql_error());
while ($row = mysql_fetch_assoc($rs))
{
echo "<img src='image/{$row['image']}' />";
}

PHP - Compare exploded word with mysql varchar in PHP

How can I compare exploded word with mysql varchar in PHP?
This code produce what i want but it also give this error
veranderenwachtwoordjij
Fatal error: Call to a member function fetch_assoc() on a non-object......
$word = "Also, to be safe, change your password regularly... you don't have to be obsessive about it: every three hours or so should be enough. And because erring on the side of caution is always a good idea, fake your own suicide and change your identity at least once a year.";
$pieces = explode(" ", $word);
$x = 0;
while($x < word_count($word)) { // word count function returns int (51)
$aPiece = $pieces[$x]; // change $pieces[$x] to 'you' and then it works
$result = $conn->query("SELECT * FROM dict WHERE english='$aPiece'");
$z = 0;
while($z < $num_result) // $num_result returns amount of rows in database
{
$row = $result->fetch_assoc(); //error line is here
echo stripslashes($row['dutch']);
$z++;
}
$x++;
}
I guess the problem comes from the don't in your test sentence : you forgot to escape quotes with a function like mysql_real_escape_string.
For example :
$aPiece = mysql_real_escape_string($pieces[$x]);
$result = $conn->query("SELECT * FROM dict WHERE english='$aPiece'");
I think
$row = $result2->fetch_assoc();
should be
$row = $result->fetch_assoc();
since you don't seem to have a $result anywhere.
$result2 in $result2->fetch_assoc(); is not the correct variable, it should be
$result->fetch_assoc();
by the way you have to delete the punctuation marks in order to find the words in your database (I think) one of your first lines should (before the explode) be similar to this:
$words = strtr($words, ',.:!','');

Categories