PHP - Insert Multiple Data Into Mysql With Explode?
Hi all .
In my scripts , there is a textarea that allow user to enter multiple phone number , message and date . If there are 3 phone numbers in textarea , how can I insert 3 of them into sql with the same data of message and date? Such as : phone number : 0102255888,0235544777,0896655444 message:hello all date:10/10/2011 and when it's insert into table , it will become: 1. 0102255888 | hello all | 10/10/2011 2. 0235544777 | hello all | 10/10/2011 3. 0896655444 | hello all | 10/10/2011 Here is the code I tried , but it will just save the last phone number . Code: [Select] $cellphonenumber = explode(',', $_POST['cellphonenumber']); $message = $_POST['inputtext']; $date = $_POST['datetime']; foreach($cellphonenumber as $value) { $sql="INSERT INTO esp( Recipient , Message , Date) VALUES ('$value','$message','$date')"; } mysql_query($sql) or die ("Error: ".mysql_error()); echo "Database updated."; Any hints or advices ? Thanks for every reply . Similar TutorialsHello all, I am trying to learn OOP in PHP so please forgive my ignorance. I seem to be having difficulty inserting data into my database from checkbox items. My database has a column for each each fruit. I would like for each column to be populated with either a one(1) for checked or a zero(0) for not checked. Currently, my attempts have failed. I can either get all checkboxes to insert all zeros or I can get the first column to insert a one(1) while the others as zeros. Is there anybody here that can help me figure out what I am doing wrong and help me to re-work my code so I can get this to work? If anybody can help me using OOP methods that would be fantastic. Thank you all in advance.
$preffruit->create_preffruit(array( 'fruit_apple' => escape(Input::get(['fruit_selection'][0]) ? 1 : 0), 'fruit_orange' => escape(Input::get(['fruit_selection'][1]) ? 1 : 0), 'fruit_banana' => escape(Input::get(['fruit_selection'][2]) ? 1 : 0), 'fruit_pear' => escape(Input::get(['fruit_selection'][3]) ? 1 : 0), 'fruit_kiwi' => escape(Input::get(['fruit_selection'][4]) ? 1 : 0) )); <input type="checkbox" name="fruit_selection[]" value="fruit_apple"> <input type="checkbox" name="fruit_selection[]" value="fruit_orange"> <input type="checkbox" name="fruit_selection[]" value="fruit_banana"> <input type="checkbox" name="fruit_selection[]" value="fruit_pear"> <input type="checkbox" name="fruit_selection[]" value="fruit_kiwi"> public function insert_preffruit($table, $fields = array()) { $keys = array_keys($fields); $values = ''; $x = 1; foreach($fields as $field) { $values .= '?'; if($x < count($fields)) { $values .= ', '; } $x++; } $sql = "INSERT INTO preffruit (`user_id`, `" . implode('`, `', $keys) . "`) VALUES (LAST_INSERT_ID(), {$values})"; if(!$this->query($sql, $fields)->error()) { return true; } return false; } Edited September 23, 2020 by ke-jo Ok I'm trying to insert multiple rows by using a while loop but having problems. At the same time, need to open a new mysql connection while running the insert query, close it then open the previous mysql connection. I managed to insert multiple queries before using a loop, but for this time, the loop does not work? I think it is because I am opening another connection... yh that would make sense actually? Here is the code: $users = safe_query("SELECT * FROM ".PREFIX."user"); while($dp=mysql_fetch_array($users)) { $username = $dp['username']; $nickname = $dp['nickname']; $pwd1 = $dp['password']; $mail = $dp['email']; $ip_add = $dp['ip']; $wsID = $dp['userID']; $registerdate = $dp['registerdate']; $birthday = $dp['birthday']; $avatar = $dp['avatar']; $icq = $dp['icq']; $hp = $dp['homepage']; echo $username." = 1 username only? :("; // ----- Forum Bridge user insert ----- $result = safe_query("SELECT * FROM `".PREFIX."forum`"); $ds=mysql_fetch_array($result); $forum_prefix = $ds['prefix']; define(PREFIX_FORUM, $forum_prefix); define(FORUMREG_DEBUG, 0); $con = mysql_connect($ds['host'], $ds['user'], $ds['password']) or system_error('ERROR: Can not connect to MySQL-Server'); $condb = mysql_select_db($ds['db'], $con) or system_error('ERROR: Can not connect to database "'.$ds['db'].'"'); include('../_phpbb_func.php'); $phpbbpass = phpbb_hash($pwd1); $phpbbmailhash = phpbb_email_hash($mail); $phpbbsalt = unique_id(); safe_query("INSERT INTO `".PREFIX_FORUM."users` (`username`, `username_clean`, `user_password`, `user_pass_convert`, `user_email`, `user_email_hash`, `group_id`, `user_type`, `user_regdate`, `user_passchg`, `user_lastvisit`, `user_lastmark`, `user_new`, `user_options`, `user_form_salt`, `user_ip`, `wsID`, `user_birthday`, `user_avatar`, `user_icq`, `user_website`) VALUES ('$username', '$username', '$phpbbpass', '0', '$mail', '$phpbbmailhash', '2', '0', '$registerdate', '$registerdate', '$registerdate', '$registerdate', '1', '230271', '$phpbbsalt', '$ip_add', '$wsID', '$birthday', '$avatar', '$icq', '$hp')"); if (FORUMREG_DEBUG == '1') { echo "<p><b>-- DEBUG -- : User added: ".mysql_affected_rows($con)."<br />"; echo "<br />-- DEBUG -- : Query used: ".end($_mysql_querys)."</b></p><br />"; $result = safe_query("SELECT user_id from ".PREFIX_FORUM."users WHERE username = '$username'"); $phpbbid = mysql_fetch_row($result); safe_query("INSERT INTO `".PREFIX_FORUM."user_group` (`group_id`, `user_id`, `group_leader`, `user_pending`) VALUES ('2', '$phpbbid[0]', '0', '0')"); safe_query("INSERT INTO `".PREFIX_FORUM."user_group` (`group_id`, `user_id`, `group_leader`, `user_pending`) VALUES ('7', '$phpbbid[0]', '0', '0')"); mysql_close($con); } include('../_mysql.php'); mysql_connect($host, $user, $pwd) or system_error('ERROR: Can not connect to MySQL-Server'); mysql_select_db($db) or system_error('ERROR: Can not connect to database "'.$db.'"'); } So I need to be able to insert these rows using the while loop.. how can I do this? I really appreciate any help. For instance if i set the following 2x variables; "$varOne = $_GET[first_name]" "$varTwo = $_GET[last_name]" "$varThree = $_GET[userid]" how do i insert them both together into a DB field for example: $full = $varOne,$varTwo,$varThree (without the , ) this would then be echo as : joebloggs66985 i have the INSERT in there atm but i wanted to insert first name and last name together with there userid to generate a sort of username possibility. sorry if i didnt explain correcly Hi all I am trying to take the data from a form and add into a mySQL table. I have multiple forms on one page that uses a loop: Code: [Select] <?php $textqty = $showbasket['qty']; for ($i = 1; $i <= $textqty ; $i++) { ?> <form id="texts" name="texts" method="post" action=""> <input name="mainqty" type="hidden" value="<?php echo $textqty; ?>" /> <input name="productid" type="hidden" value="<?php echo $showbasket['productid']; ?>" /> <input name="productqtyid" type="hidden" value="<?php echo $i; ?>" /> <input name="productsize" type="hidden" value="<?php echo $showbasket['size']; ?>" /> Text: <input name="text_<?php echo $i; ?>" type="text" value="<?php echo $showtext['text']; ?>" size="35" maxlength="250" /> Colour: <select name="colour"> <?php $getcolours = mysql_query(" SELECT * FROM text_colours ORDER BY id ASC"); while($showcolours = mysql_fetch_array($getcolours)) { ?> <option value="<?php echo $showcolours['colour']; ?>"><?php echo $showcolours['colour']; ?></option> <?php } ?> </select> No. Characters: <br /> <?php } ?> <input name="update" type="submit" id="update" value="Update" /> </form> This data is then inserted into the mySQL: Code: [Select] <?php if(isset($_POST['update'])) { $mqty = $_POST['mainqty']; for ($i = 1; $i <= $mqty ; $i++) { $productid = $_POST['productid']; $productqtyid = $_POST['productqtyid']; $productsize = $_POST['productsize']; $colour = $_POST['colour']; $producttext = $_POST['text_$i']; mysql_query (" INSERT INTO emb_texts SET sessionid = '".$sessionid."', productid = '".$productid."', qtyid = '".$productqtyid."', size = '".$productsize."', colour = '".$colour."', text = '".$producttext."'") or die(mysql_error()); } } ?> This almost works but it adds the $productqtyid the same very time. I'm not sure if I am going about the the right way? Each form needs to add its own values into the mySQL. Many thanks for your help
Array ( [data] => Array ( [0] => Array ( [latitude] => 22.934566 [longitude] => 79.08728 [type] => county [distance] => 44.328 [name] => Narsinghpur [number] => [postal_code] => [street] => [confidence] => 0.5 [region] => Madhya Pradesh [region_code] => MP [county] => Narsinghpur [locality] => [administrative_area] => [neighbourhood] => [country] => India [country_code] => IND [continent] => Asia [label] => Narsinghpur, India ) ) ) Hi guys, I have an array: array ( [apple]=> red, [orange] => orange, [banana] => yellow ) That I want to insert into the apidata table, the PDO connection is good so I guess my code is wrong: $mykeys = implode(', ', array_keys($newarr)); $myplaceholders[] = '(' . implode (", ", array_fill(0, count($newarr), '?')) . ')'; $values = array_values($newarr); $res = $db->prepare("INSERT INTO apidata (item, value) VALUES $myplaceholders") ; $res->execute([$mykeys, $values]); The apidata table has three fields id (auto_increment) item and value, where am I going wrong? Thanks I’m trying to insert from a multiple option form into MySQL. I’ve tried numerous methods and have had issues such as blank entries being inserted for each specified column, to the last value selected from the form being inserted multiple times, but I never get the desired outcome. Any guidance on how to insert from this type of HTML form? I know that there are issues regarding SQL injection - I'll worry about that later. I'd like to understand how to insert data from this kind of HTML form into MySQL, as i can't seem to find any guidance. There's plenty on how to insert from a standard HTML form i.e. where either every value is selected or left blank, but each entry corresponds to a column in MySQL which either receives a value or NULL. I'm really struggling with when a user can select more than one option from a list. Quote
<form action ='insert.php' method='POST'>
Here’s one option I’ve tried for PHP Quote
<?php
{ { } $conn->close(); ?>
Hi. I'm making a private webpage for my self where i can post news, games, music titles and movies. I'm made it so that i can post and delete them from my page. Also i wanted to have the option to edit them. So i made a action that shows me a list og the posts in each category. And then i want the option to hit UPDATE, and then it should open the form with the info's from MySQL. I've made those two options as the following: Code: [Select] elseif ( $action == "EditNews" ) { // EDIT NEWS START if ( !$_GET['id'] ) { ?> <div id="content"> <?php $sql = mysql_query("SELECT * FROM news") or die(mysql_error()); while ( $row = mysql_fetch_assoc($sql) ) { echo "<a href=\"?page=Admin&action=UpdateNews&id=" . $row['news_id'] . "\">Update</a> | " . $row['subject'] . "<br>"; } echo "</div>"; } else { $type = $_GET['type']; $id = $_GET['id']; } // EDIT NEWS END } elseif ( $action == "UpdateNews" ) { // UPDATE NEWS START if ( !$_POST['submit'] ) { $id = $_GET['id']; $sql = mysql_query("SELECT * FROM news WHERE news_id='$id'") or die(mysql_error()); $user_id = $_SESSION['uid']; $subject = $_row['subject']; $body = nl2br($_row['body']); ?> <div id="content"> <form action="?page=Admin&action=EditNews" method="post"> <div id="">Subject</div> <div id=""><input id="input" type="text" name="subject"></div> <div id="">Message</div> <div id=""><textarea id="input" name='body' cols='15' rows='4'></textarea></div> <div id=""><input id="submit" class="input" type="submit" name="submit" value="Post News"></div> </form> </div> <?php } else { ?> <div id="content">Not Working!</div> <?php } // UPDATE NEWS END } - I know i miss something, but i've tried to get to the point, where i only have the form as blank, and need some help from there. I hope someone can help me with my problem. MOD EDIT: [code] . . . [/code] tags added. I am trying to display data from mysql. Each row from the mysql database shows up under rows. I want the rows of data from mysql to appear in colums of 4. can some one help please. <?php $sql = 'SELECT * FROM dbtable ORDER BY id'; $result = $db->query($sql); $output[] = '<ul>'; while ($row = $result->fetch()) { $output[] = '<table>'; $output[] = '<tr>'; $output[] = '<td class="style10"><strong>'.$row['item'].'</strong></td>'; $output[] = '</tr>'; $output[] = '<tr>'; $output[] = '<td><img src="images/'.$row['pic'].'" width="100" height="150" /></td>'; $output[] = '</tr>'; $output[] = '<tr>'; $output[] = '<td>'.$row['description'].'</td>'; $output[] = '</tr>'; $output[] = '</table>'; } echo join('',$output); ?> Hi, I'm having trouble adding data to the database (test) that i created. I just can't see where I'm going wrong. need some other peoples opinions. I have tried taking the id out of the SQL statement completely as it is an auto increment, but that doesn't seem to work either. Thanks in advance... <?php $fname = $_POST['fname']; $sname = $_POST['sname']; $email = $_POST['email']; $pword = $_POST['password']; $gender = $_POST['gender']; $user_name = "root"; $password = ""; $database = "test"; $server = "127.0.0.1"; $db_handle = mysql_connect($server, $user_name, $password); $db_found = mysql_select_db($database, $db_handle); if ($db_found) { $SQL = "INSERT INTO members (id, fname, sname, email, password, gender) VALUES (NULL, $fname, $sname, $email, $pword, $gender);"; $result = mysql_query($SQL); mysql_close($db_handle); print "Thanks for joining us ".$fname."."; print "<br /><br />"; print $fname . "<br />"; print $sname . "<br />"; print $email . "<br />"; print $pword . "<br />"; print $gender . "<br />"; } else { print "Database NOT Found"; mysql_close($db_handle); } ?> Hi to everybody I need ur help because I’m trying to make a script in php to write the same data but with different date in MySQL depending on the splitting ($data06).... like a schedule...
For example if $data06 = annual and $data03 = “2019/01/01” programm must create in MySQL : 2019/01/01 2020/01/01 2021/01/01 2022/01/01 2023/01/01
if $data06=“half year” will create 10 date , increasing 6 moths ...
But I have a problem at finish of code switch ($data06) { case 'annual': $numrate = 5; $aumdata = "+12 months"; break; case 'half year': $numrate = 10; $aumdata = "+6 month"; break;
default: echo "error"; $sql = "INSERT into $nometb ( name, scadenza ) values ( '$data01', '$data03' )"; if ($conna->query($sql) === TRUE) {} else {die('ERROR'. $conna->error); }
//IMPORT NEXT AND NEW DATE $newDate = date_create($data03); for ($mul = 2; $mul <= $numrate; ++$mul) {
$datanuova = date_create($data03); $datanuova->modify($aumdata); $datanuova->format('yy/m/d'); $newDate = $datanuova->format('yy/m/d');
$sql = "INSERT into $nometb ( name, scadenza ) values ( '$data01', '$newDate' )"; if ($conna->query($sql) === TRUE) {} else {die('ERROR'. $conna->error); }
//HERE THERE IS ERROR $data03 = $newDate;
if ($conna->query($sql) === TRUE) {} else {die('ERRORE NELL\'IMPORTAZIONE'. $conna->error); } }
} }
}
How I can resolve ?
many thanks Francesco Hi all. Here is the code:(thanks to jcbones) Code: [Select] if (($handle = fopen($source_file, "r")) !== FALSE) { $columns = fgetcsv($handle, $max_line_length, ","); foreach ($columns as &$column) { $column = str_replace(".","",$column); } while (($data = fgetcsv($handle, $max_line_length, ",")) !== FALSE) { while(count($data) < count($columns)) { array_push($data, NULL); } $c = count($data); for($i = 0; $i < $c; $i++) { $data[$i] = "'{$data[$i]}'"; } $sql[] = '(' . implode(',',$data) . ','.$_POST[group].')'; } $sql = implode(',',$sql); $query = "INSERT INTO mytable (".mysql_real_escape_string(implode(",",$columns)).",Custgroup,user_id) VALUES " . $sql . "\n"; mysql_query($query) or trigger_error(mysql_error()); fclose($handle); } } If my csv file is: lastname,firstname,gender bob,ah,male So now the query will be : INSERT INTO mytable (lastname,firstname,gender) VALUES ('bob',ah','male'). But how if I want to insert extra data into mysql together with the data in csv file? Such as I have a value $_POST['group'] = 'family', so I tried: Code: [Select] $sql[] = '(' . implode(',',$data) . ','.$_POST[group].')'; $query = "INSERT INTO $target_table (".mysql_real_escape_string(implode(",",$columns)).",custgroup) VALUES " . implode(',',$sql) . "\n"; But in the query it will become : INSERT INTO mytable (lastname,firstname,gender,custgroup) VALUES ('bob',ah','male',family). It didn't have single quote , so I have error to insert the record.Can I know how to solve this problem? Thanks. Hi there, hope u guys able to help. I'm have created a enquiry form where I want these actions to run when a button is submitted: 1. Insert data from form fields into my database 2. When data is inserted into database, then send an e-mail (multiple email user) to the address with the form fields. The e-mail is carrying the form fields. so ...what I need now is how to send the form field to email. Insert the data into my table in my database,then send en e-mail. Code: [Select] <? // Connects to your Database mysql_connect("xxxxxx","xxxxxx","xxxxxx") or die(mysql_error()); mysql_select_db("xxxxxx") or die(mysql_error()); // now we insert it into the database $insert = "INSERT INTO enquiry (name, email, cont_number, subject, msg) VALUES ('".$_POST['name']."', '".$_POST['email']."', '".$_POST['cont_number']."', '".$_POST['subject']."','".$_POST['msg']."')"; $add_member = mysql_query($insert); ?> <?php function error_bool($error, $field) { if($error[$field]) { print("<td style=color:red>"); } else { print("<td>"); } } function show_form() { global $HTTP_POST_VARS, $print_again, $error; ?> <h2 align="center"> Enquiry Form</h2> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> <table align="center" cellpadding="3"> <tr> <?php error_bool($error, "name"); ?> Name </td> <td>:<input name="name" type="text" id="name" SIZE="33" value="<? echo $_POST["name"]; ?>"></td> </tr> <tr> <?php error_bool($error, "email"); ?> Email </td> <td>:<input name="email" type="text" id="email" SIZE="33" value="<? echo $_POST["email"]; ?>"></td> </tr> <tr><td>Contact No. </td><td> :<input type="text" name="cont_number" SIZE="33" maxlength="10"> </td></tr> <tr><td>Subject </td><td> :<input type="text" name="subject" SIZE="33" maxlength="25"> </td></tr> <tr><td>Your Message :</td><td> <textarea name="msg" cols="27" rows="5" wrap="virtual"></textarea> </td></tr> <tr> <td><th colspan=4 align="right"> <input type="reset" value="CLEAR"><input type="submit" name="Submit" value="Submit"></td> </th><td> </td> </tr> </table> </form> <? } if(isset($_POST["Submit"])) { check_form(); } else { show_form(); } function check_email_address($email) { // First, we check that there's one @ symbol, and that the lengths are right if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)) { // Email invalid because wrong number of characters in one section, or wrong number of @ symbols. return false; } // Split it into sections to make life easier $email_array = explode("@", $email); $local_array = explode(".", $email_array[0]); for ($i = 0; $i < sizeof($local_array); $i++) { if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i])) { return false; } } if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) { // Check if domain is IP. If not, it should be valid domain name $domain_array = explode(".", $email_array[1]); if (sizeof($domain_array) < 2) { return false; // Not enough parts to domain } for ($i = 0; $i < sizeof($domain_array); $i++) { if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i])) { return false; } } } return true; } function check_form() { global $HTTP_POST_VARS, $error, $print_again; $error['name'] = false; if($_POST["name"]=="") { $error['name'] = true; $print_again = true; $message="The name field is empty<br>"; } if(!check_email_address($_POST['email'])) { $error['email'] = true; $print_again = true; $message.="Either Field Empty or Invalid Email ID <br>"; } if($print_again) { show_form(); } else { show_form(); $message="Thank You !! <br> Form has been submitted"; } echo "$message"; } ?> </body> </html> How do i do this? Thank you in advanced and sorry for bad English. Best regards, Desmond how i can make a insert using this fuctions I m learning php, as using this functions (mysqli abstract) but after update wont work any more.
/** insert data array */ public function insert(array $arr) { if ($arr) { $q = $this->make_insert_query($arr); $return = $this->modifying_query($q); $this->autoreset(); return $return; } else { $this->autoreset(); return false; } }complement /** insert query constructor */ protected function make_insert_query($data) { $this->get_table_info(); $this->set_field_types(); if (!is_array(reset($data))) { $data = array($data); } $keys = array(); $values = array(); $keys_set = false; foreach ($data as $data_key => $data_item) { $values[$data_key] = array(); $fdata = $this->parse_field_names($data); foreach ($fdata as $key => $val) { if (!$keys_set) { if (isset($this->field_type[$key])) { $keys[] = '`' . $val['table'] . '`.`' . $val['field'] . '`'; } else { $keys[] = '`' . $val['field'] . '`'; } } $values[$data_key][] = $this->escape($val['value'], $this->is_noquotes($key), $this->field_type($key), $this->is_null($key), $this->is_bit($key)); } $keys_set = true; $values[$data_key] = '(' . implode(',', $values[$data_key]) . ')'; } $ignore = $this->ignore ? ' IGNORE' : ''; $delayed = $this->delayed ? ' DELAYED' : ''; $query = 'INSERT' . $ignore . $delayed . ' INTO `' . $this->table . '` (' . implode(',', $keys) . ') VALUES ' . implode(',', $values); return $query; }before update this class i used to insert data like this $db = Sdba::table('users'); $data = array('name'=>'adam'); $db->insert($data);this method of insert dont works on new class. if i try like this i got empty columns and empty values. thanks for any help complete class download http://goo.gl/GK3s4E Hello guys, im using this code atm and it's working, but the new rows created are put in the end of the table. I want them to stack up from the beginning pushing older rows down. What should i do to make that work? <?php $con = mysql_connect("localhost","*****","*******"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("ananaz_se", $con); $sql="INSERT INTO stuff (adult, namn, url) VALUES ('$_POST[adult]','$_POST[namn]','$_POST[url]')"; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } echo "1 row added"; mysql_close($con) ?> I'm Trying to INSERT Data into mysql which is generated from biomatric attendance device. what i wanted to do is to save these data into mysql database. <?php include 'db.php'; ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script> <!-- <script type="text/javascript" src="load.js"></script> --> <link rel="stylesheet" href="style.css"> <title>Live Attendance</title> </head> <?php include("zklib/zklib.php"); $zk = new ZKLib("192.168.1.3", 4370); $ret = $zk->connect(); sleep(1); if ( $ret ): $zk->disableDevice(); sleep(1); ?> <body> <table border="1" cellpadding="5" cellspacing="2" style="float: left; margin-right: 10px;"> <tr> <th colspan="5">Data User</th> </tr> <tr> <th>UID</th> <th>ID</th> <th>Name</th> <th>Role</th> <th>Password</th> </tr> <?php try { //$zk->setUser(1, '1', 'Admin', '', LEVEL_ADMIN); $user = $zk->getUser(); sleep(1); while(list($uid, $userdata) = each($user)): if ($userdata[2] == LEVEL_ADMIN) $role = 'ADMIN'; elseif ($userdata[2] == LEVEL_USER) $role = 'USER'; else $role = 'Unknown'; ?> <tr> <td><?php echo $uid ?></td> <td><?php echo $userdata[0] ?></td> <td><?php echo $userdata[1] ?></td> <td><?php echo $role ?></td> <td><?php echo $userdata[3] ?> </td> </tr> <?php endwhile; } catch (Exception $e) { header("HTTP/1.0 404 Not Found"); header('HTTP', true, 500); // 500 internal server error } //$zk->clearAdmin(); if (isset($_POST['create_post'])) { $query = "INSERT INTO attendance(idx)"; $query .= "VALUES ($id)"; $submittodbquery = mysqli_query($con,$query); if (!$submittodbquery) { die("Failed up upload " . mysqli_error($con)); }else { echo "updated"; } } ?> </table> <button id="submit" type="submit" name="create_post" class="btn btn-danger">Submit New Post</button> <?php $name = $userdata[1]; $attendance = $zk->getAttendance(); sleep(1); while(list($idx, $attendancedata ) = each($attendance)): if ( $attendancedata[2] == 1 ) $status = 'Check Out'; else $status = 'Check In'; ?> <?php $idx ?> <?php $attendancedata[0] ?> <?php $attendancedata[1] ?> <?php $status ?> <?php date( "d-m-Y", strtotime( $attendancedata[3] ) ) ?> <?php date( "H:i:s", strtotime( $attendancedata[3] ) ) ?> <?php // custom code if (isset($_POST['submit'])) { $query = "INSERT INTO attendance(idx)"; $query .= "VALUES ($idx)"; $submittodbquery = mysqli_query($con,$query); if (!$submittodbquery) { die("Failed up upload " . mysqli_error($con)); }else { echo "updated"; } } ?> <?php endwhile ?> </table> <input type="submit" name="submit" value="Update Database"> <?php $zk->enableDevice(); sleep(1); $zk->disconnect(); endif ?> </body> </html> Thanks for reading my question ..
Hi I have been trying to grab some data from an XML feed parse it and then insert it into a database. I will only need to do this on one occasion so no update or deletes. Sample of xml structu Code: [Select] <property> <id>34935</id> <date>2009-11-03 06:52:45</date> <ref>SVS0108</ref> <price>450000</price> <currency>EUR</currency> <price_freq>sale</price_freq> </property> Using xml2array class to parse the feed: <?php /** * xml2array Class * Uses PHP 5 DOM Functions * * This class converts XML data to array representation. * */ class Xml2Array { /** * XML Dom instance * * @var XML DOM Instance */ private $xml_dom; /** * Array representing xml * * @var array */ private $xml_array; /** * XML data * * @var String */ private $xml; public function __construct($xml = '') { $this->xml = $xml; } public function setXml($xml) { if(!empty($xml)) { $this->xml = $xml; } } /** * Change xml data-to-array * * @return Array */ public function get_array() { if($this->get_dom() === false) { return false; } $this->xml_array = array(); $root_element = $this->xml_dom->firstChild; $this->xml_array[$root_element->tagName] = $this->node_2_array($root_element); return $this->xml_array; } private function node_2_array($dom_element) { if($dom_element->nodeType != XML_ELEMENT_NODE) { return false; } $children = $dom_element->childNodes; foreach($children as $child) { if($child->nodeType != XML_ELEMENT_NODE) { continue; } $prefix = ($child->prefix) ? $child->prefix.':' : ''; if(!is_array($result[$prefix.$child->nodeName])) { $subnode = false; foreach($children as $test_node) { if($child->nodeName == $test_node->nodeName && !$child->isSameNode($test_node)) { $subnode = true; break; } } } else { $subnode = true; } if ($subnode) { $result[$prefix.$child->nodeName][] = $this->node_2_array($child); } else { $result[$prefix.$child->nodeName] = $this->node_2_array($child); } } if (!is_array($result)) { $result['#text'] = html_entity_decode(htmlentities($dom_element->nodeValue, ENT_COMPAT, 'UTF-8'), ENT_COMPAT,'ISO-8859-15'); } if ($dom_element->hasAttributes()) { foreach ($dom_element->attributes as $attrib) { $prefix = ($attrib->prefix) ? $attrib->prefix.':' : ''; $result["@".$prefix.$attrib->nodeName] = $attrib->nodeValue; } } return $result; } /** * Generated XML Dom * */ private function get_dom() { if(empty($this->xml)) { echo 'No XML found. Please set XML data using setXML($xml)'; return false; } $this->xml_dom = @DOMDocument::loadXML($this->xml); if($this->xml_dom) { return $this->xml_dom; } echo 'Invalid XML data'; exit; } } ?> My results page: <?php require_once('classes/xml2array.php'); require_once('conn.php'); function curlURL($url) { $ch= curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.2) Gecko/20070219 Firefox/2.0.0.2'); $output = curl_exec($ch); return $output; } $curlResults = curlURL("http://localhost/alphashare_dump/property.xml"); $xml = $curlResults; $converter = new Xml2Array(); $converter->setXml($xml); $xml_array = $converter->get_array(); $array = ($xml_array['root']['property']); echo "<pre>"; print_r($array); echo "</pre>"; ////////////// INSERT DATA INTO DB //////////////////////////////////////////////////// ?> My array structure looks like this: Code: [Select] Array ( [0] => Array ( [id] => Array ( [#text] => 34935 ) [date] => Array ( [#text] => 2009-11-03 06:52:45 ) [ref] => Array ( [#text] => SVS0108 ) [price] => Array ( [#text] => 450000 ) [currency] => Array ( [#text] => EUR ) [price_freq] => Array ( [#text] => sale ) [part_ownership] => Array ( [#text] => 0 ) Can somebody help with actually getting this into some format that will enable me to insert this into my database please GT hi there..im new to php mysql and im having trouble inserting a string data to mysql from a php date() function. here's my code: Code: [Select] $year = date('Y'); echo $year; $insertSQL = sprintf("INSERT INTO tbl_elections (election_id=$year)"); mysql_select_db($database_organizazone_db, $organizazone_db); $Result1 = mysql_query($insertSQL, $organizazone_db) or die(mysql_error()); when i try to output the $year variable on a webpage, it returns "2012" but when i try to insert this data into my database table, it returns an error like this: check the manual that corresponds to your MySQL server version for the right syntax to use near '=2012)' is there a way to convert "2012" into a normal string data type? Not sure exactly what my problem is here, but i have looked at this at least a hundred times and I just can't figure out what is going on. Everything works great except for the sending the email part. It displays the error "There was a problem sending the mail". The form field checking works fine, the insert into mysql works fine - - but it won't send the email. I have tried using double quotes and single quotes for the email information ($to, $subject, etc...) I have even eliminated the form data from the email information and it still doesn't send. I am hopelessly stuck at this point Any ideas?? Code below: <html> <body bgcolor = 'blue'> <div align = 'center'> <h1>test FORM</h1> </div> <p> <?php If ($_POST['submit']) //if the Submit button pressed { //collect form data $fname = $_POST['FName']; $lname = $_POST['LName']; $email = $_POST['Email']; $tel = $_POST['Tel']; $mess = $_POST['Mess']; $errorstring = ""; if (!$fname) $errorstring = $errorstring."First Name<br>"; if (!$lname) $errorstring = $errorstring."Last Name<br>"; if (!$email) $errorstring = $errorstring."Email<br>"; if ($errorstring !="") echo "<div align = 'center'><b>Please fill out the following fields:</b><br><font color = 'red'><b>$errorstring</b></font></div>"; else { $fname = mysql_real_escape_string($fname); $lname = mysql_real_escape_string($lname); $email = mysql_real_escape_string($email); $tel = mysql_real_escape_string($tel); $mess = mysql_real_escape_string($mess); $con = mysql_connect("localhost","user","password"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("mec", $con); $sql="INSERT INTO formtest (FName, LName, Title, Tel, Email, Mess) VALUES ('$fname','$lname','$title','$tel','$email','$mess')"; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } $to = 'myemailaddress'; $subject = 'test form'; $message = 'Hello'; $headers = 'From Me'; $sent = mail($to, $subject, $message, $headers); if($sent) {print "Email successfully sent";} else {print "There was an error sending the mail";} mysql_close($con); } } ?> <p> <form action= 'testmecform.php' method= 'POST'> <table width = '640' border = '0' align = 'center'> <tr> <td align = 'right'><b>First Name</b></td> <td><input type = 'text' name = 'FName' value = '<?php echo $fname; ?>' size = '25'></td> <td><div align = 'right'><b>Telephone</b></div></td> <td><input type = 'text' name = 'Tel' value = '<?php echo $tel; ?>' size = '25'></td> </tr> <tr> <td align = 'right'><b>Last Name</b></td> <td><input type = 'text' name = 'LName' value = '<?php echo $lname; ?>' size = '25'></td> <td> </td> <td> </td> </tr> <tr> <td align = 'right'><b>Email</b></td> <td><input type = 'text' name = 'Email' value = '<?php echo $email; ?>' size = '25'></td> <td> </td> <td> </td> </tr> <tr> <th colspan = '4'><b>Please enter any additional information he </b></th> </tr> <tr> <th colspan = '4'><textarea name = 'Mess' cols = '50' rows = '10'><?php echo $mess; ?></textarea></th> </tr> <tr> <th colspan = '4'><b>Please make sure all information is correct before submitting</b></th> </tr> <tr> <th colspan = '4'><input type = 'submit' name = 'submit' value = 'Submit Form'></th> </tr> </table> </form> </body> </html> |