Using the mysqli Object-Oriented API : mysqli « MySQL Database « PHP






Using the mysqli Object-Oriented API

 
<?php 
$mysqli = new mysqli ("localhost","root","","mydatabase"); 
try { 
    if (mysqli_connect_errno()){ 
        throw new exception ("Error: " . mysqli_connect_errno() . " - ". mysqli_connect_error()); 
    
    } else { 
        if ($cdquery = $mysqli->query ("SELECT * FROM mytable ORDER BY id ASC")){ 
    
            while ($cddata = $cdquery->fetch_array ()){ 
                echo "ID: " . $cddata['id'] . "<br />"; 
                echo "Title: " . stripslashes ($cddata['title']) . "<br />"; 
                echo "MyValue: " . stripslashes ($cddata['MyValue']) . "<br />"; 
            } 
            $cdquery->close(); 
        } else { 
            echo $mysqli->errno . " - " . $mysqli->error; 
        } 
    
        $prep = $mysqli->prepare ("INSERT INTO mytable(id,title,myvalue) VALUES ('0',?,?)"); 
        $prep->bind_param ('ss',$title,$myvalue); 
        
        $title = "AA"; 
        $myvalue = 20; 
        
        $prep->execute(); 
        
        echo $prep->affected_rows . " row(s) affected."; 
        $prep->close(); 
        if ($result = $mysqli->prepare ("SELECT title, myvalue FROM mytable WHERE id > 2")){ 
            $result->execute (); 
            $result->bind_result ($title,$myvalue); 
            while ($result->fetch ()){ 
                echo "Title: " . stripslashes ($title) . "<br />"; 
                echo "MyValue: " . stripslashes ($myvalue) . "<br />"; 
            } 
            $result->close (); 
        } else { 
            echo $mysqli->errno . " - " . $mysqli->error; 
        } 
        $mysqli->close(); 
    } 
} catch (exception $e) { 
echo $e->getmessage(); 
} 
?>
  
  








Related examples in the same category

1.Multiple Queries Using MySQLi
2.Parameter Binding in MySQLi
3.Use mysqli to fetch data from mysql
4.Using the Object-Oriented Syntax in MySQLi
5.mysqli_fetch_object.php
6.mysqli_fetch_result-2.php
7.mysqli_fetch_result.php
8.mysqli_fetch_row.php
9.mysqli_free_result.php
10.mysqli_multi_query.php
11.mysqli_stmt_prepare.php
12.mysqli_store_result.php
13.retrieving_multiple_rows.php