I try to retrieve a array from one table What is wrong with this code?
$_fbexclude = mysql_query("SELECT fbempfang FROM fbinvite WHERE fbreturn = '1' ");
$fbexcludearray= mysql_fetch_array($_fbexclude);
// Convert the array
$excludes = implode(',', $fbexcludearray);
From echo $excludes; It only gives me just the following response: 1000033xxx161,1000033xxx161 Twice the same fbempfang
See if the following gives you what you want (FIXED):
$_fbexclude = mysql_query("SELECT fbempfang FROM fbinvite WHERE fbreturn = '1'");
$fbexcludearray = array();
while ($row = mysql_fetch_assoc($_fbexclude)) {
$fbexcludearray[] = $row['fbempfang'];
}
// Convert the array
$excludes = implode(',', $fbexcludearray);
mysql_fetch_array() and it's siblings (_assoc, _row) only retrieve one row at a time. This means that your original code will only give you the first returned row - to work around this, we use the loop you see above.
The reason you see the same data twice is because mysql_fetch_array() returns a mixed indexed and associative array, which contains all the data twice over. For this reason, it is much better to use mysql_fetch_assoc() or mysql_fetch_row(), as you rarely need both formats.
In fact, it is much better to use mysqli, but the same information applies to that as well.
Use right SQL query:
SELECT GROUP_CONCAT(`fbempfang`) as imploded from `fbinvite` WHERE fbreturn = '1'
It's return string as PHP implode(',', array(…));
Try this on for size:
$implode_arr = array();
$_fbexclude = mysql_query("SELECT fbempfang
FROM fbinvite
WHERE fbreturn = '1'");
while($row = mysql_fetch_array($_fbexclude)) {
$implode_arr[] = $row['fbempfang'];
}
// Convert the array
$excludes = implode(',', $implode_arr);
You need to loop over the mysql_fetch_* functions because they only return one of the result rows at a time. For more information and examples see the manual page for mysql_fetch_assoc().
Related
The intention with the below code is to extract messages from a mysql table, and put each of them inside ONE array with {} around each output. Each output consists of various parameters as you can see, and is an array in itself.
What the code does is that each time the loop is processed, in the JSON array that this later is converted into, it wraps the output in []´s, hence it´s now a new array which is created.
What I get is:
[{"sender":"ll","message":"blah","timestamp":"2016-12-21 14:43:04","username":"","msgtype":"","threadid":"32629016712222016034323"},{"sender":"kk","message":"blahblah","timestamp":"2016-12-21 14:43:23","username":"","msgtype":"","threadid":"32629016712222016034323"},{"sender":"ll","message":"blahblahblah","timestamp":"2016-12-21 14:43:47","username":"","msgtype":"","threadid":"32629016712222016034323"}],[{"sender":"ll","message":"blahblahblahblah","timestamp":"2016-12-21 14:43:04","username":"","msgtype":"","threadid":"92337321312222016034304"},{"sender":"kk","message":"blahblahblahblahblah","timestamp":"2016-12-21 14:44:05","username":"","msgtype":"","threadid":"92337321312222016034304"}]]
And what I want is:
[{"sender":"ll","message":"blah","timestamp":"2016-12-21 14:43:04","username":"","msgtype":"","threadid":"32629016712222016034323"},{"sender":"kk","message":"blahblah","timestamp":"2016-12-21 14:43:23","username":"","msgtype":"","threadid":"32629016712222016034323"},{"sender":"ll","message":"blahblahblah","timestamp":"2016-12-21 14:43:47","username":"","msgtype":"","threadid":"32629016712222016034323"}],{"sender":"ll","message":"blahblahblahblah","timestamp":"2016-12-21 14:43:04","username":"","msgtype":"","threadid":"92337321312222016034304"},{"sender":"kk","message":"blahblahblahblahblah","timestamp":"2016-12-21 14:44:05","username":"","msgtype":"","threadid":"92337321312222016034304"}]
How do I proceed to get the right result here?
$data = array ();
foreach($threads as $threadid){
$sql = ("SELECT sender,message,timestamp,username,msgtype,threadid FROM Messages WHERE threadid = '$threadid' AND subject = '' AND timestamp > '$newtimestamp' ORDER BY timestamp");
$arrayOfObjects = $conn->query($sql)->fetchAll(PDO::FETCH_OBJ);
$data[] = $$arrayOfObjects;
}
And FYI, $threadid is another array containing... threadids, and the loop correctly fetches these one by one, that´s not where the problem is.
Thanks in advance!!
You are doing O(N) database queries, consider doing just O(1) using an IN expression in your where clause. No need for a foreach loop and you'll get all your data in one array.
SELECT ... FROM Messages WHERE threadid IN (1, 2, 3, ...) AND ...
You might have to use a prepared statement for that.
I think you are searching for PDO::FETCH_OBJ.
You had FETCH_ASSOC, which will return an array of associative arrays.
FETCH_OBJwill return an array ob stdObjects.
Also you reassigned $array to itself when doing $array[] = $array;..
$data = array();
foreach($threads as $threadid){
$sql = ("SELECT sender,message,timestamp,username,msgtype,threadid FROM Messages WHERE threadid = '$threadid' AND subject = '' AND timestamp > '$newtimestamp' ORDER BY timestamp");
// here it is:
$arrayOfObjects = $conn->query($sql)->fetchAll(PDO::FETCH_OBJ);
$data[] = $arrayOfObjects;
}
// now you can encode that as json and show it:
echo json_encode($data);
#akuhn
Well, I decided to give your suggestion one more try, and managed to do it in a none prepared way. I´m aware that this is supposed to be risky, but so far this project just needs to work, then have the php codes updated to safer versions, and then go live. It works, so thanks a bunch!
$sql = ("SELECT sender,message,timestamp,username,msgtype,threadid FROM Messages WHERE threadid IN ('" . implode("','",$threadid) . "') AND subject = '' AND timestamp > '$newtimestamp' ORDER BY timestamp");
$data = $conn->query($sql)->fetchAll(PDO::FETCH_OBJ);
I have a file file.php and inside my file I am using the code bellow to pull some data from my database and display some information.
My code is
$array = $_GET['theurl']; // My url looks like myfile.php?theurl=1,2,3 (id,s)
$sqlnt4 = "select * from mytable WHERE `id` IN ($array)";
$rsdt4 = mysql_query($sql);
$tc4a = mysql_fetch_assoc($rsdt4);
$mycomma4 = ",";
if ($tc4a['a_youtube'] == "#"){
}else{
while ($tc4 = mysql_fetch_assoc($rsdt4))
{
echo $tc4['a_youtube'];
echo ",";
}
}
I expect to echo the infos of the two id's (in array) inside my while function, but it returns the results only from the first.
Any ideas?
I am confusing on $sql :
$sqlnt4 = "select * from mytable WHERE `id` IN ($array)";
$rsdt4 = mysql_query($sql);
Can you take a look after changing below:
$sqlnt4 = "select * from mytable WHERE `id` IN ($array)";
$rsdt4 = mysql_query($sqlnt4);
First that's extremely vulnerable to security issues - I hope this isn't used in production and just for playing around.
I recommend switching to PDO, or at the very least securing your variables.
To put that array into the query, you need to implode it into a list, as such.
$list = implode(',', $array);
You can then use the list in the statement, which will look like 1,2,3.
Edit:
I've just realized your $array value isn't actually an array - have you missed code out or is it badly named?
mysql_fetch_assoc: "Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead." http://pt2.php.net/mysql_fetch_assoc
Try mysql_fetch_rows to return all matching rows into an array.
I'm trying to create a while loop in PHP which retrieves data from a database and puts it into an array. This while loop should only work until the array its filling contains a certain value.
Is there a way to scan through the array and look for the value while the loop is still busy?
to put it bluntly;
$array = array();
$sql = mysql_query("SELECT * FROM table");
while($row = mysql_fetch_array($sql)){
//Do stuff
//add it to the array
while($array !=) //<-- I need to check the array here
}
You can use in_array function and break statement to check if value is in array and then stop looping.
First off, I think it'd be easier to check what you're filling the array with instead of checking the array itself. As the filled array grows, searching it will take longer and longer. Insted, consider:
$array = array_merge($array, $row);
if (in_array('ThisisWhatIneed', $row)
{
break;//leaves the while-loop
}
However, if you're query is returning more data, consider changing it to return what you need, only process the data that needs to be processed, otherwise, you might as well end up with code that does something like:
$stmt = $db->query('SELECT * FROM tbl');
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
if ($row['dataField'] === 'username')
{
$user = $row;
break;
}
}
WHERE could help a lot here, don't you think? As well taking advantage of MySQL's specific SELECT syntax, as in SELECT fields, you, need FROM table, which is more efficient.
You may also have noticed that the code above uses PDO, not mysql_*. Why? Simply because the mysql_* extension Is deprecated and should not be used anymore
Read what the red-warning-boxes tell you on every mysql* page. They're not just there to add some colour, and to liven things up. They are genuine wanrings.
Why don't you just check each value when it gets inserted into the array? It is much more efficient than iterating over the whole array each time you want to check.
$array = array();
$stopValue = ...
$sql = mysql_query("SELECT * FROM table");
while($row = mysql_fetch_assoc($sql)){
array_push($array,$row['column']);
if($row['column'] == $stopValue){
// The array now contains the stop value
break;
}
I'm selecting a single column from a MySQL table with mysql_query(). Is there already a function for getting the results into an array, or will I have to iterate through all the results with something like mysql_fetch_array()?
You have to iterate.
If you moved into the 21st century, and used mysqli, there's a mysqli_fetch_all() function.... and you'd be able to use prepared statements
you can do this with mysqli_fetch_all and array_column
$r = mysqli_query($c,"SELECT bug_name FROM bugs WHERE color='red'");
$bug_names = array_column(mysqli_fetch_all($r,MYSQLI_ASSOC),"bug_name");
Nothing like that built in, you will need to do this manually.
you can use mysql_result function still need to do some coding
mysql_result($result,$row_num,$fieldname) ;
retrieves $row_num 'th columes $field_name field .
and following snippet can be taken as an example
$con =mysql_connect($host,$uname,$passwd);
mysql_select_db($dbname,$con);
$result = mysql_query($query,$con);
$arr = array();
$numrows = mysql_num_rows($result);
for($i=0;$i<$numrows;$i++) {
$arr[] = mysql_result($result,$i,$fieldname);
}
this stores every elements of column $fieldname to
array $arr
can any one know the, convert mysql query in to an php array:
this is mysql query :
SELECT SUM(time_spent) AS sumtime, title, url
FROM library
WHERE delete_status = 0
GROUP BY url_id
ORDER BY sumtime DESC
I want to convert this query in to simple php array .
So, you need to get data out of MySQL. The best way, hands down, to fetch data from MySQL using PHP is PDO, a cross-database access interface.
So, first let's connect.
// Let's make sure that any errors cause an Exception.
// <http://www.php.net/manual/en/pdo.error-handling.php>
PDO::setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// We need some credentials...
$user = 'username';
$pass = 'password';
$host = 'hostname';
$dbname = 'database';
// PDO wants a "data source name," made up of those credentials.
// <http://www.php.net/manual/en/ref.pdo-mysql.connection.php>
$dsn = "mysql:host={$host};dbname={$dbname}";
$pdo = new PDO($dsn, $user, $pass);
There, we've connected. Let's pretend that $sql has the SQL you provided in your question. Let's run the SQL:
$statement = $pdo->prepare($sql);
$statement->execute();
There, it's been executed. Let's talk about results. You steadfastly refuse to tell us how you want your data structured, so let's go through four ways that you could get your data.
Let's first assume that the query returns a single row. If you want a numerically indexed array, you would do this:
// <http://www.php.net/manual/en/pdostatement.fetch.php>
$array = $statement->fetch(PDO::FETCH_NUM);
unset($statement);
If you want an associative array with the column names as the keys, you would do this:
$array = $statement->fetch(PDO::FETCH_ASSOC);
unset($statement);
Now, what if the query returns more than one record? If we want each row in a numerically indexed array, with each row as an associative array, we would do this:
// <http://www.php.net/manual/en/pdostatement.fetchall.php>
$array = $statement->fetchAll(PDO::FETCH_ASSOC);
unset($statement);
What if we want each row as a numerically indexed array instead? Can you guess?
$array = $statement->fetchAll(PDO::FETCH_NUM);
unset($statement);
Tada. You now know how to query MySQL using the modern PDO interface and get your results as no less than four types of array. There's a tremendous number of other cool things that you can do in PDO with very minimal effort. Just follow the links to the manual pages, which I have quite intentionally not linked for you.
This over-the-top post has been brought to you by the letters T, F and W, and the number PHP_MAX_INT + 1.
i don't get you clearly, but
mysql_fetch_array and mysql_fetch_assoc
both returns only array
please refer:-
http://php.net/manual/en/function.mysql-fetch-array.php
http://php.net/manual/en/function.mysql-fetch-assoc.php
If you just need a simple array...
while ($row = mysql_fetch_array($query)) { //you can assume rest of the code, right?
$result[$row['url_id']] = array($row['sumtime']);
}
For a simple array
$sql = mysql_query("SELECT SUM(time_spent) AS sumtime, title, url
FROM library
WHERE delete_status = 0
GROUP BY url_id
ORDER BY sumtime DESC");
while($row = mysql_fetch_array($sql)){
$array1 = $row['sumtime'];
$array2 = $row['title'];
$array3 = $row['url'];
}
Hope this is one you wanted
Dude the fastest way is probably the following
$data = array();
while($row = mysql_fetch_array($result))
{
$data[] = $row;
}
print_r($data);