Krish Chandran Krish Chandran - 1 year ago 80
PHP Question

How to use Insert query in PHP code

I do not understand what is going wrong with code. The result is get is "connected successfully successQuery failed". I tried few combinations and I get the same result. Please help me in solving this. Thanks in advance.


$link = mysql_connect('localhost', 'root1', '')
or die('Could not connect: ' . mysql_error());

if ($link) {
echo 'connected successfully';

$l = mysql_select_db('vtflix', $link) or die ('Could not select the database');
if ($l) {
echo ' success';

/*$varCNAME = 'John';
$varCONTENT = '4';
$varVID = '1';*/
$sql = "INSERT INTO mpaa(C_Name, ContentRating, V_ID) VALUES ('Jon', 4, 3)";
mysql_query($sql, $link) or die("Query failed");
$que = "SELECT * FROM mpaa";
$query = mysql_query($que, $link);
if (!$query) {
echo 'query failed';

while ($sqlrow = mysql_fetch_array($query, MYSQL_ASSOC)) {
$row = $sqlrow['C_Name'];
$nrow = $sqlrow['Content Rating'];
$mrow = $sqlrow['V_ID'];
echo "<br>" . $row . " " . $nrow . " " . $mrow . "<br>";


Answer Source

1.Don't use mysql_* library (deprecated from php5 onward + removed from php7) .Use mysqli_* OR PDO.

2.An example of mysqli_*(with your code)is given below:-

error_reporting(E_ALL); // check all type of error
ini_set('display_errors',1); // display those errors

$link = mysqli_connect('localhost', 'root1', '','vtflix');

    echo 'connected successfully';
    $sql= "INSERT INTO mpaa(C_Name,ContentRating,V_ID) VALUES ('Jon', 4, 3)";

        $query = "SELECT * FROM mpaa";
        $res  =  mysqli_query($link,$query);
                $row= $sqlrow['C_Name'];
                $nrow= $sqlrow['Content Rating'];
                $mrow= $sqlrow['V_ID'];
                echo "<br>".$row." ".$nrow." ".$mrow."<br>";
            echo die('Query error: ' . mysqli_error($link));  
        echo die('Query error: ' . mysqli_error($link));  
  echo die('Could not connect: ' . mysqli_connect_error());  

Note:- To check php version (either on localhost or on live server) create a file with name phpInfo.php, and just write one line code in that file:-


Now run this file and you will get the current php version.

Like this:-

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download