sepoto Posted October 21, 2010 Share Posted October 21, 2010 $query = "INSERT INTO dsgbars.bars VALUES('name','address')"; I have to pass $barname, $baraddress in the above mysql query. How can this be done? Thanks! Link to comment Share on other sites More sharing options...
Fmdpa Posted October 21, 2010 Share Posted October 21, 2010 Just like printing any other string. It can be inserted directly if the query is double-quoted: $query = "INSERT INTO dsgbars.bars VALUES('$barname','$baraddress')"; You could interpolate it with periods: $query = "INSERT INTO dsgbars.bars VALUES('" . $barname . "','" . $baraddress . "')"; Make sure your variables are sanitized to prevent SQL injection or XSS: $barname = $db->real_escape_string(htmlentities($barname));$baraddress = $db->real_escape_string(htmlentities($baraddress));query = "INSERT INTO dsgbars.bars VALUES('" . $barname . "','" . $baraddress . "')"; ...where $db = the database connection: $db = new mysqli('host','user','pswd','database'); Link to comment Share on other sites More sharing options...
Fmdpa Posted October 21, 2010 Share Posted October 21, 2010 Although my previous post would be functional, a more secure and, in my opinion, streamlined approach is using mysqli's prepared statements. Basically, you just put an unquoted question mark where you want the variable to be, and fill bind the variable to the query. This method also prevents SQL injection since the values are inserted directly into the database, instead of first being interpolated into the query. $query = "INSERT INTO dsgbars.bars VALUES(?,?)";if ($stmt = $db->prepare($query)) { $stmt->bind_param('ss', $barname, $baraddress); $stmt->execute(); $stmt->close();} This is just a very basic use of it. The bind_param method works like this: First it searches the query for question marks. The first parameter of the bind_param method defines what type of data is being inserted. s = string, i = integer, d = double, b = blob. Those values respectively represent the type of variable found in the second parameter of the method. Read more here. Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.