Jump to content

Please Check My Understanding Of SQL Programming


johnsmith153

Recommended Posts

Using PHP MySQL:

 

This is how I will do it:

 

The question is: have I got things right? Will this do everything, including ensure security?

 

This is my entire code for mySQL - there is nothing else I will add - so please tell me if I am missing something.

 


//config
$serverName   = "server-name";
$dbaseName    = "dbaseName1";
$tableName    = "table1";
$mysqlUser    = "testuser1";
$mysqlPass   = "passwordxyz";



//start / connect
$con = mysql_connect("$serverName", "$mysqlUser", "$mysqlPass");
if (!$con)
{
echo "Could not connect to db";//. mysql_error()
exit;
}



//select a database
mysql_select_db($dbaseName, $con);



//if inserting, will need to make data safe:
$sql = sprintf("INSERT INTO $tableName ('field1', 'field2', 'field3') VALUES ('%s', '%s', %s)",
                    mysql_real_escape_string($_POST['Name']),
                    mysql_real_escape_string($_POST['Info2']),
                    mysql_real_escape_string($_POST['Info3']),
				);


//perform query   ($sql being a string containing the query)
$mysqlRes = mysql_query($sql);



//check errors
if (!$mysqlRes) {
    echo "Could not run query";//. mysql_error()
    exit;
}
if (mysql_num_rows($mysqlRes) == 0) {
    echo "No records found";
exit;
}



//if searching database/table
//
//display
while($row = mysql_fetch_array($mysqlRes))
  	{
  	echo $row['Field_Name'];
  	echo "<br />";
  	}	
//store for later
while($row = mysql_fetch_array($mysqlRes))
  	{
  	$storeValues[] = $row['Field_Name'];
  	}
//
///////////////////////////////	

  

//close / end
////ESSENTIAL TO CLOSE CONNECTION AT THE END
mysql_close($con);


Looks fine.

I would advice you to learn and use mysqli extension however. It is recommended for MySQL 4.1 and later. Has better performance, some new functionality and its syntax is almost the same (there are some differences though).

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.