i have the mysql table 'persons' with 3 columns as,
Name Salary Profession
I am sending 3 parameters with values using php get method as,
$name = raj|lokesh|amar
$salary = 10000|20000|30000
$job = telecom|marine|shipyard
I have to insert them in 'persons' table as,
Name Salaray Profession
raj 10000 telecom
lokesh 20000 marine
amar 30000 shipyard
Can any one tell me how can i do this?
You can turn string into an array using the explode function.
You can surely use this in your case, using my little demonstration:
$name = "raj|lokesh|amar";
$salary = "10000|20000|30000";
$job = "telecom|marine|shipyard";
You just set the variables.
Now turn them into exploded arrays:
$name = explode("|", $name);
$salary = explode("|", $salary);
$job = explode("|", $job);
You basically want to get all of the words between the character | and turn each word into an array item, so each word will have it's own index.
now, $name[0] (the first array index),
echo $name[0]; // echoes 'raj'
echo $name[1]; // echoes lokesh'
echo $job[3]; // echoes 'shipyard';
And now you have to loop trough these arrays and insert it in the query:
for ($i = 0; $i < count($name); $i++) {
echo $name[$i];
}
So final solution will look like this:
for ($i = 0; $i < count($name); $i++) {
$query = $pdoObject->prepare("INSERT INTO table (name, salary, profession) VALUES (:name, :salary, :jobs)");
$query->execute(array(
":name" => $name[$i],
":salary" => $salary[$i],
":jobs" => $jobs[$i]
);
}
This is not a direct answer , since you haven't showed us any code.
Try something like this.
<?php
$name = "raj|lokesh|amar";
$salary = "10000|20000|30000";
$job = "telecom|marine|shipyard";
$name = explode("|",$name);
$salary=explode("|",$salary);
$job=explode("|",$job);
for($i=0;$i<count($name);$i++)
{
$q = mysql_query("INSERT INTO `yourtable` VALUES ('$name[$i]','$salary[$i]','$job[$i]')");
}
Try to use
$names = explode("|", $name);
$salaries = explode("|", $salary);
$professions = explode("|", $profession);
and then loop through the arrays ($names, $salaries, $professions) to insert the values in your database.
http://php.net/manual/fr/function.explode.php
Like this
INSERT INTO `persons`(`Name`, `Salaray`, `Profession`) values('raj', '10000','telecom'),('lokesh', '20000','marine'),('amar', '30000','30000')
//ASSIGN THE VARIABLES TO INSERT
$name= '';
$salary='';
$job='';
//INSERT DATA INTO DATABASE
$Input = mysql_query('INSERT INTO persons (name, salary, profession) VALUES ($name, $salary, $job)');
//SEARCH FOR PERSONS
$output= mysql_query('SELECT * FROM persons ORDER BY id ASC');
$personsCount = mysql_num_rows($output); //count output amount
//LOOP PERSONS OUTPUT
if($personsCount > 0){
while($row=mysql_fetch_array($output)){
$id = $row['id'];
$name = $row['name'];
$salary = $row['salary'];
$job = $row['job'];
$personsList .= $name.' '.$salary.' '.$job.'';
}
}
echo $personsList;
Related
I have a csv string and need to select rows having corresponding id.
And need to do something specific if a row doesn't exist.
$str = '1,2,3,4,5,6,7,8,9,10,11,12';
$st = $db->query("select *
from arts
where id in (" . $str . ")
order by field (id, " . $str . ")");
$arr = $st->fetchAll(PDO::FETCH_ASSOC);
foreach ($arr as $el) {
// if ($el is missing) {echo 'the row is missing';} // how to do this?
else { ... }
}
The easiest option here, assuming you are stuck with the input CSV string, is to use FIND_IN_SET, something along these lines:
$sql = "SELECT id, FIND_IN_SET(id, :list) AS result FROM arts";
$str = "1,2,3,4,5,6,7,8,9,10,11,12";
$stmt = $db->prepare($sql);
$stmt->bindParam(':list', $str);
$stmt->execute();
$arr = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($arr as $el){
if ($el["result"] <= 0) {
echo "the row is missing for id " . $el["id"];
}
}
Rather than look at the records found, this code first keys the retrieved records on the id and then looks through the ID's you are looking for and if this record isn't found (using isset()) then process the not found part...
$arr = array_column($arr, null, "id");
$ids = explode(",", $str);
foreach($ids as $el){
if(!isset($arr[$el])) {
echo 'the row is missing';
} else{
echo 'the row is there';
}
}
I have two strings, one containing names separated by commas and the other containing email addresses separated by commas.
I now want my end result to replicate the behaviour as if I had gotten those values from the database with a:
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
echo $row['name'].'<br />'.$row['email'];
}
So I have for example these strings:
email1#domain.com,email2#domain.com,email3#domain.com
and
name1,name2,name3
And can then explode these into value arrays. Now, after exploding them,
I want to be able to make a loop where in each loop I can get $name[0] and $email[0] together, and $name[1] and $email[1] together, etc.
How can I merge the two arrays (after exploding them) and get the data for each datapair (name and email) in a loop?
So if I understood you right, you are converting your strings (lets call them email, and name) too two arrays (lets call them arrEmail, and arrName) and now you want to get a array with the merged datasets.(creating the arrays should be easy if not check this out: manual for php explode function)
If so I would create a for loop based on the length of your two arrays. In the loop I would extract value i of arrEmail and arrName, and put the information into an two-dimensional array. Maybe something like this:
It should work but I didn't test it for ages so if not leave me a comment.
<?php
$arrEmail = array();
$arrName = array();
$arrGoal;
$arrLength = count($arrName);
//creating two-dimensional Array
for($i = 0; $i < $arrLength; $i++){
$arrGoal[$i] = array($arrName[$i], $arrEmail[$i]);
//should look something like this ((name, email),(name, email)…)
}
$arrGoalLength = count($arrGoal);
//accessing Array
//1. dimension
for($i = 0; $i < $arrGoalLength; $i++){
//2. dimension
//Variables should be global (but aren't)
$newName = $arrGoal[$i][0];
$newEmail = $arrGoal[$i][1];
}
?>
I think you want something like this:
$output = array();
for ($i = 0; $i < count($names); $i++) {
$output[] = $names[$i] . ' ' . $emails[$i];
}
print_R($output);
$emails = 'email1#domain.com,email2#domain.com,email3#domain.com';
$emails = explode(',', $emails);
$names = 'name1,name2,name3';
$names = explode(',', $names);
and you can use array_combine() as follow :
$combined = array_combine($names, $emails);
foreach($combined as $name => $email){
echo $name, ' : ', $email, '<br/>';
}
I think you should use the built in explode function wich will allow you to turn a string to an array by spliting it using a delimiter (comma) :
$names = explode(",",$row['name']);
$email = explode(",",$row['email']);
for merging them you should use something like this
$Array = array();
for ($j = 0; $j < count($names); $j++) {
$Array[] = [$names[$j],$email[$j]];
}
This is kind a related with your question, but only if you like to access the value by a key(e.g. access the name by email provided):
<?php
$emails = 'email1#gmail.com,email2#gmail.com,email3#gmail.com';
$names = 'name1,name2,name3';
$arrayEmails = explode(',',$emails);
$arrayNames = explode(',',$names);
$result = array_combine( $arrayEmails, $arrayNames);
print_r($result);
?>
I want to insert multipl rows in single query.
$firstname = array('Arfan','Awais','Ahmad'.....);
$lastname = array('Haider','k','Raza'..........);
Insert Data:
INSERT INTO `table_nmae`(firstname,lastname)
VALUES
('Arfan','Haider'),('Awais','k'),('Ahmad','Raza');
I can do it very easily if these are only three record.
If I did not know how many records are present then I can not able to use the above.
Then what I did do?
UPDATE:
If I can not know the numbers of record in array.I can simply use foreach loop to do this
But this decrease the performance.
foreach($firstname as $f){
foreach($lastname as $l){
INSERT INTO `table_name`(firstname,lastname)
VALUES('$f','$l');
}
}
Now this time I am using multi query.I think single query is good to performance.
FOR ONE COLUMN:
If I had only one column it is very easy to use single query for this.
INSERT INTO `table_name`(firstname) VALUES
.implode(',', $firstname);
But here is multi column how can I do that for those.
Thanks.....
Use for loop if $firstname and $lastname array are of same length
$str = "INSERT INTO `table_nmae`(firstname,lastname) VALUES"; // create string of query
for($i = 0 ;$i< count($firstname); $i++) {
$str .= "('" . $firstname[$i] . "','" . $lastname[$i] . "'),"; //append the values
}
$str = trim($str, ","); // remove last ,
Try
$size_of_array = count( $firstname );
$query = "INSERT INTO `table_nmae`(firstname,lastname) VALUES ";
for($i = 0; $i < $size_of_array; $i++ )
{
if( $i !== ($size_of_array-1))
$query .= "('{$firstname[$i]}', '{$lastname[$i]}'),";
else
$query .= "('{$firstname[$i]}', '{$lastname[$i]}')";
}
echo $query;
?>
Suppose you have array of values e.g. $values_arr.
$count = count( $values_arr );
$query = "INSERT INTO `table_nmae`(firstname,lastname) VALUES ";
for($i = 0; $i < $count; $i++ )
{
if( $i == 0)
$query .= "('{$values_arr[$i]['firstname']}', '{$values_arr[$i]['lastname']}')";
else
$query .= ",('{$values_arr[$i]['firstname']}', '{$values_arr[$i]['lastname']}')";
}
echo $query;
I am attempting to generate a weekly email to users of my site that lists locations that have added new information. When someone adds information, a table receives two numbers, one for the state and the second for the county. The first step of my cron job is to take the numbers and convert them to county, state format (Alameda, California for example). At the end of each conversion I added a | to be used as a delimiter. This part works perfectly. Next I loop through each user to send this information via email but this part does not work. What I end up with is the word array instead of my county, state format. What am I missing?
This is the code that performs the 1st step, which works just fine:
$i = 0;
while ($row = mysql_fetch_assoc($result)) {
$SID = $row['SID'];
$CID = $row['CID'];
$states = mysql_query("SELECT * FROM State WHERE ID = '$SID'");
while ($state = mysql_fetch_array($states)) {
$statename = $state['Name'];
}
$countys = mysql_query("SELECT * FROM County WHERE ID = '$CID'");
while ($county = mysql_fetch_array($countys)) {
$countyname = $county['Name'];
}
$locations = '<a href="http://hammerpins.net/display.php?state=' . $SID .' &county=' . $CID .'" >' . "$countyname, $statename ". '</a>' . "|";
$i = $i + 1;
}
This is the code that I am using to explode the array into the county, state format, which does not function properly. Instead I get the word array.
$locals = explode("|", $locations);
$locals is used in the email message as the list of new information. Please point me in the right direction. Thanks
explode will give you array
$pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2
so when you use explode function, it will explode string in to array
in your case .. write
$locals = explode("|", $locations);
echo "<pre>";print_r($locals);echo "</pre>";
and you will have exact idea and it will solve your problem
First, what is the purpose of $i?
Second, I think you want to concatenate $locations:
// This overwrites the variable - this is what you are doing
// at the end $locations will be the one single last link
$locations = '<a href="ht
// This adds to / concatenates - giving you a long strong of many links
$locations .= '<a href="ht
// ^ Note the period.
Third, explode does take a string and turns it into an array.
If you're making a long string, why would you want to explode it back into the parts you constructed it from?
I would suggest storing your states, countys, and constructed links in arrays. Then you can use the contents of those arrays at will to create your emails.
To look at what's in an array use print_r() or var_dump(). You can loop over arrays with foreach().
<?php
$i = 0;
while ($row = mysql_fetch_assoc($result)) {
$SID = $row['SID'];
$CID = $row['CID'];
$states = mysql_query("SELECT * FROM State WHERE ID = '$SID'");
while ($state = mysql_fetch_array($states)) {
// There had better only be ONE statename per SID or you lose info!
$user_array[$i]['statename'] = $state['Name'];
}
$countys = mysql_query("SELECT * FROM County WHERE ID = '$CID'");
while ($county = mysql_fetch_array($countys)) {
// There had better only be ONE countyname per CID or you lose info!
$user_array[$i]['countyname'] = $county['Name'];
}
$user_array[$i]['link'] = '<a href="http://hammerpins.net/display.php?state=' . $SID .' &county=' . $CID .'" >' . "{$user_array[$i]['countyname']}, {$user_array[$i]['statename']} ". '</a>';
++$i; // add one to i
}
// Show the arrays:
echo "<pre>";
print_r($user_array);
echo "</pre>";
?>
The above gives you an array like
Array
(
[0] => Array
(
[statename] => CA
[countyname] => San Bernardino
[link] => <a href="blah...
)
[1] => Array
(
[statename] => OR
[countyname] => Multnomah
[link] => <a href="yada...
)
)
To use the array just do
foreach ($user_array as $single_user_item) {
echo $single_user_item['link'];
}
This question already has answers here:
Two arrays in foreach loop
(24 answers)
Closed last month.
This is what I want:
foreach($_POST['something'] as $something){
foreach($_POST['example'] as $example){
$query = mysql_query("INSERT INTO table (row, row2) VALUES ('{$something}','{$example}')");
}
}
$_POST['something'] and $_POST['example'] are arrays from an input with
name="something[]" and name="example[]".
The problem:
In this way I will send the data twice to database. So I need a solution where I can loop trough 2 arrays without seding the data twice.
EDIT
The two array will always have the same size
In the mysql_query I will have other elements not just row, row2, and those will be static without any array.
Do you mean something like:
foreach($_POST['something'] as $key => $something) {
$example = $_POST['example'][$key];
$query = mysql_query("INSERT INTO table (row, row2) VALUES ('{$something}','{$example}')");
}
SOLUTION FOR MULTIPLE Arrays
TRY -
1)
<?php
$ZZ = array('a', 'b', 'c', 'd');
$KK = array('1', '2', '3', '4');
foreach($ZZ as $index => $value) {
echo $ZZ[$index].$KK[$index];
echo "<br/>";
}
?>
or 2)
<?php
$ZZ = array('a', 'b', 'c', 'd');
$KK = array('1', '2', '3', '4');
for ($index = 0 ; $index < count($ZZ); $index ++) {
echo $ZZ[$index] . $KK[$index];
echo "<br/>";
}
?>
Your solution does not seem to send the data twice. Unless if records with the same values appear as a result of issuing your queries. This might mean that you should process your data before constructing your queries.
One solution could be:
$sql = array();
foreach($_POST['something'] as $something){
foreach($_POST['example'] as $example){
$sql[] = "INSERT INTO table (row, row2) VALUES ('{$something}','{$example}')";
}
}
foreach($sql as $query){
mysql_query($query);
}
I think the best way would be as a single loop to build a query. This should work even if your arrays are not the same length:
$size1 = count($_POST['something']);
$size2 = count($_POST['example']);
if( $size1 >= $size2 ) {
$size = $size1;
} else {
$size = $size2;
}
$sql = "INSERT INTO table (row, row2) VALUES";
$values = array();
for( $i=0; $i<$size; $i++ ) {
$values[] = "('" . mysql_real_escape_string($_POST['something'][$i]) . "','" . mysql_real_escape_string($_POST['example'][$i]) . "')";
}
$sql .= implode(",", $values);
mysql_query($sql);
Also more secure because it escapes your input. This would also be even easier using placeholders with PDO.
$cnt = count($_POST['something']);
$cnt2 = count($_POST['example']);
if ($cnt > 0 && $cnt == $cnt2) {
$insertArr = array();
for ($i=0; $i<$cnt; $i++) {
$insertArr[] = "('" . mysql_real_escape_string($_POST['something'][$i]) . "', '" . mysql_real_escape_string($_POST['example'][$i]) . "')";
}
$query = "INSERT INTO table (column, column2) VALUES " . implode(", ", $insertArr);
mysql_query($query) or trigger_error("Insert failed: " . mysql_error());
}
Here is another method. This one uses extended inserts, so should be more efficient and quicker, and utilizes mysql_real_escape_string for security reasons. The count check is to just make sure that both fields have the same count, if not then I take this is a mishap. If they are allowed to have a different number of fields, you can simply use the isset() function to check to make sure they contain a value.
EDIT
This is assuming of course, that you do not want 'something' to iterate over all the 'example' values and be assigned to each one. If you want that well it is a bit of a change up.
Added an insert array test, if there are no elements no need to update. Thanks Gumbo for that.
Although you already selected an answer, don't forget this piece of script may fail if the POST values are not arrays. You can overcome this with a small piece of code:
$something = is_array($_POST['something']) ? $_POST['something'] : array();
$example = is_array($_POST['example']) ? $_POST['example'] : array();
/* Get all the keys from both arrays
* If they don't share the keys, none will be lost
*/
$keys = array_merge(array_keys($something),array_keys($example));
$keys = array_unique();
if (count($keys)) {
$sql = 'INSERT INTO table (row, row2) VALUES ';
$values = array();
foreach ($keys as $key) {
// Single quotes for PHP, we are not expanding variables
// If the element cannot be converted into a string, don't show the error on screen
$values[] = '("' . #mysql_real_escape_string($something[$key]) . '","' . #mysql_real_escape_string($example[$key]) . '")';
}
$sql .= implode(',', $values);
mysql_query($sql);
}
Foreach loop with multiple arrays:
foreach($_POST['quantity'] as $key=>$quantity)
{
$product_no=$_POST['product_id'][$key];
echo $product_no;
echo $quantity;
}
Yours example dont work in me.
I made like this :
if($_POST[add_all])
{
$n=0;
foreach($_POST['pieces'] as $checked)
{
if ($checked!=0)
{
$box=$_POST['box'];
echo $box[$n]." ".$checked . ' <br>';
$n++;
}
}
<input type="submit" id="coin" name="add_all" value="..Test.."><BR>
<select name="pieces[]">
<?php for ($x=0;$x<=20;$x++){ echo "<option>$x</option>";} ?>
<input type="checkbox" name="box[]" value="<?php echo"$row_produkt";?>">