To get an array like this array("123","456","789"); I use the code:
$Regids = mysql_query("SELECT regid FROM $tabel WHERE active = '1'");
while($row = mysql_fetch_array($Regids))
{
$result_array[] = "\"".$row['regid']."\"";
}
$regIDs = implode(',', $result_array);
$registrationIDs = array($regIDs); // array("123","456","789");
but I would expect PHP/mySQL has a simpler/faster solution for this?
I doubt that your code produces the result you want.
// assuming the this query produces 123,456,789
$Regids = mysql_query("SELECT regid FROM $tabel WHERE active = '1'");
// $row contains: array("123")
while($row = mysql_fetch_array($Regids))
{
$result_array[] = "\"".$row['regid']."\"";
}
// $result_array now contains: array("\"123\"", "\"456\"", "\"798\"");
$regIDs = implode(',', $result_array);
// $regIDS now contains a single string: "\"123\",\"456\",\"798\"";
$registrationIDs = array($regIDs);
// registrationIDs now is an array containing a single string: array("\"123\",\"456\",\"798\"");
If you really need an array that looks like this: array("123","456","789"); it is much simpler.
$Regids = mysql_query("SELECT regid FROM $tabel WHERE active = '1'");
while($row = mysql_fetch_array($Regids))
$registrationIDs[] = $row['regid'];
and that's all.
If your mysql result contains the number as an integer instead of an string you can convert it like this:
$Regids = mysql_query("SELECT regid FROM $tabel WHERE active = '1'");
while($row = mysql_fetch_array($Regids))
$registrationIDs[] = strval($row['regid']);
Also, keep in mind that the mysql_* functions are becoming deprecated. Don't start new code with it and make plans to port your existing code to mysqli_* or PDO.
You can use PDO implementation. At first sight, it may be more difficult to understand, but once you get used to it, it reveals to be really powerful and handy (IMHO! One year ago i switched to it and i love it)!
For your example, the PDO implementation would be like this:
/*CONNECT TO DB, FIRST. $dbh contains a handler to the current DB connection*/
$stmt = $dbh->prepare("SELECT regid FROM table WHERE active = '1'");
$stmt->execute();
$Regids = $stmt->fetchAll(PDO::FETCH_COLUMN,0);
There are many formatting options you can specify, like
PDO::FETCH_COLUMN
PDO::FETCH_ASSOC
and more...These options will allow you to get the array formatted as you prefer. As you can see i got the result in just 3 simple rows.
EDIT
Note: you are not escaping PHP variables before inserting them in your Query, and your code may suffer SQL INJECTION. Be careful!! Here is a simple guide to prevent it.
(In my code, just to be clear, i avoided the problem by just putting the table name instead of $table, just to show simply how to get the result you wanted.)
try this .. use Group concat in query ...
$Regids = mysql_fetch_array(mysql_query("SELECT GROUP_CONCAT(regid) as regids FROM $tabel WHERE active = '1'"));
echo $Regids[0]['regids']; // 123,456,789
for getting result "123","456","789" try this
$Regids = mysql_fetch_array(mysql_query("SELECT GROUP_CONCAT('\"',CONCAT(regid),'\"') as regids FROM $tabel WHERE active = '1'"));
echo $Regids[0]['regids']; // "123","456","789"
Related
I have a table in mysql called site_settings that looks like this
Table in PHPMyAdmin
I am trying to store all of my website settings in mysql and want to pull them into PHP as variables.
I want to pull all values from the variable_name column as the $variable names in PHP and have their values set to whats in the variable_type column.
$site_name = Vexed
$registration_enabled = False
here is my code:
$sql = connect($database_address, $database_username, $database_password, $database);
$query = "SELECT * FROM site_settings";
$result = $sql->query($query);
//$row = $result->fetch_all(MYSQLI_ASSOC);
while($row = $result->fetch_assoc())
{
$$row['variable_name'] = $row["variable_type"];
}
$arr = get_defined_vars();
print_r($arr);
the last two lines i am using to see if the variable have been created but i cant get it to work. the best result i have got so far is
[Array] => Array
(
[variable_name] => Vexed
)
Can anyone tell me where i am going wrong?
Thanks in advance to anyone who can help.
What you're trying to duplicate is PHP's extract() builtin function.
It's generally considered a bad practice, because it will make your code harder for readers to understand or debug.
What is so wrong with extract()?
How to demonstrate an exploit of extract($_POST)?
https://dzone.com/articles/php-bad-practice-use-extract
https://blog.josephscott.org/2009/02/05/i-dont-like-phps-extract-function/
What I think is happening is that when you call $$arr['variable_name'] it's actually doing $$arr first (which evaluates to $Array after the string conversion), and then trying to assign into assign the ['variable_name'] key into $Array.
I would expect this minor modification to work:
$sql = connect($database_address, $database_username, $database_password, $database);
$query = "SELECT * FROM site_settings";
$result = $sql->query($query);
//$row = $result->fetch_all(MYSQLI_ASSOC);
while($row = $result->fetch_assoc())
{
$name = $row['variable_name'];
$$name = $row["variable_type"];
}
$arr = get_defined_vars();
print_r($arr);
Edit: I'll also echo, that it's a little bit weird to dynamically create variables in this way and it will make your code hard to follow.
I'm working on a Kitchen Display Screen. I have it working if I know the order numbers. I'm trying to get all of the order numbers where status = "INQUEUE" and put those numbers into an array. The goal is to have a count of the total "INQUEUE" orders as well as have the segments on the screen only show arr[0]-Arr[4]. For some reason this section of code causes an error.
$status= "INQUEUE";
$arr = array();
$sql = "select ORDID from HEADERS where CurrentStatus=$status";
$result = mysql_query($sql) or die(mysql_error());
while( $row = mysql_fetch_assoc( $result ) ) {
$arr[] = $row[ORDID];
}
I'm hoping to grab all of the order numbers that have a status of "INQUEUE" into the array, so I can display the orders as arr[X]
What is the specific error you are receiving?
One thing that stands out on the query is the variable needs to be enclosed within single quotes so it looks like this:
$sql = "select ORDID from HEADERS where CurrentStatus='$status'";
Sometimes when I'm working with dynamically-built queries I like to echo out the query string so I can see exactly how it's being sent to the server.
Also, it's always a good idea to get in the habit of using prepared statements with parameterized queries when working with dynamically-built SQL queries.
Also, in agreement with ArtisticPhoenix, I recommend porting over to another library. Finally, make sure the array index descriptor is enclosed in double quotes. Here's your code using mysqli:
$link = mysqli_connect("dbserver", "user", "password", "database");
$status= "INQUEUE";
$arr = array();
$sql = "select ORDID from HEADERS where CurrentStatus='$status'";
$result = mysqli_query($link, $sql);
while( $row = mysqli_fetch_assoc($result)) {
$arr[] = $row["ORDID"];
}
I am new to PHP. I wanted to create a new record in another table but just one new variable gets returned. I've tried following:
$user_id = mysql_real_escape_string($_POST['user_id']);
$user_name = mysql_query("SELECT user_name FROM accept WHERE user_id=".$user_id." ");
$row1 = mysql_fetch_array($user_name);
$server = mysql_query("SELECT server FROM accept WHERE user_id=".$user_id." ");
$row2 = mysql_fetch_array($server);
$url = mysql_query("SELECT link FROM accept WHERE user_id=".$user_id."");
$row3 = mysql_fetch_array($url);
$lpoints = mysql_real_escape_string($_POST['lpoints']);
And my result is this.
First of all, combine your queries into one:
$user_id = mysql_real_escape_string($_POST['user_id']);
$user_info = mysql_query("SELECT user_name, server, link FROM accept WHERE user_id=".$user_id." ");
$row = mysql_fetch_array($user_info);
$lpoints = mysql_real_escape_string($_POST['lpoints']);
In order to create a new record, you will need INSERT INTO, to change existing records use UPDATE.
When you're fetching info from the database, it will be an array so you will need to use it accordingly. So essentially, to use the variables it will be like this:
$row['user_name'] or $row['server'] etc..
Also, look into using mysqli instead. You will need to change your connection script and some other syntax but it needs to be done. mysql is deprecated, insecure, and future support is not there so you will need to change it later anyway.
You should use pdo or mysqli and here is your code;
$user_id = &$_POST["user_id"];
if($user_id){
$result = mysql_query("select user_name,server,link,lpoints from accept where user_id='".mysql_real_escape_string($user_id)."'");
/*You should use single quotes for escaping sql injection*/
if($result){
$vars = mysql_fetch_array($result);
if($vars){
list($username,$server,$link,$lpoints) = $vars;
}
else{
//do something with errors
}
mysql_free_result($result);
}
else{
//do something with errors
}
}
else{
//do something with errors
}
Try This-
$user_id = mysql_real_escape_string($_POST['user_id']);
$result = mysql_query("SELECT user_name, server, link FROM accept WHERE user_id=".$user_id." ");
$row=mysql_fetch_array($result)
$row1=$row['user_name'];
$row2=$row['server'];
$row3=$row['link'];
$lpoints = mysql_real_escape_string($_POST['lpoints']);
Now you got what you wanted based on your requirement use the data to insert or update.
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);
I'm using PHP ADOdb and I can get the result set:
$result = &$db->Execute($query);
How do I get the field names from that one row and loop through it?
(I'm using access database if that matters.)
It will depend on your fetch mode - if you setFetchMode to ADODB_FETCH_NUM (probably the default) each row contains a flat array of columns. If you setFetchMode to ADODB_FETCH_ASSOC you get an associative array where you can access each value by a key. The following is taken from ADODB documentation - http://phplens.com/lens/adodb/docs-adodb.htm#ex1
$db->SetFetchMode(ADODB_FETCH_NUM);
$rs1 = $db->Execute('select * from table');
$db->SetFetchMode(ADODB_FETCH_ASSOC);
$rs2 = $db->Execute('select * from table');
print_r($rs1->fields); # shows array([0]=>'v0',[1] =>'v1')
print_r($rs2->fields); # shows array(['col1']=>'v0',['col2'] =>'v1')
To loop through a set of results:
$result = &$db->Execute($query);
foreach ($result as $row) {
print_r($row);
}
Small improvement to the solution posted by #thetaiko.
If you are ONLY needing the field names, append LIMIT 1 to the end of your select statement (as shown below). This will tell the server to send you a single row with column names, rather than sending you the entire table.
SELECT * FROM table LIMIT 1;
I'm working with a table that contains 9.1M records, so this minor change speeds up the query significantly!
This is a function I use to return a field array - I've stripped out some extra stuff that, for example, allows it to work with other DBs than MySQL.
function getFieldNames($strTable, $cn) {
$aRet = array();
# Get Field Names:
$lngCountFields = 0;
$strSQL = "SELECT * FROM $strTable LIMIT 1;";
$rs = $cn->Execute($strSQL)
or die("Error in query: \n$strSQL\n" . $cn->ErrorMsg());
if (!$rs->EOF) {
for ($i = 0; $i < $rs->FieldCount(); $i++) {
$fld = $rs->FetchField($i);
$aRet[$lngCountFields] = $fld->name;
$lngCountFields++;
}
}
$rs->Close();
$rs = null;
return $aRet;
}
Edit: just to point out that, as I say, I've stripped out some extra stuff, and the EOF check is therefore no longer necessary in the above, reduced version.
I initally tried to use MetaColumnNames, but it gave differing results in VisualPHPUnit and actual site, while running from the same server, so eventually
I ended up doing something like this:
$sql = "select column_name, column_key, column_default, data_type, table_name, table_schema from information_schema.columns";
$sql .= ' where table_name="'.$table.'" and table_schema="'.$database_name.'"';
$result = $conn->Execute($sql);
while($row = $result->fetchRow()) {
$out[] = strToUpper($row['column_name']);
}
I think it should work with mysql, mssql and postgres.
The benefit of doing it like this, is that you can get the column names, even if a query from a table returns an empty set.
If you need the Coloumn names even for empty tables or for joins about multiple tables use this:
$db->Execute("SELECT .......");
// FieldTypesArray - Reads ColoumnInfo from Result, even for Joins
$colInfo = $res->FieldTypesArray();
$colNames = array();
foreach($colInfo as $info) $colNames[] = $info->name;
The OP is asking for a list of fieldnames that would result of executing an sql statement stored in $query.
Using $result->fetchRow(), even with fetch mode set to associative, will return nothing if no records match the criteria set by $query. The $result->fields array would also be empty and would give no information for getting the fieldnames list.
Actually, we don't know what's inside the $query statement. Besides, setting limit to 1 may not compatible with all database drivers supported by PHP ADOdb.
Answer by Radon8472 is the right one, but the correct code could be:
$result = $db->Execute($query);
// FieldTypesArray - an array of ADOFieldObject Objects
// read from $result, even for empty sets or when
// using * as field list.
$colInfo = [];
if (is_subclass_of($result, 'ADORecordSet')){
foreach ($result->FieldTypesArray() as $info) {
$colInfo[] = $info->name;
}
}
I have the habit of checking the class name of $result, for as PHP ADOdb will return false if execution fails.