storing array data in mysql - php

I am new to PHP and MySQL, please I would appreciate your help.
I have a table that generates several rows depending on the number of options selected by a user.
I want to store the content in a database table after the user presses the submit button.
Since i cannot tell how may options the user would select and how many rows will be generated, i don't know how to write the SQL code that will store it in my database table.
here is the code to generate the table
for($x=0;$x<$N; $x++) {
echo nl2br("<td><textarea name=art[] rows=10 cols=30></textarea></td><td><textarea name=science[] rows=10 cols=30></textarea></td></textarea></td><td><textarea name=method[] rows=10 cols=30></textarea></td><td><textarea name=criteria[] rows=10 cols=30></textarea></td></tr>");
}
To get the data from the table
for($i = 0; $i <$N; $i++){
$data[] = array(($art[$i]), ($science[$i]), ($method[$i]), ($criteria[$i]));
}

I would normalize this design and have a USER and OPTION table with a one-to-many relationship between them. You have as many rows as you do selections that way. You can query later to see how many USER rows chose OPTION X.

You can merge (implode) all values and store into table. split ( explode ) the values while retrive.
Store :
$optionsVal = implode(",", $data);
Retrieve :
$data = explode(",", $optionsVal);

Related

insert array with dynamic amount of values to database

I am attempting to insert an array of image information into my database. The array consists of a ton of image information and originally i started with just allowing 3 images out of the array to be entered into the database.
The images detail goes into a table called print and each of the three image urls has a column of their own to go into, along with a caption for each image, the date the image was taken and its location. All of this info goes into one row with the users id.
// Assign images and data to appropriate variables
$image_one = $feed['0']['images']['standard_resolution']['url'];
$image_one_caption = htmlspecialchars($feed['0']['caption']['text'], ENT_QUOTES);
$image_one_date = $feed['0']['created_time'];
$image_one_location = $feed['0']['location']['name'];
$image_two = $feed['1']['images']['standard_resolution']['url'];
$image_two_caption = htmlspecialchars($feed['1']['caption']['text'], ENT_QUOTES);
$image_two_date = $feed['1']['created_time'];
$image_two_location = $feed['1']['location']['name'];
$image_three = $feed['2']['images']['standard_resolution']['url'];
$image_three_caption = htmlspecialchars($feed['2']['caption']['text'], ENT_QUOTES);
$image_three_date = $feed['2']['created_time'];
$image_three_location = $feed['2']['location']['name'];
However I now want to make it so that the number of prints entered into the table can vary from 3 up to 10 as a maximum. I'm wondering about the best way to do this.
I could simply assign the array values to more variables in the way shown above, however this is bulky and I feel unnecessarily repetitive.
I was thinking about a foreach loop, however I'm uncertain of how to insert each image and each images accompanying data into the correct columns of the users print row.
The other option would be to create a separate print_info table and store the users id and print_job number, then in the print table purely have the image info in separate rows with a print_job column to link the print_job to the users print_info row. is this the best way forward with this little problem?
What about this:
$numOfImages = 4; //the number you want
for ($i=0; $i < $numOfImages; $i++) {
$image = $feed[$i]['images']['standard_resolution']['url'];
$image_caption = htmlspecialchars($feed[$i]['caption']['text'], ENT_QUOTES);
$image_date = $feed[$i]['created_time'];
$image_location = $feed[$i]['location']['name'];
//...operation with $image
}

How to search record "without knowing tables name" in database using php

I'm trying to make a PHP search form that lets you search for something without knowing No tables name, after search, it compares to the record with "search text" in all over database ?
You want to search in every fields of every tables ?
What you can try is to get all tables :
SHOW TABLES FROM your-database;
Then for each table you can get fields :
SHOW COLUMNS FROM your-table
Example :
$array = array();
$getTables = mysqli($link, "SHOW TABLES FROM your-database");
while ($t = mysqli_fetch_row($getTables))
$array[$t[0]] = array();
foreach( $array as $tableName => $fields )
{
$getColumns = mysqli($link, "SHOW COLUMNS FROM ".$tableName);
while ($c = mysqli_fetch_assoc($getColumns))
$array[$tableName][] = $c['Field'];
}
var_dump($array); // will output tables and each fields;
Now you have tables/fields so you can build your query to make your search.

Getting value from multiple drop down menus in PHP

Ive been battling away with the following problem
Ive got a page where I pull names from players specific to their positions in a sport squad.
Example: I will display all the Wings in the squad using a dropdown where a coach can then pick his wing for the game.
There are dropdowns for each different position
The aim of the page is to let the coach quickly select his team for a fixture
After the coach selected his team he will, select the opponents for which the selected team will play against.
When he clicks submit the selected oppents and players will get stored in two arrays which will get called to display the team selected and their opponents on a new page. (After which it will get uploaded to the DB.)
I am having trouble getting the values from the select list to display on the new page.
I guess I have to do something like this on the new page:
foreach ($_REQUEST['opponents'] as $opponents){
print $opponents;
echo'<br>';
}
but it is not giving the desired results.
Strangely what gets printed is the variable name from the previous page select menu.
Upon further inspection I did a vardump on the new page and it says that $opponenets gets passed a value of string which is the variable name and not the value thereof?
My page looks like this
My question is how would I go abouts getting the values from the select dropdowns
if(isset($_POST["submit"]))
{
foreach ($_REQUEST['opponents'] as $against){
var_dump($against);
print $against;
echo'<br>';
}
}
else
{
echo'<h1>Select your Team</h1>';
$x = array("THP", "HKR", "LHP", "LH", "FLH"); //players positions gets assigned to x which will be used to query the database
echo '<form name="playerselect" method="post" action="">';
//query database with different query after each loop
for ($i = 0; sizeof($x) > $i; $i++)
{
//query where position field equeals variable x
$result = mysql_query("SELECT `name`, `position` FROM `player_info`
WHERE `position` = '$x[$i]'") or die(mysql_error()) ;
//Gets data from DB and assigns values to arrays below
while($row = mysql_fetch_array($result))
{
$playername[] = $row['name'];
$position[] = $row['position'];
}
//print player position
print $position[0];
echo'<br>';
//unset the array so that it is empty for the next query in the new loop
unset($position);
echo '<select name="players[]" >' ;
foreach ($playername as $name )
{
//Put playernames relevant to the position in the option element
echo'<option value="$name" selected="selected">'.$name;'</option>';
echo'<br>';
}
echo'</select>';
//unset array so that its contents is empty for the next query in the new loop
unset($playername);
echo'<br>';
}
You cannot. Your submit will only transmit select values. This is not a bug, it is a feature. You do not want to send data back and forth from/to the server/client which is known to both of them.
On the server you are free to query your database at any time. You can also cache your select list into the $_SESSION variable in your initial list read. However this is advanced fittling as your cache list may become outdated and also your server memory utilization must leave space for file caching (the SESSION cache goes to files).
If you go for the database query you may need some ID as sort of anchor. Just put the into the $_SESSION variable - eg.:
$_SESSION['positions']=$x;
In your example the $x seems to be static, which obviously reduces the need to cache it into the $_SESSION - however on other occasions you may need this method.

Creating a Chart with PHP and MySql

I have a database with the following table:
id value
-----------
1 yes
2 no
3 no
4 maybe
I'm using some simple php to log the choices entered on a poll website. The user selects a radio box and it is entered into the above table. However, I want to make this a little more flexible. I created a simple backend that allowed an admin user to add or delete poll choices. What would I do to show on the frontend the number of votes for each individual choice, when the number of choices is not constant? I know I could do this easily if the poll choices were static but since the backend user will be changing the choices, how could I dynamically display the results?
I am not really sure what you are asking. Is it COUNT you're looking for?
Don't worry about the choices or the number of choices, grab all the votes/choices and iterate through them and add them to an array indiscriminately: http://codepad.org/LWPyuTqj
$total = array();
$votes = array(1=>'yes',2=>'no',3=>'no',4=>'maybe');
foreach($votes as $vote) {
if (!isset($total[$vote]))
$total[$vote] = 1;
else
$total[$vote] += 1;
}
print_r($total);
I would recommend google graph API for this. It is really easy!
http://code.google.com/apis/chart/interactive/docs/gallery/piechart.html
Generate the code dynamically, using the first example on the link above. First select the values. This assuming there is a question ID so you can relate to the question. In this case id 1.
$result = mysql_query('SELECT value,COUNT(*) as num FROM choises WHERE question_id = 1 GROUP BY value');
Then with PHP loop through the data
$results = array();
while ($row = mysql_fetch_assoc($result)){
$results[$row['value']] = $num;
}
With this you can generate the graph:
echo 'data.addRows('.count($results).');';
$i = 0;
foreach ($results as $value => $num){
echo'
data.setValue('.$i.', 0, "'.$value.'");
data.setValue('.$i.', 1, '.$num.');
';
$i++;
}

Save multiple rows with multiple arrays - PHP

I have a big problem on saving multiple rows with multiple arrays into MYSQL. For example row 1 contains "name" and "share percentage". Then they add another 2 rows which contains same attributes as mentioned. So how do I save these data into DB. Below was my unsuccessful code:
foreach($_POST['name_members'] as $dir){ // array 1
$directorID = run_num('director_id','proc_director'); // generate running number for each row
foreach($_POST['share_percentage'] as $share) { //array 2
$insDirector = "INSERT INTO
proc_director(director_id, vendor_cd, director_name, director_percentage)
VALUES
('$directorID','$vendorID','".trim(addslashes($dir))."','$share')";
$db->query($insDirector); // save the array value into DB
}
}
I made demo interface, so that you can get the picture what I want. Here the hyperlink: http://softboxkid.com/blog/code/add_row/
Thank for your respond. I already found the solution for my problem. Here is my code:
/* save partnerhip information */
$count_director = count(array_trim($_POST['name_members']));
for($i=0; $i<$count_director; $i++) {
$directorID[] = run_num('director_id','proc_director'); // generate running number for each row
$insDirector = "INSERT INTO proc_director(director_id, vendor_cd, director_name, director_percentage)
VALUES('".$directorID[$i]."','".$vendorID."','".$_POST['name_members'][$i]."','".intval($_POST['share_percentage'][$i])."')";
$db->query($insDirector); // save the array value into DB
}

Categories