I'm having trouble getting the value out of an array
Array
(
[0] => id
[column_name] => id
)
Array
(
[0] => businessType
[column_name] => businessType
)
Array
(
[0] => name
[column_name] => name
)
Array
(
[0] => city
[column_name] => city
)
...
I'm getting those values from
mysql_query("
SELECT column_name
FROM information_schema.columns
WHERE table_name='businessUpgrade'
")
And in my while loop
while($row = mysql_fetch_array($result)){
while($column = mysql_fetch_array($colName)){
if($row[$i] == 1){
//here comes the missing part
}
$i++;
}
}
I tried diffrent things, but according to print_r, the values I need to get have the same number of id (0). Is there any way, I can get the values out of this array.
I found that I should do it with foreach, but somehow everything I try it fails.
There is no need to use 2 while loops.
The $row array is an associative array, so you can use...
$columns = array();
// {query}
while($row = mysql_fetch_array($result)) {
$columns[] = $row['column_name'];
}
var_dump($columns);
Your $columns array now contains an index of all the columns. It's a zero-index, so these can be pulled individually using:
echo $columns[0]; // The first column from the query "id"
echo $columns[2]; // The third column from the query "name"
You can also loop this array as needed.
foreach ($columns as $id => $column) {
if ($id == 0) {
// Do something with the first column:
echo $column;
} elseif ($id == 2) {
// Do something with the third column:
echo $column;
}
}
try this
$res = mysql_query("
SELECT column_name
FROM information_schema.columns
WHERE table_name='businessUpgrade'
");
while($r = mysql_fetch_row($res)){
$arr[]=$r;
}
NOTE . do not use mysql. Try mysqli or PDO instead.
And with this:
while($row = mysql_fetch_array($result)){
while($column = mysql_fetch_assoc($colName)){
if(($column['0'] == $row[$i]) && ($row[$i] == 1)){
//something like this???
}
}
$i++;
}
Your question is a bit messy XD.....i hope this helps anyway.
Related
I am having some trouble trying to get this done. The issue is:
I have an array that looks like
wants_arr_flat ( [0] => booze [1] => nudes [2]
=> rooms
I want my foreach loop to go through these values making a different SQL statement and then saving the result of that SQL statement on to another array. The code I am trying to work with now is this.
foreach ( $wants_arr_flat as $value ) {
$sql = "SELECT * FROM offers WHERE user_id != $_SESSION[user_id] AND offer='$value'";
$result=$conn->query($sql);
$want_match_arr = mysqli_fetch_row($result);
echo '<pre>'; print_r($want_match_arr); echo '</pre>'; //testing echo
Obviously this is just overwriting the last array each iteration so I only end up with one result in the array.
instead of
$want_match_arr = mysqli_fetch_row($result);
use
$want_match_arr[] = mysqli_fetch_row($result);
If you get multiple rows from SQL then this is better.
$want_match_arr = [];
foreach ( $wants_arr_flat as $value ) {
$sql = "SELECT * FROM offers WHERE user_id != $_SESSION[user_id] AND offer='$value'";
$result=$conn->query($sql);
while ($row = mysql_fetch_assoc($result)) {
$want_match_arr[] = $row;
}
}
echo '<pre>'; print_r($want_match_arr); echo '</pre>'; //testing echo
How do I use REGEXP to fetch multiple data from the array $vall.
I referred a sample code from:
PHP sql statement where clause to multiple array values
Some of the sample data: CGCG-0025-0,CGCR-0003-0,CGRQ-0163-0
foreach ($list as $value) // this $list is from another array
{
$part = $value[3];
$vall[] = $value[3]; // $list1 is an empty array
}
$partnumber =[];
foreach($vall as $v)
{
$partnumber[] = "*.".$v.".*";
print_r(array_values($partnumber)); // these are some of the values Array ( [0] => *.CGCG-0025-0.* ) Array ( [0] => *.CGCG-0025-0.* [1] => *.CGCG-0025-0.* ) Array ( [0] => *.CGCG-0025-0.* [1] => *.CGCG-0025-0.* [2] => *.CGCR-0003-0.* )
}
foreach($partnumber as $x)
{
echo '<br>'.$partnumber; // shows 'Array' on each lines
}
$fsql="select * from Error where RptDatime = 201706091000 and partnumber REGEXP '".implode("|",$partnumber)."'";
//example 1 $fsql="select * from MPdError where RptDatime = 201706091000 and partnumber = ('CGRQ-0057-0') ";
//example 1 shows the correct data but i need multiple partnumber
$getResults = $conn->prepare($fsql);
$getResults->execute();
$results = $getResults->fetchAll(PDO::FETCH_BOTH);
foreach($results as $row)
{
$mac = $row['Machine'];
$id = $row['Id'];
echo '<br><br><br>ID:'.$id.'<br>Machine Number :'.$mac;
}
Though this may not be a good solution as it contains a huge security risk, I will still post it based on what is needed above.
REGEXP is not needed for data that are not complex in design.
$fsql = "select * from Error where RptDatime = 201706091000 and partnumber in ('" . implode("','", $vall) . "');"
I am querying the DB successfully using an array and I am getting the correct result. But I am having difficulty using the results because of the way the array is created.
Here is the OUTPUT:
Array (
[0] => Array (
[0] => Array (
[0] => 1#1.1
)
[1] => 2#2.2
)
[2] => 3#3.3
)
Here is how the code is generated:
$owners_string = $row['profile_id'];
$owners_stringd = unserialize($owners_string);
foreach ($owners_stringd as $profileid => $valuee) {
if ($valuee) {
$sql = "select email from {$mysql_tbl_pre}profile where profile_id = '$valuee' ";
$err = mysqli_query($estate_db, $sql);
if (!$err)
error_dlg(mysqli_error($estate_db));
elseif (mysqli_num_rows($err) <= 0)
info_dlg("Error");
while ($row = mysqli_fetch_array($err))
$new_array[$profileid] = $row['email'];
$new_array = array($new_array);
foreach ($new_array as $emailvalue)
$emailsd = print_r($emailvalue, true);
} else {
$emailsd = "";
}
}
I know how to implode the results, but when i do implode this result, is comes out as "Array, 1#1.1" (which ever email was last).
I need it to be one entire result such as 1#1.1,2#2.2,3#3.3
These are two separate Tables. The first Tables stores a string of Ids that, the second Tables has each Id in its own row with an email in a separate column.
Solution from the while loop:
while ($thisemail = mysqli_fetch_array($rsz)) {
$emailsd .= $thisemail['email'] . ',';
}
foreach ($emailsd as $emailvalue)
$email = print_r($emailvalue, true);
Hello i have a dynamic form that can change field names upon user selection. i would like for the form result to be inserted into one mysql row.. i create an array as follows:
<?php
include_once 'dbconnect.php';
if (isset($_POST['item_name'])) {
$table = $_POST['ItemTypeSelect'];
foreach ($_POST as $key => $variable) {
$chesckColumn = mysql_query("SELECT `$key` from $table");
if (!$chesckColumn) {
echo "column ".$key." does not exist <br/>";
}else{
$results = $variable;
$columnName = $key;
$array[] = array($columnName => $results);
}
}
mysql_query("INSERT INTO $table (`$columnName`) VALUES ('$results') ")or die(mysql_error());
}
?>
my array result are
(
[0] => Array
(
[Server_id] =>
)
[1] => Array
(
[Server_IP_Address] => 12345
)
[2] => Array
(
[Server_IP] => 12345
)
[3] => Array
(
[Server_Name] => dad
)
)
How can i have the array be inserted in one table row and reference the $results and the field value and $columnName as the field value.
You could use a few php built in functions:
function put_quotes(&$item){
$item = "'$item'";
}
$columns = implode(",",array_walk(array_keys($_POST),'put_quotes'));
$values = implode(",",array_walk(array_values($_POST),'put_quotes'));
mysql_query("INSERT INTO $table (columns) VALUES ($values) ")or die(mysql_error());
Where :
array_walk executes a function over all array, here put quotes over the item.
array_keys gets the keys from an array
array_values gets the values from an array
implode joins an array to a string with a separator
Use PDO because mysql_* functions are depreceated.
Connect to MySQL in PDO :
$db="database";
$host="127.0.0.1";
$usr="username";
$pass="password";
$dbh=new PDO("mysql:dbname=$db;host=$host", $usr, $pass);
First convert the array to JSON and save it on the table :
$json=json_encode($array);
$sql=$dbh->prepare("INSERT INTO ? (?) VALUES (?)");
$sql->execute(array($table,$columnName,$json));
If you want to retrieve the array back, decode the JSON data got from table:
$sql=$dbh->prepare("SELECT ? FROM ?");
$sql->execute(array($columnName,$table));
while($r=$sql->fetch()){
$array=json_decode($r[$columnName],true);
print_r($array);
}
Have a PHP factory with a sub class that queries either one or more unrelated tables in a database. The class takes a table name as a parameter and returns an array object.
When more than one table is required, I would like a way to delimit each tables result set in to its own array. The class would then return a multi-dim array.
I would prefer to not instantiate another instance of the factory. Here is the current query/result code block. I've left out all the other non-essential code for brevity
// if array has more than one table to query,
// run queries on each table
$count = count($tname);
if ($count>1) {
foreach ($tname as $value) { //each table name in array
/* $query = "SELECT s.* FROM $value s"; tried with table alias */
$query = "SELECT * FROM $value";
if ($stmt = self::$_conn->prepare($query)) {
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$result[] = $row;
}
} else {
return false;
}
}
return $result;
// else if only one table to query
} else {
$string = $tname; //table name
$query = "SELECT * FROM $string";
if ($stmt = self::$_conn->prepare($query)) {
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$result[] = $row;
}
return $result;
} else {
return false;
}
}
With more than one table, would return something like:
Array
(
[0] => Array
(
[team_id] => 3
[team_name] => Maverics
)
[1] => Array
(
[team_id] => 4
[team_name] => Stallions
)
[3] => Array
(
[fld_id] => 1
[fld_name] => 6v6-1
)
[4] => Array
(
[fld_id] => 2
[fld_name] => 8v8-2
)
)
Where 0,1 are from one table and 3,4 are from another.
Thank you in advance
Figured it out... Simple actually, just didn't see it before I asked the questions. I changed:
$result[] = $row;
to
$result[$value][] = $row; //line 11 in code block example
This now returns the array with each table name as the array name for the result set.
Thanks anyway,