PHP - Php To Mysql - Putting A Php Array Into A Mysql Table??
Hello everyone,
Sorry if this has been answered but if it has I can't find it anywhere. So, from the begining then. Lets say I had a member table and in it I wanted to store what their top 3 interests are. Their$ row has all the usual things to identify them userID and password etc.. and I had a further 3 columns which were labled top3_1 top3_2 & top3_3 to put each of their interests in from a post form. If instead I wanted to store this data as a PHP Array instead (using 1 column instead of 3) is there a way to store it as readable data when you open the PHPmyadmin? At the moment all it says is array and when I call it back to the browser (say on a page where they could review and update their interests) it displays 'a' as top3_01 'r' as top3_02 and 'r' as top3_03 (in each putting what would be 'array' as it appears in the table if there were 5 results. Does anyone know what I mean? For example - If we had a form which collected the top 3 interests to put in a table called users, Code: [Select] <form action="back_to_same_page_for_processing.php" method="post" enctype="multipart/form-data"> <input name="top3_01" type="text" value="enter interest number 1 here" /> <input name="top3_02" type="text" value="enter interest number 2 here" /> <input name="top3_03" type="text" value="enter interest number 3 here" /> <input type="submit" name="update_button" value=" Save and Update! " /> </form> // If my quick code example for this form is not correct dont worry its not the point im getting at :) And they put 'bowling' in top3_01, 'running' in top3_02 and 'diving' in top3_03 and we catch that on the same page with some PHP at the top --> Code: [Select] if (isset($_POST)['update_button']) { $top3_01 = $_POST['top3_01']; // i.e, 'bowling' changing POST vars to local vars $top3_02 = $_POST['top3_02']; // i.e, 'running' $top3_03 = $_POST['top3_03']; // i.e, 'diving' With me so far? If I had a table which had 3 columns (1 for each interest) I could put something like - Code: [Select] include('connect_msql.php'); mysql_query("Select * FROM users WHERE id='$id' AND blah blah blah"); mysql_query("UPDATE users SET top3_01='$top3_01', top3_02='$top3_02', top3_03='$top3_03' WHERE id='$id'"); And hopefully if ive got it right, it will put them each in their own little column. Easy enough huh? But heres the thing, I want to put all these into an array to be stored in the 1 column (say called 'top3') and whats more have them clearly readable in PHPmyadmin and editable from there yet still be able to be called back an rendered on page when requested. Continuing the example then, assuming ive changed the table for the 'top3' column instead of individual colums, I could put something like this - Code: [Select] if (isset($_POST)['update_button']) { $top3_01 = $_POST['top3_01']; // i.e, 'bowling' changing POST vars to local vars $top3_02 = $_POST['top3_02']; // i.e, 'running' $top3_03 = $_POST['top3_03']; // i.e, 'diving' $top3_array = array($top3_01,$top3_02,$top3_03); include('connect_msql.php'); mysql_query("UPDATE members SET top3='$top3_array' WHERE id='$id' AND blah blah blah"); But it will appear in the column as 'Array' and when its called for using a query it will render the literal string. a r r in each field instead. Now I know you can use the 'serialize()' & 'unserialize()' funtcions but it makes the entry in the database practically unreadable. Is there a way to make it readable and editable without having to create a content management system? If so please let me know and I'll be your friend forever, lol, ok maybe not but I'd really appreciate the help anyways. The other thing is, If you can do this or something like it, how am I to add entries to that array to go back into the data base? I hope ive explained myself enough here, but if not say so and I'll have another go. Thanks very much people, L-PLate (P.s if I sort this out on my own ill post it all here) Similar TutorialsHi again all, Why does the foreach loop im doing, put the array values from collection, into seperate table rows rather than 1 row per whole array? <?php class registration{ public $fields = array("username", "email", "password"); public $data = array(); public $table = "users"; public $dateTime = ""; public $datePos = 0; public $dateEntryName = "date"; public $connection; function timeStamp(){ return($this->dateTime = date("Y-m-d H:i:s")); } function insertRow($collection){ //HERE foreach($this->fields as $row => $value){ mysql_query("INSERT INTO $this->table ($value) VALUES ('$collection[$row]')"); } mysql_close($this->connection->connectData); } function validateFields(){ $this->connection = new connection(); $this->connection->connect(); foreach($this->fields as $key => $value){ array_push($this->data, $_POST[$this->fields[$key]]); } $this->dateTime = $this->timeStamp(); array_unshift($this->data, $this->dateTime); array_unshift($this->fields, $this->dateEntryName); foreach($this->data as $value){ echo "$value"; } $this->insertRow($this->data); } } $registration = new registration(); $registration->validateFields(); ?> I end up with 3 rows row 1: username row 2: email row 3 : password rather than row 1:username email password. I have a table like this: http://empirebuildingsestate.com/company.html How can I separate the table values into variables so I can insert them into my mySQL database? I have been trying DOMDocument but i need some help. Hi all, I want to create an array from the output of a table. In the table cell I have some numbers where for each number I would like to relate it to a value in another table. However using the code below I get Array ( => "26","27","28","29","30","31" ) from the print_r($arr); meaning that $range ins't being treated as an array, and hence, the second query only gives one value. Code: [Select] $showIng = mysql_query("SELECT * FROM recipe WHERE name = '$dish'") or die(mysql_error()); $rowShowIng = mysql_fetch_assoc($showIng); $range = $rowShowIng['keyno']; $arr = array($range); print_r($arr); foreach ($arr as &$value) { $getIng = mysql_query("SELECT * FROM keywords WHERE keyid = '$value'") or die(mysql_error()); $rowGetIng = mysql_fetch_assoc($getIng); echo $rowGetIng['ingredient']; } So, I want to know how I can create the array from $range Thanks I have a user table that holds email addresses and for testing purposes I am trying to replace every email address with an email address defined in an array. I would like to randomly choose an email address from the array and update the table with this address. When I run the following code it randomly chooses a email address from the array but then updates every row with this one email address. Can you someone please let me know what I am doing wrong. Thanks in advance. Code: [Select] $query = "SELECT * FROM user '"; $result = mysql_query($query); $input = array('email1', 'email2', 'email3', 'email4', 'email5', 'email6', 'email7'); $rand_keys = array_rand($input, 2); $replaceStr = $input[$rand_keys[0]]; while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { $rand_keys = ""; $rand_keys = array_rand($input, 2); $replaceStr = $input[$rand_keys[0]]; mysql_query("UPDATE user SET email = '$replaceStr'"); } <?php $PostID = mysql_escape_string($_GET['postid']); ?> <?php If ($_GET['CODE'] == '0') { $GetPostData = "SELECT * FROM ".FORUM_POSTS." WHERE post_id='{$PostID}'"; $GetPostRes = mysql_query($GetPostData, $db); $PostText = mysql_result($GetPostRes, 0, 'post_text'); $AuthorID = mysql_result($GetPostRes, 0, 'user_id'); If ($memid == $AuthorID || $MemLevel >= 1000) { ?> <div class="maintitle" align="left"><img src="./images/nav_m.gif" width="8" height="8"> Editing Post</div> <form action="index.php?act=edit&postid=<?php echo $PostID; ?>&CODE=1" method="POST"> <table width="100%" cellspacing="1" cellpadding="4"> <tr> <td class="titlemedium" colspan="2">Make changes below.</td> </tr> <tr> <td class="row2" align="right" width="15%" valign="top">Post Text:</td> <td class="row2" align="left" width="85%"> <textarea cols="80" rows="20" name="posttext"><?php echo $PostText; ?></textarea> </td> </tr> <tr><td class="row2" colspan="2" align="center"><input type="submit" value="Post" /></td></tr> </table> </form> <?php } Else { ?> <div class="maintitle" align="left"><img src="./images/nav_m.gif" width="8" height="8"> Error</div> <table width="100%" cellspacing="1" cellpadding="4"> <tr><td class="row2">You do not have the permission to edit this post.<br>If you believe this is an error please contact an administrator.</td></tr> </table> <?php } } If ($_GET['CODE'] == '1') { //Gather Information $PostText = mysql_escape_string($_POST['posttext']); $PostText = htmlentities($PostText); $PostID = mysql_escape_string($_GET['postid']); //Update Database $EditQry = "UPDATE ".FORUM_POSTS." SET post_text='{$PostText}' WHERE post_id='{$PostID}'"; $EditRes = mysql_query($EditQry, $db); //Check Data went in If (!$EditRes) { ?> <div class="maintitle" align="left"><img src="./images/nav_m.gif" width="8" height="8"> Error</div> <table width="100%" cellspacing="1" cellpadding="4"> <tr><td class="row2">Could not modify database. Please contact administrator.</td></tr> </table> <?php } Else { ?> <div class="maintitle" align="left"><img src="./images/nav_m.gif" width="8" height="8"> Success</div> <table width="100%" cellspacing="1" cellpadding="4"> <tr><td class="row2">Post modified. Please go back to the thread to see it.</td></tr> </table> <?php } } ?> </div> This is my page for editing a post. However, whenever this form actually goes through, the query for some reason makes post_text in the database blank with no text in it whatsoever. I have tried echoing the query to see what it says and it has a perfectly fine query and I can copy/paste it manually to put it into the mysql but I don't get why this isn't adding it. Hi, I am still learning php and I've been racking my brain to get some field data from the mysql database and put the results into variables to use. I need to do a query to get the data from two fields and place them in a variable. I have this field from a form: $_REQUEST['linkurl'] So i need to check this form field against (tablename, fieldname) alldomain.domain_name when the match is found I need to store the value of tablename, fieldname) domain.manual_approve into $x_manual_approve and then check that rows userid field: (tablename, fieldname) alldomain.userid and equals (tablename, fieldname) register.id the userid and id are matching from two different tables (tables alldomain and register). When I get that match I need to get (tablename, fieldname) register.username and store the value into $x_username Thanks much for any help, Gibs I am pulling 5 addresses and I am wanting to store these 5 addresses in columns in a separate table. On the query string I put LIMIT 5. How can I store the results of each of the 5 loops into columns in a separate table? The columns are A1(for name), A2(for address), A3 (for city), A4 (for state), A5 (for zip), A6 (for phone), A7 (for miles), .... then I also have B1-B7, C1-C7, D1-D7, and E1-E7. I am basically wanting to store up to 5 addresses in an array and then update them into a mysql table. Code: [Select] foreach ($zips as $key => $value) { $result = mysql_query("SELECT State FROM extreme WHERE Zip = '$key' AND Type='store' AND `InStore` <> 'NO' LIMIT 5", $db); $num_rows = mysql_num_rows($result); while($myrow = mysql_fetch_array ($result)) { $Dealer=$myrow['Dealer']; $Address=$myrow['Address']; $City=$myrow['City']; $State=$myrow['State']; $Zip=$myrow['Zip']; $Phone=$myrow['Phone']; $Miles = $value; } } Hi all, hope some can help because this is giving me more grey hairs than I allready have.
I am trying to solve the following: I'm pulling in JSON data, decoding it to a array which I write to a database. However in the array are social security numbers that I don't want to store (privacyregulations). So I need to check if a row has a social security number and if it has one I want to replace it with 'anonymized'. I have got it to work successfully on a local Xampp test environment using the following script (extract off course): //first anonymize the social security number (ssn) if exists $data = json_decode($jsondata, true);
// then fill the tables foreach($data as $row) {
$insertstatement = mysqli_query($link,"INSERT INTO $tablename (personid, type, ssn) VALUES ('".$row["personid"]."', '".$row["type"]."', '".$row["ssn"]."') ON DUPLICATE KEY UPDATE type = VALUES(type), bsn = VALUES(ssn)");
This leads to a filled table where the ssn's are filled with 'anonymized' if they exist in the array and empty if it does not exist for that row. This is exactly what I want ;-).
Personid type ssn
However, when I run the same script on a Lamp production environment (lamp stack on an Azure server) it does not work. Then the scripts results in totally ignoring the whole row that contains a ssn??
Personid type ssn Hope someone can help to get this working on my production environment as well.
Richard
Hi all, I have implemented a WYSIWYG in my admin panel, here i can write text and customize it how i want it and then convert it to a html code and save it in my mysql database. Now I want to let other people see the text in the homepage, but it is showing this text very wrong functions like this Code: [Select] <p> <b> <strong> <font> arent working. For example I make text Code: [Select] <b>title</b> <strong> blabla bla bla </strong> then the text becomes like this litterly Quote "<b>title<b> <strong> blabla bla bla </strong> " the codes have no effect and are seen as text in the homepage. My question is how is this possible and how can i fix this, thanks. The code on my homepage is like this Code: [Select] <?php $tekst="SELECT * from homepage where id='1'"; $tekst2=mysql_query($tekst) or die("unable to connect"); $tekst3=mysql_fetch_array($tekst2); print "$tekst3[tekst]"; ?> create table mimi (mimiId int(11) not null, mimiBody varchar(255) ); <?php //connecting to database include_once ('conn.php'); $sql ="SELECT mimiId, mimiBody FROM mimi"; $result = mysqli_query($conn, $sql ); $mimi = mysqli_fetch_assoc($result); $mimiId ='<span>No: '.$mimi['mimiId'].'</span>'; $mimiBody ='<p class="leading text-justify">'.$mimi['mimiBody'].'</p>'; ?> //what is next? i want to download pdf or text document after clicking button or link how to do that //First I'm assigning a $variable ($emailzipmatch) to query a database table called(repzipcodes) and having it pull and display 1 to 3 records based on matching up a customer's zip code (RepZipCode = $CustomerZipMatch) with 1 to 3 other people (GROUP BY RepId HAVING COUNT(1) <= 3") that want that customer's information from that particular zip code. <This code works fine> // CODE WORKS BELOW Code: [Select] <?php $emailzipmatch = mysql_query("SELECT * FROM repzipcodes WHERE RepZipCode = $CustomerZipMatch GROUP BY RepId HAVING COUNT(1) <= 3") or die(mysql_error()); $recipients = array(); while($row = mysql_fetch_array($emailzipmatch)) { $recipients[] = $row['RepEmail']; echo "Agent's Email Address: "; echo 'font color="#FF7600"',$row['RepEmail'], '/font'; echo '<br />'; echo "Rep's ID: "; echo '<br />'; echo 'font color="#FF7600"',$row['RepId'], '/font'; echo '<br />'; echo 'hr align="left" width="50%" size="2" /'; } //MY PROBLEM BELOW // For the NEXT step of the process above I would take $row['RepEmail'] and $row['RepId'] which can have 1 to 3 results and assign the 1 to 3 results a new $variable so it can be inserted into a different db table so I can track the results of the query ($emailzipmatch = ) from the top of the page: ie.. <New Variable> <Listed from above> $SentRepId 0 = RepId (results from above echo area) $SentRepId 1 = RepId (results from above echo area) $SentRepId 2 = RepId (results from above echo area) // Below I'd like to insert the above results into a new database $?Variable??? = mysql_query("INSERT INTO sentemail (SentRepId0, SentRepId1, SentRepId2,SentDateTime ) VALUES ( '$_SESSION[RepId]', // ????? '$_SESSION[RepId]', // ????? '$_SESSION[RepId]', // ????? NOW() )") or die(mysql_error()); Thank ahead of time for any help you guys can give me. Please respond with ANY question if my coding or request isn't clear or if I've been confusing due to my lack of experience with PHP and MySQL. MOD EDIT: code tags added. Hi Everyone, I have a problem displaying some information from an array (selected from my database). The array is below. Array ( [0] => Array ( [ssc_skill_categories] => Web [sc_skill_categories] => Programming ) [1] => Array ( [ssc_skill_categories] => Actionscript [sc_skill_categories] => Programming ) [2] => Array ( [ssc_skill_categories] => C# [sc_skill_categories] => Programming ) [3] => Array ( [ssc_skill_categories] => CSS [sc_skill_categories] => Programming ) [4] => Array ( [ssc_skill_categories] => Graphic [sc_skill_categories] => Designers ) [5] => Array ( [ssc_skill_categories] => Logo [sc_skill_categories] => Designers ) [6] => Array ( [ssc_skill_categories] => Illistration [sc_skill_categories] => Designers ) [7] => Array ( [ssc_skill_categories] => Animation [sc_skill_categories] => Designers ) ) What i would like to to is display this information in a table like so: <html> <body> <table> <tr> <td>Programming</td><td>Web</td><td>Actionscript</td><td>C#</td><td>CSS</td> <tr> <tr> <td>Designers</td><td>Graphic</td><td>Logo</td><td>Illistration</td><td>Animation</td> <tr> <table> </body> </html> I have been trying and failing all day to do this. Posting my "progress" will clog up the thread, so for now i wont post it. Does anyone have an idea how i would achieve this? Regards, -Ben Hi, I have two html made text boxes one that is called "name" and another that is called "regnum". I also have a submit button. They are both used to add data to a database. The name text box should add a name to the database under the "name" heading and the regnum should add a number under the "regnum" heading Here is the code for them: HTML Code: <form action="" method="post"> <p> Name: <input type="text" name="name"/> </p> <p> Regnum: <input type="text" name="regnum"/> </p> <p> <input type="submit" value="Add To Database" name = "submit2" /> </p> </form> Here is the PHP code that i am using for adding the user to the database: PHP Code: $host="localhost"; $username="root"; $password=""; $database="lab2"; mysql_connect("$host", "$username", "$password") or die(mysql_error()); mysql_select_db("$database") or die(mysql_error()); $name = $_POST['name']; $regnum = $_POST['regnum']; if(!$_POST['submit2']){ echo "Enter A Vaue"; }else{ mysql_query("INSERT INTO lab2('name', 'regnum') VALUES(NULL, '$name', '$regnum')") or die(mysql_error()); echo "User Added To Database"; } The problem i get with this is "Undefined Index name and regnum". I watched a video on youtube and this is how the guy did it but it worked for him and for some reason it doesn't work for me. Can anyone help?? Thanks. So I have a big table of about 30-40 columns. Some variables are quite long strings while others are simple tinyint(1) values.
Input into the code is a value or range of values or something that applies to each of the columns.
I need to find which ones are an applicable match to the user request and then load them into php.
Now I know variations can cause something to run more optimally one way or another but this system will get bogged down with lots of requests and lots of data, so any additional performance I give it now will help me down the road. I am just looking for general concepts to help, not specific code tweaking.
I have heard the typical rule is to query mysql as little as possible and do the hard lifting in php but I am not positive this is right.
Since I have to query anyways, should I do a mysql pull using a complex 'WHERE' to do most of the sorting. ie only get rows where a=1, b>5, c="http://google.com", d="3242342323kj4238237489023ejfjf3jrjf8jeifjdjf" ie long string, etc for all 30+columns?
OR I pull the whole DB and do all the sorting in php...
OR I do all the simple sorting in the MySQL query and some of the more complicated sorting in PHP (or vice versa)
Any ideas would help.
How can i save array from inputs, witch is $igraci and it have 5 values, to mysql base, i tryed but in mysql it shows Array. This is form: <form action="dodaj_klan.php" method="post" > <p> <label>Naziv klana:</label> <input name="naziv" type="text" size="20%" /> <label>Web Sajt:</label> <input name="website" type="text" size="20%" /> <label>E-Mail:</label> <input name="email" type="text" size="20%" /> <br /><br /> <label>Igraci klana(5):</label> <input name="lider" type="radio" value="1" /> <input name="igraci[]" type="text" size="20%" /><br /> <input name="lider" type="radio" value="2" /> <input name="igraci[]" type="text" size="20%" /><br /> <input name="lider" type="radio" value="3" /> <input name="igraci[]" type="text" size="20%" /><br /> <input name="lider" type="radio" value="4" /> <input name="igraci[]" type="text" size="20%" /><br /> <input name="lider" type="radio" value="5" /> <input name="igraci[]" type="text" size="20%" /> <label><i>(obelezi lidera klana)</i></label> <br /><br /> <input class="button" type="submit" name="submit" value="Dodaj" /> </p> </form> Now i wonna save this igraci[] array in mysql, i tried like this but it doesn't work: $igraci = $_POST['igraci']; $query = "INSERT INTO klanovi (naziv, website, email, igraci) VALUES ('{$naziv}', '{$website}', '{$email}', '{$igraci}')"; $result = mysql_query($query, $connection); How can i do this? Thanks.. Hello, I need some help. Say that I have a list in my MySQL database that contains elements "A", "S", "C", "D" etc... Now, I want to generate an html table where these elements should be distributed in a random and unique way while leaving some entries of the table empty, see the picture below. But, I have no clue how to do this... Any hints? Thanks in advance, Vero So I'm querying my database to add the results (mapID's) into a PHP array. The MySQL query I used in the below code would usually return 10 values (only 10 mapID's in the database) Code: [Select] while($data = mysql_fetch_array(mysql_query("SELECT mapID FROM maps"))){ $sqlsearchdata[] = $data['mapID']; } Instead the page takes ages to load then gives this error: Quote Fatal error: Allowed memory size of 8388608 bytes exhausted (tried to allocate 16 bytes) It says the error begins on the first line of the above code. I'm assuming this is not the right way to add the value from the MySQL array into a normal PHP array. Can anyone help me? I know I'm doing it something right, but can someone tell me why only one table is showing up? Can you help me fix the issue? Heres my code: function showcoords() { echo"J3st3r's CoordVision"; $result=dbquery("SELECT alliance, region, coordx, coordy FROM ".DB_COORDFUSION.""); dbarray($result); $fields_num = mysql_num_fields($result); echo "<table border='1'>"; // printing table headers echo "<td>Alliance</td>"; echo "<td>Region</td>"; echo "<td>Coord</td>"; // printing table rows while($row = mysql_fetch_array($result)) { // $row is array... foreach( .. ) puts every element // of $row to $cell variable foreach($row AS $Cell) echo "<tr>"; echo "<td>".$row['alliance']."</td>\n"; echo "<td>".$row['region']."</td>\n"; echo "<td>".$row['coordx'].",".$row['coordy']."</td>\n"; echo "</tr>\n"; } echo "</table>"; mysql_free_result($result); } I have 2 rows inserted into my coords table. Just frustrated and ignorant to php. |