how to insert multiple of values in a single field in mysql - php

i want to insert multiple values into a single field, i don't know how to achieve this i'm using a long-text data type field. And also tell me how to fetch these a value only one separate value at a time.

Insert Mutliple values in a single Field:
For inserting the flat no's in a single field, use implode and the values separated by comma.
$r=implode(",",$available);
$insert=mysql_query("insert into flatdetails(available) value ('$r')")
For retrieve the values from database use, explode to separate out all the values..
For Retrieve the values using
$i=explode(",",$r);
<?php
$select_tbl=mysql_query("select * from flatdetails",$conn);
while($fetch=mysql_fetch_object($select_tbl))
{
$r=$fetch->available;
$i=explode(",",$r);
echo $i[0]."</br>";
}
?>

As far as my knowledge goes, MySQL does not have any data types that could help your use case. Well, actually it has a "set" data type, but it only allows for up to 60-something members if I recall correctly.
You can try using BLOB as your column type and store serialized data in there (i.e. JSON, protocol buffers).
However, I would recommend that you re-evaluate your DB's design. You're breaking the first normal form, and it's a sign that you're doing something wrong.

Use json_encode to encode the content and then store it in db field and when you retrieve the value then use json_decode ( Same like wordpress )

Its not a good idea to store multiple values into a single column. If you really want to do that store your strings as coma separated. And when reading back from database you can use php explode function. Php explode
I'll give you another option to store
Assume your strings are str1,str2,str3
First if you use your method it will be like below. which is not a good idea i think.
I think following is the good method

I think you should use Array and Implode functionality of PHP. Create an array and implode it by comma. For example---
Suppose you have three fields then get values of these input fields and make an array.
$arr = array(); // Declare an array
$arr[] = $_POST['FirstField'];
$arr[] = $_POST['SecondField'];
$arr[] = $_POST['ThirdField'];
// As more as you have input fields.
Then make it a string like
$insertValue = implode(',',$arr); // This will create a string containing all your fields values and you can save it in single field.
Just use this single variable in your insert query.
Hope this will help you.

db connect file with PDO save as config.php
<?php
$dbhost = 'localhost';
$dbname = 'clsrepair';
$dbuser = 'root';
$dbpass = '';
try {
$db = new PDO("mysql:host={$dbhost};dbname={$dbname}",$dbuser,$dbpass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Connection error: ".$e->getMessage();
}
?>
then in you desire file:
if(isset($_POST['your_form']))
{
try {
$leavingEquipment = implode(', ', $_POST['leavingEquipment']);
$statement = $db->prepare("INSERT INTO orderForm (orderNo,leavingEquipment) VALUES (?,?)");
$statement->execute(array($_POST['orderNo'],$leavingEquipment));
$success_message = "Order's has been inserted successfully.";
}
catch(Exception $e) {
$error_message = $e->getMessage();
}
}

try adding additional field to your apartmat table wher you writte for example 1 for rented (not available)
0 for available
query all apartments accordint to 0 and you got your list of all available appartments.

Related

Insert Json object to database in php

I am working on an android app which uses APIs made with php. Here, i am dynamically creating columns and their values.
I am verifying the API via postman and a strange thing happens every time, While looping through the Json Object what i am doing is first creating column and then inserting its values.
The problem is only the 1st iteration saves the element and rest of them only creates the column but does not insert the values. I don't know if i am doing anything wrong, below is my php code.
<?php
include("connection.php");
$data = file_get_contents('php://input');
$json_data = json_decode($data);
foreach($json_data as $key => $val) {
$column_name = $key ;
$c_column_name = preg_replace('/[^a-zA-Z]+/', '', $column_name);
$column_value = $val ;
$table_name = "test2";
$email = "ht#t.com";
$result = mysqli_query($conn,"SHOW COLUMNS FROM $table_name LIKE '$c_column_name'");
$exists = (mysqli_num_rows($result))?TRUE:FALSE;
if($exists) {
$query1 = "INSERT INTO $table_name($c_column_name)VALUES('$column_value') ";
$data0=mysqli_query($conn,$query);
if($data0)
{
echo json_encode(array("success"=>"true - insertion","message"=>"Column existed, Successfully data sent."));
}
else{
echo json_encode(array("success"=>"false - insertion","message"=>"Column existed, data not inserted."));
}
}
else{
$query2="ALTER TABLE $table_name ADD COLUMN `$c_column_name` varchar(50) NOT NULL";
$data1=mysqli_query($conn,$query2);
if($data1){
$query3="INSERT INTO $table_name($c_column_name)VALUES('$column_value')";
$data2=mysqli_query($conn,$query3);
if($data2)
{
echo json_encode(array("success"=>"true - insertion","message"=>"Successfully data sent."));
}
else{
echo json_encode(array("success"=>"false - insertion","message"=>"Column created but data not inserted."));
}
}
else
{
echo json_encode(array("success"=>"false - column creation","message"=>"Failed to create column.'$column_name', '$table_name', '$conn'"));
}
}
}
?>
Here is the Json Object through postman.
{"Shape":"rewq","Trans.No.":"yuuiop","Color":"qwert"}
Please help me with this, any help or suggestions are highly appreciated.
The second column name is Trans.No. which contains a dot, this is why it fails, probably you have an error as a result which prevents further columns from being created.
I think it would be much better to have a table with this structure:
attributes(id, key, value)
and whenever a key-value pair is received, you just insert/update it, depending on the logic you need to be executed. Your current model will create a separate row for each attribute, which is probably not what you want to achieve.
EDIT
Based on the information received in the comment section I reached the following conclusion:
You could create the missing columns first and then generate the insert statement with all the columns, having a single insert.
But it would be better to not create a separate column for each value, as the number of columns could quickly get out of hand. Instead you could have a table:
myentity(id, name)
for storing the entities represented by the JSON and
attributes(id, myentity_id, key, value)
for storing its attributes. This would be a neat schema with all the dinamicity you could want.

Can someone explain the principle behind this simple code please?

Im having difficulty comprehending a line of code that i am using to retrieve results from a mysql database.
I connect to the database with
<?php
try
{
$pdo = new PDO('mysql:host=localhost;dbname=****', '****',
'****');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('SET NAMES "utf8"');
}
catch (PDOException $e)
{
$error = 'Unable to connect to the database server.' . $e->getMessage;
echo $error;
exit();
}
this is fine. the connection works.
to retrive the results i use this code....
$sql = 'SELECT joketext FROM joke';
$results = $pdo->query($sql);
this also is fine but then i use a foreach loop to loop through the result set as so...
foreach ($results as $result){
$jokes[] = $result['joketext'];
}
and then another foreach to loop through $jokes as so...
foreach ($jokes as $joke) {
echo $joke;
}
now this all works it displays the joketext i wanted from the mysql table. However i dont understand the line...
$jokes[] = $result['joketext'];
does this means I am assigning the result set to an array? what does $jokes[]= mean? and why do i have to do this?
I thought i was retrieving strings of text from the database table. The table has an id, joketext, jokedate, and authorid as columns. But if im only selecting the joketext column surely that retrieves a list of all the joketext entries and therefore i can just loop through with a foreach echoing out the results?
The $jokes[] syntax is appending the joke text string to the $jokes array. If the array doesn't exist, it will be created.
It's the same as doing:
array_push($jokes, $result['joketext']);
If you don't need to create a new array, you can just work with the joke text directly in the $results foreach, if you prefer.
your query only selects for one column joketext so you don't have any of the other column data in your result set.
Using $jokes[] = .. is a shorthand way of assigning a value to a new element in the $jokes array. You don't necessarily need to do this. It is just commonly done so that you can use the data later on, in multiple places if you want. Alternatively, you can just work with the result set directly each time. That isn't as commonly done though since the result set is an object or resource that contains more than what you may actually need. But if you're just looking to output the joketext immediately, then you can skip putting it into a separate array and just echo $result['joketext']; in your first loop
$jokes[] = appends a new value to an array and is the same as doing $jokes[count($jokes)] (not completely correct but is a simple way of explaining it).
Technically, you don't have to put all the values in a new array, you could use the original loop instead.
array_push has the same functionality, you can read up about it here
If I understand you correctly then I believe you are correct. The second foreach is not needed, you can simply echo the $result['joketext'] during the first foreach and skip the second one altogether.
so delete the second foreach and edit the first one as follows:
foreach ($results as $result){
echo( $result['joketext'] );
}

Remove a loop to find existing numbers in database to one single query

I am sending an array of numbers separated by commans to server. Basically on server database I have a field that cotains numbers.Server side code checks which numbers are in database and send me the array of those numbers.
Following code is what I am using...
public function already_user()
{
$contacts=$this->input->post('contact');
//$contacts is an array.
$user= explode(',',$contacts);
foreach($user as $number)
{
$data = array (
'username' =>$number
);
$usernumber = $this->chat_model->get(array('username'=>$number)); // a simple query to datbase that check if number exists in database column or not.
if(!$usernumber==""){
$value[]=$usernumber;
}
}
echo json_encode($value);
}
Only drawback about this code is , its extremely slow.... If i have 1000+ numbers it takes a minute.since its a loop Is there any way to fasten this up. Any single mysql query??
Why don't you just write a single query? Parse the string to get an array and query the table in a single go.
$contact_array = array_map('trim', explode(', ', $contacts));
$all_usernumbers = $this->chat_model->get(array('username IN'=> $contact_array));
which should (depending of what your chat_model->get() accepts), translate to:
SELECT * FROM your_table WHERE username IN ('123', '345')
This is all pseudocode since I don't know what your framework accepts but the SQL query above should be valid.

Update Only Changed Values to Database

I have a form that I am trying to use to track batches of beer. Because the process of brewing takes several weeks or even months, I cannot complete the form all at once. When I first create a record for a beer, most of my values are set as NULL. When I retrieve the record and attempt to update it, it also updates all my NULL values to zeros. How can I send only changed values to the database from my form so the rest will be left as NULL?
Below is a sample of my update code (please forgive any PDO transgressions - it is my first foray into using PDO).
<?php
//Connect to Database
try {
$DBH = new PDO('mysql:host=localhost; dbname=dbname', 'user', 'password');
}
catch (PDOException $e) {
echo $e->getMessage();
exit();
}
//Build Update SQL Query
$update = "UPDATE brewlog
SET
BrewDate = :BrewDate,
EndOfPrimary = :EndOfPrimary,
EndOfSecondary = :EndOfSecondary,
PackagingDate = :PackagingDate,
AnticipatedOG = :AnticipatedOG,
WHERE ID = :ID";
//Prepare Query, Bind Parameters, Excute Query
$STH = $DBH->prepare($update);
$STH->bindParam(':ID', $_POST['ID'],PDO::PARAM_INT);
$STH->bindParam(':BrewDate', $_POST['BrewDate'],PDO::PARAM_STR,10);
$STH->bindParam(':EndOfPrimary', $_POST['EndOfPrimary'],PDO::PARAM_STR,10);
$STH->bindParam(':EndOfSecondary', $_POST['EndOfSecondary'],PDO::PARAM_STR,10);
$STH->bindParam(':PackagingDate', $_POST['PackagingDate'],PDO::PARAM_STR,10);
$STH->bindParam(':AnticipatedOG', $_POST['AnticipatedOG'],PDO::PARAM_INT);
$STH->execute();
?>
You would want to validate your data before you bind it. Say something like
if(!empty($_POST['EndOfPrimary'])) {
$eop = $_POST['EndOfPrimary'];
} else {
$eop = NULL;
}
Then bind
$STH->bindParam(':EndOfPrimary', $eop,PDO::PARAM_STR,10);
Edit:
You would also use this validation to check more than if the field was left blank. It looks like you probably want a date to be entered, so perhaps your would check if the user actually entered a date, and if not then send them back to the form with some type of helpful message about where they made the mistake. This is the regexp I use to validate a date.
function pcre_date($subject) {
return preg_match('/^[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}$/', $subject);
/*
* matches 01/01/1984, 1/1/1984, but NOT 1/1/84
* wants mm/dd/yyyy
*/
} // returns 0 for non valid, 1 for valid
Then I would use this for the validation
if(!empty($_POST['EndOfPrimary'])) {
if(pcre_date($_POST['EndOfPrimary'])) {
$eop = $_POST['EndOfPrimary'];
} else {
$form_errors[] = "Please format date as mm/dd/yyyy.";
}
} else {
$eop = NULL;
}
To accomplish this cleanly, use two steps:
In the form presented to the user, maintain a list of changed fields. For example, when a user modifies the data in an input field, use Javascript to copy the contents of that field into a hidden form to be submitted. Then when the user clicks "submit", send only the contents of the hidden form, not the contents of the original form with all fields.
In your PHP script, build your query based on the fields provided. Your query will now include only the fields that were modified. This way, when you perform your UPDATE statement, the unchanged fields will be untouched.
Sorry george, I guess you are way far complicated of what he is trying to do.
Actually, when you use _POST['somevar'], if the field is blank, you get and EMPTY string.
and the empty string is saved to the database so the field is not NULL anymore
The simplest way to ensure the fields stay NULL in the database if there is no value captured is:
$STH->bindParam(':EndOfPrimary', isset($_POST['EndOfPrimary'])?$_POST['EndOfPrimary']:null ,PDO::PARAM_STR,10);

can i insert a php array into a single mysql record field?

suppose we have a mysql table "table" with fields "user" "siblings" and we want to store this family info for every user.
is it possible to do this:
$user=35;
$sibs=array("george","christina");
mysql_query("insert into table (user,siblings) values ('$user','$sibs')");
so that field "siblings" contains an array?
You want to use PHP's serialize() function for this. To reverse the process, use unserialize()
Snippit from PHP.net:
<?php
// $session_data contains a multi-dimensional array with session
// information for the current user. We use serialize() to store
// it in a database at the end of the request.
$conn = odbc_connect("webdb", "php", "chicken");
$stmt = odbc_prepare($conn,
"UPDATE sessions SET data = ? WHERE id = ?");
$sqldata = array (serialize($session_data), $_SERVER['PHP_AUTH_USER']);
if (!odbc_execute($stmt, $sqldata)) {
$stmt = odbc_prepare($conn,
"INSERT INTO sessions (id, data) VALUES(?, ?)");
if (!odbc_execute($stmt, $sqldata)) {
/* Something went wrong.. */
}
}
?>
To build on #David Houde's answer from the post he refered to also use compression to save space (if useful to you):
<?php
mySerialize( $obj ) {
return base64_encode(gzcompress(serialize($obj)));
}
myUnserialize( $txt ) {
return unserialize(gzuncompress(base64_decode($txt)));
}
?>
You can use serialize http://ru2.php.net/manual/en/function.serialize.php
But it's really bad practice.
You can use implode() to add a divider between values. For example, you can use the pipe "|"
e.g.
$user=35;
$sibs=array("george","christina");
$sibs1 = ''.implode('|',$sibs).'|';
mysql_query("insert into table (user,siblings) values ('$user','$sibs1')");
When extracting information from the database use LIKE '%|$var|%' in your query to extaract the exact value. e.g. |Christina|
Yes, you can serialize() the array prior to inserting it, or implode() it with some kind of a separator of your choice for this, but I would recommend you just insert separate rows for each user->sibling relationship.

Categories