Krish Chandran Krish Chandran - 14 days ago 9
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.

<?php

$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>";
}
mysql_close($link);

?>

Answer

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:-

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

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

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

        $query = "SELECT * FROM mpaa";
        $res  =  mysqli_query($link,$query);
        if($res){
            while($sqlrow=mysqli_fetch_assoc($query))
            {
                $row= $sqlrow['C_Name'];
                $nrow= $sqlrow['Content Rating'];
                $mrow= $sqlrow['V_ID'];
                echo "<br>".$row." ".$nrow." ".$mrow."<br>";
            }
        mysqli_close($link);
        }else{
            echo die('Query error: ' . mysqli_error($link));  
        }
    }else{
        echo die('Query error: ' . mysqli_error($link));  
    }
}else{
  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:-

<?php  
phpinfo();
?>

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

Like this:- https://eval.in/684551