-
Notifications
You must be signed in to change notification settings - Fork 28
Recipe: using MySQLi
Piotr edited this page Dec 10, 2013
·
4 revisions
var mysqli = new MySQLi("localhost1", "root", null, DATABASE_NAME);
if (mysqli.WasConnectionError)
{
echo("Connection error (" + mysqli.ConnectErrno + ") " + mysqli.ConnectError);
return;
}
if (mysqli.SetCharset("utf8"))
echo("Charset OK<br />");
else
{
echo("Error " + mysqli.Error + "<br />");
mysqli.Close();
return;
}
mysqli.AutoCommit(true);
var result = mysqli.QueryResult("select * from persons", MySQLiResultMode.UseResult);
if (result.IsNotFalse)
{
echo("Rows = " + result.Value.NumRows + "<br />");
Person person;
while (result.Value.Fetch<Person>(out person))
echo("firstName= " + htmlspecialchars(person.FirstName) + ", lastName=" + htmlspecialchars(person.LastName) + "<br />" + PHP_EOL);
result.Value.Free();
}
else
echo("Error " + mysqli.Error + "<br />");
mysqli.Close();
$mysqli = new \mysqli('localhost1', 'root', null, self::DATABASE_NAME);
if (!empty($mysqli->connect_error))
{
echo 'Connection error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error;
return;
}
if ($mysqli->set_charset('utf8'))
echo 'Charset OK<br />';
else
{
echo 'Error ' . $mysqli->error . '<br />';
$mysqli->close();
return;
}
$mysqli->autocommit(true);
$result = $mysqli->query('select * from persons', MYSQLI_USE_RESULT);
if ($result !== false)
{
echo 'Rows = ' . $result->num_rows . '<br />';
while($person = $result->fetch_assoc())
echo 'firstName= ' . htmlspecialchars($person['first_name']) . ', lastName=' . htmlspecialchars($person['last_name']) . '<br />' . PHP_EOL;
$result->free();
}
else
echo 'Error ' . $mysqli->error . '<br />';
$mysqli->close();
Note that mysqli.WasConnectionError is translated to !empty($mysqli->connect_error) but for PHP version <=5.3.0 is translated to !empty(mysqli_connect_error()) according to this example
Sample code taken from Php site.
var mysqli = new MySQLi("localhost", "my_user", "my_password", "world");
var stmt = mysqli.Prepare("INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)").Value;
MySQLiParam<string> code;
MySQLiParam<string> language;
MySQLiParam<string> official;
MySQLiParam<double> percent;
stmt.BindParams(out code, out language, out official, out percent);
code.Value = "DEU";
language.Value = "Bavarian";
official.Value = "F";
percent.Value = 11.2;
stmt.Execute();
$mysqli = new \mysqli('localhost', 'my_user', 'my_password', 'world');
$stmt = $mysqli->prepare('INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)');
$stmt->bind_param('sssd', $code, $language, $official, $percent);
$code = 'DEU';
$language = 'Bavarian';
$official = 'F';
$percent = 11.2;
$stmt->execute();