Skip to content

Latest commit

 

History

History
75 lines (57 loc) · 1.9 KB

php.org

File metadata and controls

75 lines (57 loc) · 1.9 KB

PHP cheatsheat

check if a string is numeric

$number = "550;"
$number2 = "-550";
$number3 = "+420.342";
if (is_numeric ($number) && is_numeric ($number2) && is_numeric ($number3)) {
echo "they are all numeric strings!";
}

Database connections

PHP is smart enough to let you connect to a database in a procedural way or in an OO way.

You can mix and match the ways you access the database.

Here is the OO style.

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}

/* Create table doesn't return a resultset */
if ($mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City") === TRUE) {
    printf("Table myCity successfully created.\n");
}
?>

Here is the procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* Create table doesn't return a resultset */
if (mysqli_query($link, "CREATE TEMPORARY TABLE myCity LIKE City") === TRUE) {
    printf("Table myCity successfully created.\n");
}

/* Select queries return a resultset */
if ($result = mysqli_query($link, "SELECT Name FROM City LIMIT 10")) {
    printf("Select returned %d rows.\n", mysqli_num_rows($result));

Now here is how one might mix them via using the procedural style in setting up the connection, but querying via the OO style.

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");


/* Create table doesn't return a resultset */
if ($link->query("CREATE TEMPORARY TABLE myCity LIKE City") === TRUE) {
    printf("Table myCity successfully created.\n");
}