Rectangle 27 12

BEWARE !! of "LAST_INSERT_ID()" if trying to return this primary key value within PHP.

I know this thread is not tagged php, but for anybody who came across this answer looking to return a MySQL insert id from a PHP scripted insert using standard mysql_query calls - it wont work and is not obvious without capturing SQL errors.

The newer mysqli supports multiple queries - which LAST_INSERT_ID() actually is a second query from the original.

IMO a separate SELECT to identify the last primary key is safer than the optional mysql_insert_id() function returning the AUTO_INCREMENT ID generated from the previous INSERT operation.

LAST_INSERT_ID is a per-connection MySQL function. If you query for the last insert ID it is possible a separate connection will have performed a write and you will have the wrong ID.

@ExplosionPills mysql_insert_id() also works on a per connection basis, but it also suffers strange behaviour as seen here stackoverflow.com/a/897374/1305910 in the comment by Cliffordlife -- nevermind we should all have been using mysqli

Get the new record primary key ID from mysql insert query? - Stack Ove...

mysql insert key auto-increment
Rectangle 27 1

<?php
    mysql_connect("localhost","root","");
    mysql_select_db("school");
?>

<html>
    <head>
        <script type="text/javascript" src="../js/exp_stdsub.js"></script>
    </head>
       <hr />
                            <u><h3>Export your Data here</h3></u>
                            <form action="" method="post"> 
                                        <select name="expstd" id="expstd" onclick="return expsubjs(this.value);">
                                            <option>Select Standared</option>
                                    <?php
                                        $exe_sel_std = mysql_query("SELECT * from s_standared");
                                        while($r_sel_std = mysql_fetch_array($exe_sel_std)){
                                            $sel_stdid = $r_sel_std['std_id'];
                                            $sel_std = $r_sel_std['std']; ?>
                                            <option value="<?php echo $sel_stdid; ?>"><?php echo $sel_std; ?></option>
                                            <?php  } ?>
                                            </select></td>


                                <input type="submit" class="btn btn-green" name="exp_stdque" value="Export Standardwise Question">

                            </form>
                        </table>

<?php

//EDIT YOUR MySQL Connection Info:
$DB_Server = "localhost";        //your MySQL Server
$DB_Username = "root";                 //your MySQL User Name
$DB_Password = "";                //your MySQL Password
$DB_DBName = "school";                //your MySQL Database Name
$DB_TBLName = "s_question";                //your MySQL Table Name

if(isset($_POST['exp_stdque'])) {
    $exstdid = $_POST['expstd'];

//$DB_TBLName,  $DB_DBName, may also be commented out & passed to the browser
//as parameters in a query string, so that this code may be easily reused for
//any MySQL table or any MySQL database on your server

//DEFINE SQL QUERY:
//edit this to suit your needs
$sql = "Select * from $DB_TBLName WHERE std_id = $exstdid";

//Optional: print out title to top of Excel or Word file with Timestamp
//for when file was generated:
//set $Use_Titel = 1 to generate title, 0 not to use title
$Use_Title = 1;
//define date for title: EDIT this to create the time-format you need
$now_date = DATE('m-d-Y H:i');
//define title for .doc or .xls file: EDIT this if you want
$title = "Dump For Table $DB_TBLName from Database $DB_DBName on $now_date";
/*

Leave the connection info below as it is:
just edit the above.

(Editing of code past this point recommended only for advanced users.)
*/
//create MySQL connection
$Connect = @MYSQL_CONNECT($DB_Server, $DB_Username, $DB_Password)
     or DIE("Couldn't connect to MySQL:<br>" . MYSQL_ERROR() . "<br>" . MYSQL_ERRNO());
//select database
$Db = @MYSQL_SELECT_DB($DB_DBName, $Connect)
     or DIE("Couldn't select database:<br>" . MYSQL_ERROR(). "<br>" . MYSQL_ERRNO());
//execute query
$result = @MYSQL_QUERY($sql,$Connect)
     or DIE("Couldn't execute query:<br>" . MYSQL_ERROR(). "<br>" . MYSQL_ERRNO());

//if this parameter is included ($w=1), file returned will be in word format ('.doc')
//if parameter is not included, file returned will be in excel format ('.xls')
IF (ISSET($w) && ($w==1))
{
     $file_type = "msword";
     $file_ending = "doc";
}ELSE {
     $file_type = "vnd.ms-excel";
     $file_ending = "xls";
}
//header info for browser: determines file type ('.doc' or '.xls')
HEADER("Content-Type: application/$file_type");
HEADER("Content-Disposition: attachment; filename=database_dump.$file_ending");
HEADER("Pragma: no-cache");
HEADER("Expires: 0");

/*    Start of Formatting for Word or Excel    */

IF (ISSET($w) && ($w==1)) //check for $w again
{
     /*    FORMATTING FOR WORD DOCUMENTS ('.doc')   */
     //create title with timestamp:
     IF ($Use_Title == 1)
     {
         ECHO("$title\n\n");
     }
     //define separator (defines columns in excel & tabs in word)
     $sep = "\n"; //new line character

     WHILE($row = MYSQL_FETCH_ROW($result))
     {
         //set_time_limit(60); // HaRa
         $schema_insert = "";
         FOR($j=0; $j<mysql_num_fields($result);$j++)
         {
         //define field names
         $field_name = MYSQL_FIELD_NAME($result,$j);
         //will show name of fields
         $schema_insert .= "$field_name:\t";
             IF(!ISSET($row[$j])) {
                 $schema_insert .= "NULL".$sep;
                 }
             ELSEIF ($row[$j] != "") {
                 $schema_insert .= "$row[$j]".$sep;
                 }
             ELSE {
                 $schema_insert .= "".$sep;
                 }
         }
         $schema_insert = STR_REPLACE($sep."$", "", $schema_insert);
         $schema_insert .= "\t";
         PRINT(TRIM($schema_insert));
         //end of each mysql row
         //creates line to separate data from each MySQL table row
         PRINT "\n----------------------------------------------------\n";
     }
}ELSE{
     /*    FORMATTING FOR EXCEL DOCUMENTS ('.xls')   */
     //create title with timestamp:
     IF ($Use_Title == 1)
     {
         ECHO("$title\n");
     }
     //define separator (defines columns in excel & tabs in word)
     $sep = "\t"; //tabbed character

     //start of printing column names as names of MySQL fields
     FOR ($i = 0; $i < MYSQL_NUM_FIELDS($result); $i++)
     {
         ECHO MYSQL_FIELD_NAME($result,$i) . "\t";
     }
     PRINT("\n");
     //end of printing column names

     //start while loop to get data
     WHILE($row = MYSQL_FETCH_ROW($result))
     {
         //set_time_limit(60); // HaRa
         $schema_insert = "";
         FOR($j=0; $j<mysql_num_fields($result);$j++)
         {
             IF(!ISSET($row[$j]))
                 $schema_insert .= "NULL".$sep;
             ELSEIF ($row[$j] != "")
                 $schema_insert .= "$row[$j]".$sep;
             ELSE
                 $schema_insert .= "".$sep;
         }
         $schema_insert = STR_REPLACE($sep."$", "", $schema_insert);
         //following fix suggested by Josue (thanks, Josue!)
         //this corrects output in excel when table fields contain \n or \r
         //these two characters are now replaced with a space
         $schema_insert = PREG_REPLACE("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
         $schema_insert .= "\t";
         PRINT(TRIM($schema_insert));
         PRINT "\n";
     }
}
}

?>
IMPORTING FROM EXCEL INTO MySQL USING PHP
<table>
                    <form enctype="multipart/form-data" action="" method="post">
                      <input type="hidden" name="MAX_FILE_SIZE" value="2000000" />
                            <tr>
                            <td><h5><b>Select Standared</b></h5></td>
                            <td><select name="chap_sel_std" id="chap_sel_std">
                                                        <option>Select Standared</option>
                                                <?php
                                                    $exe_sel_std = mysql_query("SELECT * from s_standared");
                                                    while($r_sel_std = mysql_fetch_array($exe_sel_std)){
                                                        $sel_stdid = $r_sel_std['std_id'];
                                                        $sel_std = $r_sel_std['std'];?>

                                                        <option value="<?php echo $sel_stdid; ?>"><?php echo $sel_std;?></option>
                                                        <?php } ?>
                                </select></td>
                            </tr>
                            <tr>
                                <td><h5><b>Select Font</b></h5></td>
                                <td><select name="sel_f_gn_que">
                                    <option>Select Font</option>
                                        <?php
                                            $xf = mysql_query("SELECT * from s_font");
                                            while($rquef = mysql_fetch_array($xf)){
                                                $f_id = $rquef['f_id'];
                                                $f_name = $rquef['f_name'];  ?>
                                    <option value="<?php echo $f_id; ?>"><?php echo $f_name; }?>  </option>
                                </select></td>
                            </tr>
                            <tr>
                                <td><h5><b>Upload Question<h5><b></td>
                                <td>
                                    <input type="file" name="file" id="file" class="btn">
                                </td>
                            </tr>
                            <tr>
                                <td></td>
                                <td colspan="2"><input type="submit" class="btn btn-green big" name="add_que" value="Add Questions"></td>
                                <td><input type="submit" name="saveandexit" class="" value="Finish" onclick="close();"></td>
                            </tr>
                    </form>
                    </table>
                    </div>                   

    <?php

            $data = array();

    //$db =& DB::connect("mysql://root@localhost/names", array());
    //if (PEAR::isError($db)) { die($db->getMessage()); }
      //quetype    difficulty    standard    subject    chap    que    marks

    function add_person($quetype,$dif, $subject,$chap_name,$que,$marks)
    {
     global $data, $db;

     //$sth = $db->prepare( "INSERT INTO names VALUES( 0, ?, ?, ?, ? )" );
    // $db->execute( $sth, array( $first, $middle, $last, $email ) );

     $data []= array(
       'quetype' => $quetype, 
       'difficulty' => $dif,
       'subject' => $subject,
       'chap' => $chap_name,
       'que' => $que,
       //'ans' => $ans,
       'marks' => $marks

     );
    }

    if(!isset($_FILES['file']['tmp_name'])){
        echo "";
    }elseif($_FILES['file']['tmp_name'])
    {
     $dom = DOMDocument::load( $_FILES['file']['tmp_name'] );
     $rows = $dom->getElementsByTagName( 'Row' );
     $first_row = true;
     foreach ($rows as $row)
     {
       if ( !$first_row )
       {
         $quetype = "";
         $dif = "";
         $subject = "";
         $chap_name = "";
         $que = "";
         //$ans = "";
         $marks = "";

         $index = 1;
         $cells = $row->getElementsByTagName( 'Cell' );
         foreach( $cells as $cell )
         {
           $ind = $cell->getAttribute( 'Index' );
           if ( $ind != null ) $index = $ind;

           if ( $index == 1 ) $quetype = $cell->nodeValue;
           if ( $index == 2 ) $dif = $cell->nodeValue;
           if ( $index == 4 ) $subject = $cell->nodeValue;
           if ( $index == 6 ) $chap_name = $cell->nodeValue;
           if ( $index == 8) $que = $cell->nodeValue;
           //if ( $index == 9) $ans = $cell->nodeValue;
           if ( $index == 9) $marks = $cell->nodeValue;

           $index += 1;
         }
         add_person($quetype,$dif, $subject,$chap_name,$que,$marks);

         if(isset($_POST['add_que'])){    

                 $chap_sel_std = $_POST['chap_sel_std'];
                 echo $simquefnt = $_POST['sel_f_gn_que'];

                    //que_id    quetype_id    chap_id    sub_id    std_id    que    dif_id    marks    que_cdate
             //$chap_sel_std = $_POST['chap_sel_std']; //que_id    quetype_id    chap_id    sub_id    std_id    que    dif_id    marks    que_cdate
             mysql_query("INSERT INTO 
                          s_question
                          VALUES (null,'$quetype','$chap_name','$subject','$chap_sel_std','$que','NO IMAGE','$dif','$marks','$simquefnt','$current')");                                                        
    //         header("location:../admin/quetionaris.php#tabs-que"); 
         echo "Successfully Added";
          }
       }
       $first_row = false;
     }
    }
    ?>

Export Data in excel and then import from excel using PHP. DB is MySQL...

php mysql excel import export
Rectangle 27 1

Despite the fact that this tutorial is geared toward using Google Maps API, the first half of the tutorial focuses on using PHP to query a database and create a bounding circle in order to search for matches within a given radius and return only those results that match.

In the tutorial, the query is super-fast and outputs the results in XML which is exceptionally useful for integrating into API. I didn't need that functionality, so I simplified mine a little.

Here's what I have - and it works perfectly for what I need:

<?
$username="Your_Database_Username";
$password="Your_Database_Password";
$database="The_Name_of_Your_Database";
?>

When visiting this page, We pass some values to it, as we're using $_GET to collect the 'lat','lng' and 'radius' values.

<?php  
require("phpsqlsearch_dbinfo.php");
// Get parameters from URL
$center_lat = $_GET["lat"];
$center_lng = $_GET["lng"];
$radius = $_GET["radius"];

// Opens a connection to a mySQL server
$connection=mysql_connect (localhost, $username, $password);
if (!$connection) {
  die("Not connected : " . mysql_error());
}
// Set the active mySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
  die ("Can\'t use db : " . mysql_error());
}
// Search the rows in the markers table
$query = sprintf("SELECT id, address, name, lat, lng, ( 3959 * acos( cos( radians('%s') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( lat ) ) ) ) AS distance FROM candidates HAVING distance < '%s' ORDER BY distance LIMIT 0 , 20",
  mysql_real_escape_string($center_lat),
  mysql_real_escape_string($center_lng),
  mysql_real_escape_string($center_lat),
  mysql_real_escape_string($radius));
$result = mysql_query($query);
if (!$result) {
  die("Invalid query: " . mysql_error());
}
while ($row = @mysql_fetch_assoc($result)){
  $ID = mysql_real_escape_string($row['id']);
  $name = mysql_real_escape_string($row['name']);
  $address = mysql_real_escape_string($row['address']);
  $lat = mysql_real_escape_string($row['lat']);
  $lng = mysql_real_escape_string($row['lng']);
  $distance = mysql_real_escape_string($row['distance']);

  echo $name .", ". $address .", Latitude:". $lat .", Longitude:". $lng .", Distance From Home = ". round($distance)." Miles <br /><br />";

   // I then insert these matches into a new table for later use. 
   $new = "INSERT INTO matrix (Marker_ID, Cand_Name, Distance)
    VALUES ('$ID', '$name', '$distance')";

   $resulting = mysql_query($new);
   if (!$resulting) {
     die("Invalid query: " . mysql_error());
   }   
}
?>

Finally, to get this example working, you need to have your database set up. If you don't have access to phpMyAdmin or prefer using SQL commands instead, here's the SQL statement that creates the table:

CREATE TABLE `markers` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`name` VARCHAR( 60 ) NOT NULL ,
`address` VARCHAR( 80 ) NOT NULL ,
`lat` FLOAT( 10, 6 ) NOT NULL ,
`lng` FLOAT( 10, 6 ) NOT NULL
) ENGINE = MYISAM ;

Now for the example data to populate the table: Click Here - This example data set contains 169 rows in total. If you follow the link above, you can copy the full data set in the following format:

INSERT INTO `markers` (`name`, `address`, `lat`, `lng`) VALUES ('Frankie Johnnie & Luigo Too','939 W El Camino Real, Mountain View, CA','37.386339','-122.085823');
INSERT INTO `markers` (`name`, `address`, `lat`, `lng`) VALUES ('Amici\'s East Coast Pizzeria','790 Castro St, Mountain View, CA','37.38714','-122.083235');
INSERT INTO `markers` (`name`, `address`, `lat`, `lng`) VALUES ('Kapp\'s Pizza Bar & Grill','191 Castro St, Mountain View, CA','37.393885','-122.078916');
INSERT INTO `markers` (`name`, `address`, `lat`, `lng`) VALUES ('Round Table Pizza: Mountain View','570 N Shoreline Blvd, Mountain View, CA','37.402653','-122.079354');
INSERT INTO `markers` (`name`, `address`, `lat`, `lng`) VALUES ('Tony & Alba\'s Pizza & Pasta','619 Escuela Ave, Mountain View, CA','37.394011','-122.095528');
INSERT INTO `markers` (`name`, `address`, `lat`, `lng`) VALUES ('Oregano\'s Wood-Fired Pizza','4546 El Camino Real, Los Altos, CA','37.401724','-122.114646');
INSERT INTO `markers` (`name`, `address`, `lat`, `lng`) VALUES ('Round Table Pizza: Sunnyvale-Mary-Central Expy','415 N Mary Ave, Sunnyvale, CA','37.390038','-122.042034');
INSERT INTO `markers` (`name`, `address`, `lat`, `lng`) VALUES ('Giordano\'s','730 N Rush St, Chicago, IL','41.895729','-87.625411');
INSERT INTO `markers` (`name`, `address`, `lat`, `lng`) VALUES ('Filippi\'s Pizza Grotto','1747 India St, San Diego, CA','32.723831','-117.168326');
INSERT INTO `markers` (`name`, `address`, `lat`, `lng`) VALUES ('Lou Malnati\'s Pizzeria','439 N Wells St, Chicago, IL','41.890346','-87.633927');
etc...
etc...

I hope this helps anyone who has struggled as much as I have. With just basic understanding of PHP and MySQL, you'll have this up and running in no time.

php - Return results within a given radius using a bounding circle as ...

php mysqli pdo
Rectangle 27 -1

use this script

So lets start the coding

Steps1: First Create MySQL Database Table:
I have used users table for this login exvample. So used below code to create table.
CREATE TABLE IF NOT EXISTS `users` (
`uid` int(11) NOT NULL AUTO_INCREMENT,
`user` varchar(255) DEFAULT NULL,
`pass` varchar(100) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`profile_photo` varchar(200) DEFAULT NULL,
PRIMARY KEY (`uid`),
UNIQUE KEY `username` (`user`),
UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Steps2: Insert Data into MySQL Table:
Use below code to insert user record to use with login example.
INSERT INTO `users` (`uid`, `user`, `pass`, `email`, `profile_photo`) VALUES
(1, 'phpzag', 'test', 'test@phpzag.com', NULL);

Steps3: We include all necessary library files and JavaScript in head tag in main file index.php:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script type="text/javascript" src="script/validation.min.js"></script>
<script type="text/javascript" src="script/login.js"></script>
<link href="css/style.css" rel="stylesheet" type="text/css" media="screen">

Steps4: Now Create Login Form HTML
Now we will create login form HTML with Bootstarp.
<form class="form-login" method="post" id="login-form">
<h2 class="form-login-heading">User Log In Form</h2><hr />
<div id="error">
</div>
<div class="form-group">
<input type="email" class="form-control" placeholder="Email address" name="user_email" id="user_email" />
<span id="check-e"></span>
</div>
<div class="form-group">
<input type="password" class="form-control" placeholder="Password" name="password" id="password" />
</div>
<hr />
<div class="form-group">
<button type="submit" class="btn btn-default" name="login_button" id="login_button">
<span class="glyphicon glyphicon-log-in"></span>   Sign In
</button>
</div>
</form>

Steps5: Handle Login Form Submit with jQuery Ajax
Now we will handle login form submission using jQuery Ajax and send Ajax request to login.php to process login. If login process is successful then redirect to the users profile page otherwise display error message.
function submitForm() {
var data = $("#login-form").serialize();
$.ajax({
type : 'POST',
url : 'login.php',
data : data,
beforeSend: function(){
$("#error").fadeOut();
$("#login_button").html('<span class="glyphicon glyphicon-transfer"></span>   sending ...');
},
success : function(response){
if(response=="ok"){
$("#login_button").html('<img src="ajax-loader.gif" />   Signing In ...');
setTimeout(' window.location.href = "welcome.php"; ',4000);
} else {
$("#error").fadeIn(1000, function(){
$("#error").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span>   '+response+' !</div>');
$("#login_button").html('<span class="glyphicon glyphicon-log-in"></span>   Sign In');
});
}
}
});
return false;
}

Steps6: Process Login at Server end
After login form submission from jQuery Ajax, now we will process user login in PHP script login.php and if user password is correct then print ok otherwise error message.

if(isset($_POST['login_button'])) {
$user_email = trim($_POST['user_email']);
$user_password = trim($_POST['password']);
$sql = "SELECT uid, user, pass, email FROM users WHERE email='$user_email'";
$resultset = mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn));
$row = mysqli_fetch_assoc($resultset);
if($row['pass']==$user_password){
echo "ok";
$_SESSION['user_session'] = $row['uid'];
} else {
echo "email or password does not exist."; // wrong details
}
}

Steps7: HTML For Members Page
We will display members page by calling welcome.php when login successful.
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
<span class="glyphicon glyphicon-user"></span> Hi <?php echo $row['user']; ?> <span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="#"><span class="glyphicon glyphicon-user"></span> View Profile</a></li>
<li><a href="logout.php"><span class="glyphicon glyphicon-log-out"></span> Sign Out</a></li>
</ul>
</li>
</ul>
</div>
<div class='alert alert-success'>
<button class='close' data-dismiss='alert'></button>
Hello, <br><br>Welcome to the members page.<br><br>
</div>

Steps8: Handle User Logout
When user will click Logout button, logout.php file called to process logout.
session_start();
unset($_SESSION['user_session']);
if(session_destroy()) {
header("Location: index.php");
}

php - Session_start doesn't work in login page - Stack Overflow

php ajax session
Rectangle 27 -1

Sorry pal, but you have almost everything wrong.

The only sensible point in your question is how to make query building ease. Here is the function I am using:

function dbSet($fields, $data = array()) {
  if (!$data) $data = &$_POST;
  $set='';
  foreach ($fields as $field) {
    if (isset($data[$field])) {
      $set.="`$field`='".mysql_real_escape_string($data[$field])."', ";
    }
  }
  return substr($set, 0, -2); 
}

this will return you a SET statement, restricted to the previously defined set of fields. Usage

$fields = explode(" ","name surname lastname address zip fax phone");
$query  = "INSERT INTO $table SET ".dbSet($fields);
$result = mysql_query($query) or trigger_error(mysql_error().$query);
$id     = intval($_POST['id']);
$fields = explode(" ","name surname lastname address zip fax phone");
$query  = "UPDATE $table SET ".dbSet($fields)." WHERE id=$id";
$result = mysql_query($query) or trigger_error(mysql_error().$query);

So, in your case you have to add just a single word to the field list

Even if you didn't mean any arrogance, your general demeanor to someone who is learning PHP is ridiculous. No decent teacher or helper would scream out WRONG every time they saw something that wasn't right or to their liking. "Sorry, pal" didn't help either.

You can still point out it's wrong without directly saying "TERRIBLE WRONG" or "WRONG." Doing things like that basically shattered any confidence I had. Even so though, I guess I'm just misinterpreting your help, and for that I apologize. I just can't believe that every time I need to add a form field that I'll have to do it manually; I figured there'd be a better way to do it.

@SkyWookie this automated approach will lead you to get hacked pretty soon. The only purpose to do it manually is to take full control over query. Post data souldn't be used for the db field names. Despite of possibility to get field names from the database, it's considered bad practice too: some fields shouldn't be allowed to edit etc. Adding just one word to the field list seems a good compromise to me.

@Col oh okay, I guess I have a lot to learn about DB security then. Thanks a lot for the help, and sorry I took your comments the WRONG way ;)

insert all $_POST data into mysql using PHP? - Stack Overflow

php mysql
Rectangle 27 -1

Sorry pal, but you have almost everything wrong.

The only sensible point in your question is how to make query building ease. Here is the function I am using:

function dbSet($fields, $data = array()) {
  if (!$data) $data = &$_POST;
  $set='';
  foreach ($fields as $field) {
    if (isset($data[$field])) {
      $set.="`$field`='".mysql_real_escape_string($data[$field])."', ";
    }
  }
  return substr($set, 0, -2); 
}

this will return you a SET statement, restricted to the previously defined set of fields. Usage

$fields = explode(" ","name surname lastname address zip fax phone");
$query  = "INSERT INTO $table SET ".dbSet($fields);
$result = mysql_query($query) or trigger_error(mysql_error().$query);
$id     = intval($_POST['id']);
$fields = explode(" ","name surname lastname address zip fax phone");
$query  = "UPDATE $table SET ".dbSet($fields)." WHERE id=$id";
$result = mysql_query($query) or trigger_error(mysql_error().$query);

So, in your case you have to add just a single word to the field list

Even if you didn't mean any arrogance, your general demeanor to someone who is learning PHP is ridiculous. No decent teacher or helper would scream out WRONG every time they saw something that wasn't right or to their liking. "Sorry, pal" didn't help either.

You can still point out it's wrong without directly saying "TERRIBLE WRONG" or "WRONG." Doing things like that basically shattered any confidence I had. Even so though, I guess I'm just misinterpreting your help, and for that I apologize. I just can't believe that every time I need to add a form field that I'll have to do it manually; I figured there'd be a better way to do it.

@SkyWookie this automated approach will lead you to get hacked pretty soon. The only purpose to do it manually is to take full control over query. Post data souldn't be used for the db field names. Despite of possibility to get field names from the database, it's considered bad practice too: some fields shouldn't be allowed to edit etc. Adding just one word to the field list seems a good compromise to me.

@Col oh okay, I guess I have a lot to learn about DB security then. Thanks a lot for the help, and sorry I took your comments the WRONG way ;)

insert all $_POST data into mysql using PHP? - Stack Overflow

php mysql