I am trying to update one row in my database like this.
if (isset($_POST['submit'])) {
$sizes = array($_POST['size_king'],
$_POST['size_queen'],
$_POST['size_double']
);
mysqli_query($con, "UPDATE beds
SET `Available Sizes` = '$sizes'
WHERE ID = '$prod_id' "
);
}
Can anyone please help me?
I want this data to only update one row, and the data must be separated by a comma.
I am thinking maybe a FOR loop, but I'm not quite sure.
just use implode() function .
if (isset($_POST['submit'])) {
$sizes = array($_POST['size_king'],
$_POST['size_queen'],
$_POST['size_double']
);
$sizes=implode(",",$sizes);
mysqli_query($con, "UPDATE beds
SET `Available Sizes` = '$sizes'
WHERE ID = '$prod_id' "
);
}
The PHP implode function will serve your purpose.
implode joins array elements into a string separated by the glue we specify. The syntax is:
string implode ( string $glue , array $pieces )
Refer to: http://in3.php.net/manual/en/function.implode.php
Example:
<?php
$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);
echo $comma_separated; // lastname,email,phone
// Empty string when using an empty array:
var_dump(implode('hello', array())); // string(0) ""
?>
there is a catch when you create database never name your table as "Available Beds" i mean don't use space try using "AvailabaleSizes" or Available_Sizes or "availableSizes" after this change write your query like below.
($con, "UPDATE `beds` SET Available_Sizes = '$sizes' WHERE ID = '$prod_id'");
Related
I have the array-ed session....
$_SESSION['Names'] = array (11,15,26);
$_SESSION['Location'] = array (35,42,10);
and I want to store them in my database...
$que = "Insert into tblpeople (DateTimePosted, first, second, third) VALUES(now(),'$_SESSION['Names'][0], $_SESSION['Location'][0])','$_SESSION['Names'][1], $_SESSION['Location'][1])','$_SESSION['Names'][2], $_SESSION['Location'][2])')";
$exec = mysql_query($que);
After Saving, my database (tblpeople) shows the following values:
DateTimePosted: 2014-01-03 16:23:02
first: Array[0],Array[0]
second: Array[1],Array[1]
third: Array[2],Array[2]
Instead, I want my output to be...
DateTimePosted: 2014-01-03 16:23:02
first: 11,35
second: 15,42
third: 26,10
What's wrong?
To expand multidimensional arrays in a string, you need to wrap them in curly braces:
$que = "Insert into tblpeople (DateTimePosted, first, second, third)
VALUES(now(),
'{$_SESSION['Names'][0]}, {$_SESSION['Location'][0]}',
'{$_SESSION['Names'][1]}, {$_SESSION['Location'][1]}',
'{$_SESSION['Names'][2]}, {$_SESSION['Location'][2]}')";
You also had some extra parentheses in the values.
However, this seems like a pretty strange way to store data into a database. Why do you have two values separated by commas in each column, rather than splitting each into separate columns? And why are you storing array elements into different columns, rather than using separate tables with each value in a row?
use this function
$x=serialize($_SESSION['Names']);
it return a string that you can save any where
and this function reverse it
$_SESSION['Names']=unserialize($x);
Try this
<?php
session_start();
$_SESSION['Names'] = array (11,15,26);
$_SESSION['Location'] = array (35,42,10);
$refNumbers = $_SESSION['Names'];
$partIds = $_SESSION['Location'];
$combined = array();
foreach($refNumbers as $index => $refNumber) {
if(!array_key_exists($index, $partIds)) {
throw OutOfBoundsException();
}
$combined[] = array(
'Names' => $refNumber,
'Location' => $partIds[$index]
);
}
print_r($combined);
$combine1 = implode(",",$combined[0]);
$combine2 = implode(",",$combined[1]);
$combine3 = implode(",",$combined[2]);
$que = "insert into tblpeople (DateTimePosted, first, second, third) VALUES(now(),'$combine1','$combine2','$combine3')";
//$exec = mysql_query($que);
?>
I am trying to create functions to run mysql queries
How would I do things like insert queries. I was thinking
function insert_query ($table,$cols,$values)
{
$sql="insert into $table ($cols) values ($values) "; ...etc
}
With the rest of the query code in the function. But how would I add multiple columns and values?
Should I make $cols and $values An array inside the function?
This is a function of my Database Class.
public function insert($table,$values){
$fieldNames = "";
$fieldValues = "";
foreach($values as $key => $value){
$fieldNames .= "$key,";
$fieldValues .= "$value,";
}
$fieldNames = substr($fieldNames,0,-1);
$fieldValues = substr($fieldValues,0,-1);
$sql = "INSERT INTO $table($fieldNames) VALUES ($fieldValues)";
$this->newConnection();
$result = $this->mysqli->query($sql);
$this->closeConnection();
return $result;
}
Here is what I'm using. Pass field name and Value as Array key and value. $lsQry is an array of field name & value pair
function insert_record($table,$lsQry)
{
$fields_str = implode(',',array_keys($lsQry));
$data_str = implode("','",$lsQry);
$data_str = "'" . implode("','", $lsQry) . "'";
$lsQry = "INSERT INTO $table($fields_str) VALUES($data_str)";
$rs = mysql_query($lsQry);
if(isset($rs))
return true;
else
return false;
}
Please Note
For this function, do consider that function is getting an array of fields name and value pair. It is assumed that htmlentities() and addslashes() or any escaping functions are already applied while creating array from post/get values.
Easy, just us arrays
function insert_query ($table,$cols,$values){
$sql="insert into $table (".implode(",", $cols).") values (".implode("','", $values)."'') ";
}
insert_query('exampleTable', array('column_1', 'column_2', 'column_3'), array('a', 123, 'c') );
The implode for the values requires a small sidenote:
Strings always required being wrapped in quotes. Therefor I made the implode with single qoutes. The downside to this is that integets (like 123 in the example) also get wrapped.
This is not a big problem, but if you want you could replace the implode with a foreach that uses is_numeric to check wether it should be wrapped in quotes.
IMPORTANT SECURITY NOTE:
In this example I havent used proper seurity, like escape_string(), this has to be added! I've not added thos to keep the examples smaller
Another approach could be key/value-usage of an array:
function insert_query ($table,$data){
$cols = array_keys($data);
$values = array_values($data);
$sql = "insert into $table (".implode(",", $cols).") values (".implode("','", $values)."'') ";
}
$info = array('column_1'=>'a', 'column_2'=>123, 'column_3'=>'c');
$info['example'] = 'Easy method to add more key/values';
insert_query('tableName', $info);
In this case you can use functions similar to codeigniter functions.
Use arrays to store table name and columns or values
For example:
$data = array('hid' => $hcsdate,'start_date' => $sdate, 'end_date' => $edate, 'title' =>$title);
Here $data holds the column name and corresponding values.
And pass this $data to another functions for insert, update etc..
I have this sql query that returns no result. The table it queries has data but no results being pull. The query is put into an array.
$qry = array();
$qry[] = "SELECT events_id as 'Reference ID', event_level as 'Level', events_date as 'Date', events_time as 'Time', events_opponent as 'Opponent', events_place as 'Place', events_results as 'Results'";
$qry[] = "FROM wp_events WHERE events_id = ".$sched_id."";
$val = array();
$val = implode(" ", $qry);
$result = $wpdb->get_results($val, ARRAY_A);
i var_dump the $result but it only output Array ( ). I also tried to var_dump($val) if there is something wrong on the query but query is ok. I don't know what im missing here. please help.
There are two points in this code which can remain problematic:
Do you always have the $sched_id filled?
Does passing a complete query string to the $wpdb->get_results() return anything?
Try doing a fully complete query in phpMyAdmin to see the expected result and work the PHP code until you have the same results back.
try something like this if u want to print variable values..
<?php
$id = $_GET['value'];//value received from array[]
$N = count($id);
for($i=0; $i <N; $i++)
{
$result_h = mysql_query("SELECT * FROM `table` where id='$id[$i]'");
$pks_h = mysql_fetch_array($result_h);
echo $pks_h['mysql coloumn name'];
}
?>
or use while loop if u want to print only mysql table value.
I want to explode an array, read each value and print them back in an array...
I dont understand where i am getting wrong. Please help me..this is my code..
I am getting an array to string conversion error
$query="SELECT categories FROM shops";
$result = mysql_query($query);
while($column = mysql_fetch_assoc($result)){
$categories=explode(",",$column['categories']);
foreach($categories as $value){
$new_query="SELECT name from categories where id='$value'";
$name = mysql_query($new_query);
$name_column= mysql_fetch_assoc($name);
array_push($shops_list,$name_column);
}
}
echo implode(",",$shops_list);
$shop_list is not defined, before using it in this line array_push($shops_list,$name_column);. And, this line
array_push($shops_list,$name_column);
needs to be, as you need to mention the key name,
array_push($shops_list,$name_column['name']); //or better
$shop_list[] = $name_column['name'];
Several issues:
$name_column = mysql_fetch_assoc($name);
$name_column = $name_column['name'];
name_column is an array.
shops_list is never initialized.
You should use [] instead of array_push.
The other guys hit it on the nose, but when you did your array push on $name_column, since $name_column is an array, you end up with:
Array
(
[0] => Array
(
[name] => boo
)
)
Obviously doing an implode on that is going to not work.
That being said, what you really need to do here is not keep your category mappings as a comma delimited string in the database. Standard DB architecture dictates you use a mapping table.
Table shops
Table categories
Table shop_category_map that has shop_id and category_id
use group_concat to retrieve values. and after getting the result, use them directly for searching. like
$result_array = explode(",",$row['category']);
foreach($result_array as $ra)
{
//sql command. fetch here.
$new_query="SELECT name from categories where id='$value'";
$name = mysql_query($new_query);
$name_column= mysql_fetch_assoc($name);
$shops_list[] = $name_column;
}
try else go for better solution
// explode an array and then implode until a particular index of an array
$a = '192.168.3.250';
$b = explode('.',$a);
$ar = array();
for($i=0;$i<=2;$i++)
{
array_push($ar,$b[$i]);
}
$C = implode($ar,'.');
print_r($C);
The following is the query that I'm trying to get to work.
$array = array();
SELECT * FROM ENTRIES
WHERE
entry_id = '12'
OR
entry_id_extra IN ('$array')
This is of course simplified. The problem is that it works great if the array has items and it returns everything fine. But if the array has no item it fails to work.
What is the correct way to construct this statement that doesn't break if there are no items in the array? I tried IN ('NULL','$array') but that didnt work.
Any help is appreciated.
You can make the OR portion of the where clause go through a conditional check:
$sql = "SELECT * FROM entries WHERE entry_id = 12"
if (count($array) > 0) {
$sql .= ' OR entry_id_extra IN ($array)';
}
$array = array(...);
$array = array_map('mysql_escape_string', $array); // make sure it's safe
$query = "SELECT *
FROM entries
WHERE entry_id = '12'"
. (count($array) > 0
? " OR entry_id_extra IN ('" . implode("','", $array) . "')"
: "");
// echo the query to see what it looks like (optional)
echo "<pre>{$query}</pre>";
You can use implode, but also make sure you escape the values so quotes don't set the query off.