Storing array items in MySQL using foreach - php

I have arrays within an array and I want to loop through each item of the nested arrays and put them into different mysql columns. There is a limit of 3 entries per array, and I need $workexp_array_t to go into the work experience column, the $credentials_array_t items to go into the credentials column etc.
The problem I'm having is that using these nested foreach loops it just places the first letter of the entry into the column instead of the proper entry. How can I get each array items to go into their proper column? Do I really need to set up separate tables for each thing (ie. education experience, credentials, work experience, etc.)?
$tutor_background = array($workexp_array_t, $credentials_array_t, $education_array_t, $extra_array_t);
foreach ($tutor_background as $entry) {
foreach ($entry as $background) {
$query = "INSERT INTO tutor_background (login_value, work_history, credentials, education_history, extra_skills) VALUES ('{$_SESSION['login_value']}', '{$background[0]}', '{$background[1]}', '{$background[2]}', '{$background[3]}')";
$process_query = mysql_query($query);
}
}

Going to take a guess here and say you only need one foreach.
$tutor_background = array($workexp_array_t, $credentials_array_t, $education_array_t, $extra_array_t);
foreach ($tutor_background as $entry) {
$query = "INSERT INTO tutor_background (login_value, work_history, credentials, education_history, extra_skills) VALUES ('{$_SESSION['login_value']}', '{$entry[0]}', '{$entry[1]}', '{$entry[2]}', '{$entry[3]}')";
$process_query = mysql_query($query);
}
}

Related

Finding a faster function then "gethostbyname"?

I run a script under xampp with a mysqlDB.
I check if a domainname has an ip.
The problem is, that I have to check over 100000 domain names from a MySQL_DB.
The function "gethostbyname" works great, but my solution is too slow.
while($row = mysqli_fetch_array($db_res)) { // get the DB domainnames entrys
if (empty($row['status'])) {
$items[] = $row['domainnames'];
}
foreach ($items AS $domain) {
if ( gethostbyname($domain) != $domain ) {
do somthing.....
}
}
}
How do I get it faster?
Your foreach() loop inside of your while() loop is simply a bad idea. Think about it.
As you iterate the result set, $items swells and swells -- this means that the foreach() will have to work longer and longer and longer.
Ultimately, if you need to process the gethostbyname() value for the next task in your script, you should be storing that value at the same time that you INSERT the entry into your table the first time -- perhaps the new column can be host.
The smart money is not to call gethostbyname() 100000 times; have the value ready when you SELECT it.
Beyond the above logic, I don't see the need to declare an array with a single element/string, then iterate it.
In fact, your query should contain a WHERE clause that excludes rows that have a null/0/blank status value AND includes rows that have a host (new column) value that matches $domain so that php doesn't have to bother any qualifying/disqualifying conditions.
foreach ($db_res as $row) { // yes, you can simply iterate the result object
// do whatever with the associative string elements (e.g. $row['domainnames'])
// ...you know this is a string and not an array, right? -^^^^^^^^^^^^^^^^^^^
}
thanks for the answers.
With your assistance i was able to reduce the procedure to:
while($row = mysqli_fetch_array($db_res))
{
$domain = $row['domainnames'];
if ( gethostbyname($domain) != $domain ) {
do somthing.....;
}
else{
do somthing.....;
}
}
it feels a little bit faster but not enough.
#mickmackusa i catch now only the empty "status" fields:
$db_res = mysqli_query ($db_link, "select domainnames FROM domaintable WHERE status = ''")
Looks like when your while loop iterates, it uses the $items from the last iteration - which will waste time - so please try this version (putting the foreach into the if:
while($row = mysqli_fetch_array($db_res)) { // get the DB domainnames entrys
if (empty($row['status'])) {
$items[] = $row['domainnames'];
foreach ($items AS $domain) {
if ( gethostbyname($domain) != $domain ) {
do somthing.....
}
}
}
}

Passing multiple checkbox values to different columns of database

I am pretty new to PHP, but have tried searching for other questions similar to mine and been unable to find anything that is close enough to my situation to help me solve this.
I am trying to code a web page that allows users to select as many or as few items as they would like to order. The item values are identical to their Primary Key in the Item table.
Once submitted, each different item value should be input into the same row of a database table based on the date{pk}. Within that row, there are numerous columns: Item1ID, Item2ID, Item3ID, etc.
So far, the value of each item selected is assigned to a new array. However, I cannot simply input the array values into a column -- I need each array index to be placed into a sequential column. The code is below:
$date = new DateTime();
$td = $date->format('Y-m-d');
$x = 1;
$checkedItems = $_POST['Item'];
$count = count($checkedItems);
echo $count;
$foodID = "Item".$x."ID";
While($x<=$count){
if(isset($_POST['Item'])){
if (is_array($_POST['Item'])) {
foreach($_POST['Item'] as $values){
$selectedFoods = substr($values,0,4);
$addFoodOrderQuery= sprintf("UPDATE WeeklyBasketFoodOrder SET '%s' = %s WHERE `foodOrderDate` = '%s'",
$foodID, $selectedFoods, $td);
$result= mysqli_query($db, $addFoodOrderQuery);
}
}
} else {
$values = $_POST['Item'];
echo "You have not selected any items to order.";
}
$x++;
}
If you need any further clarification, please let me know. After submitting the code, the database item#ID tables are different, but they are now empty instead of "NULL."

Fetch result from database to multiple variables

I have a site were the user fills a form and all data is stored in a database, when the user enter his/hers page all the added data is visible. Today I´m doing this but in a lot of code rows and there is for sure a much smoother way to do this.
Here´s a look of how I have done it today:
$query = mysqli_query($dbhandle, "SELECT * FROM ..."); // ... added now
$row = mysqli_fetch_assoc($query);
$m0 = $row['m1'];
$m1 = $row['m2'];
$m2 = $row['m3'];
$m3 = $row['m4'];
...
$m47 = $row['m48'];
$firstPlace = $row['firstPlace '];
$secondPlace = $row['secondPlace '];
$thirdPlace = $row['thirdPlace '];
$fourthPlace= $row['fourthPlace'];
As you can see there are a lot of rows of code. What I would like to do is to loop through my query and then add the right value in the database to the right value in the form.
Appreciate help.
There definitely are many alternative (and in every possible sense of the word) better ways to go about your business.
For a kickoff: ask yourself what an array actually is. An array is a collection of data. You store them together because one value of that array in itself doesn't mean much. The data in an array belongs together. Why then, assign it to individual variables in the first place?
Of course, your $row array has keys like $row['m1'], which you assign to a variable called $m0. so the names of the fields in the database don't quite match the names your code uses. That's something that you can, quite easily, fix by changing your query: use aliasses for those fields:
SELECT m1 as m0, ... FROM
Now your array will have a key called m0, instead of m1. This reduces the rest of your code down to:
$row = mysqli_fetch_assoc($query);
echo 'M0: ', $row['m0'];//<-- use m0 value here.
Alternatively, you could use a second array that maps these field-names to the name you want to use in your code:
$map = array(
'm0' => 'm1'
);
echo 'M0: ', $row[$map['m0']];//use value of m0, which is the actual key if the $row array
Still, if you are hell-bound on unmaintainable, messy, error-prone and just awful code, you could use variable variables:
foreach ($row as $key => $value)
{
$$key = $val;
}
Note the double $ in $$key. This is like saying "the variable that is called whatever the value of $key is". If $key is firstname, the code above evaluates to $firstname = $value. But whatever you do: forget this is possible. It's like an enema: yes, it's possible, but you don't want one if you can avoid it. And in this case, you clearly can avoid it.
Loop through the $row var grabbing the key and value. If key starts with "m" followed by a 1 or 2 digit number, get the number, subtract one, concatenate it with "m", and assign the value. Otherwise just interpolate key into variable name and assign value.
foreach ( $row as $key => $value ) {
if ( preg_match('/^m(\d{1,2})/', $key, $matches) ) {
${'m' . ($matches[1] - 1)} = $value;
}
else { $$key = $value; }
}
In the above example, $row['m1'] value gets assigned to var $m0, and $row['firstPlace'] to var $firstPlace, etc.

Show all keys with phpcassa

I'm fairly new to cassandra but i have making good progress so far.
$conn = new ConnectionPool('Cluster');
$User = new ColumnFamily($conn, 'User');
$index_exp = CassandraUtil::create_index_expression('email', 'John#dsaads.com');
$index_clause = CassandraUtil::create_index_clause(array($index_exp));
$rows = $User->get_indexed_slices($index_clause);
foreach($rows as $key => $columns) {
echo $columns['name']."<br />";
}
Im using this type of query to get specific date from somebodys email adress.
However, i now want to do 2 things.
Count every user in the database and display the number
List every user in the database with $columns['name']." ".$columns['email']
In mysql i would just remove the 'where attribute' from the select query, however i think its a little bit more complicated here?
In Cassandra there's no easy way to count all of the rows. You basically have to scan everything. If this is something that you want to do often, you're doing it wrong. Example code:
$rows = $User->get_range("", "", 1000000);
$count = 0;
foreach($rows as $row) {
$count += 1;
}
The second answer is similar:
$rows = $User->get_range("", "", 1000000, null, array("name", "email"));
foreach($rows as $key => $columns) {
echo $columns["name"]." ".$columns["email"];
}
Tyler Hobbs give very nice example.
However if you have many users, you do not want to iterate on them all the time.
It is better to have this iteration once or twice per day and to store the data in cassandra or memcached / redis.
I also would do a CF with single row and put all usernames (or user keys) there on single row. However some considered this as odd practice and some people will not recommend it. Then you do:
$count = $cf->get_count($rowkey = 0);
note get_count() is slow operation too, so you still need to cache it.
If get_count() returns 100, you will need to upgrade your phpcassa to latest version.
About second part - if you have less 4000-5000 users, I would once again do something odd - put then on single row as supercolumns. Then read will be with just one operation:
$users = $scf->get($rowkey = 0, new ColumnSlice("", "", 5000));
foreach($users as $user){
echo $user["name"]." ".$user["email"];
}

How to separate database entries and display them as individual records using PHP?

I used to have database entries separated by ampersands (&), but this was causing certain search issues so I decided to encapsulate my entries on both sides by $ and & symbols like:
$this&
But I am having trouble displaying all the entries of a cell as individual records. Before I used:
$unsplitItems = $row['files'];
$files = explode("#", $unsplitItems);
foreach ($files as $file) {
if(strlen($file)) {
echo "<li>$file</li>";
}
}
Any idea how I can split my records and display all the items in the array as individual entries?
You shouldn't do that!
Make your records separate db entries.
Make another db table with 2 fields - id of parent record and your entry field. So you will be able to search using database features, with single query
If you really want to do this then use one symbol as a separator and make sure that this symbol is not used in the strings it separates.
Normally, though, you would create 3 tables:
post (id, post_text, ...)
tag (id, tag_name, ...)
post2tag (post_id, tag_id)
The last table lets you assign as many tags to any post as you want.
This SQL relationship is called many-to-many; you can see examples of its use here.
Try this:
$unsplitItems = $row['files'];
$files = explode("#", $unsplitItems);
foreach ($files as $file) {
if(empty($file)) continue;
$sub_record = explode('&', $file);
foreach($sub_record as $sr) {
if(empty($sr)) continue;
$sr = substr($sr, 1);
echo "<li>$sr</li>";
}
}

Categories