IamNOOB IamNOOB - 1 month ago 12
HTML Question

Data is not getting inserted in mysql through php

I am trying to insert 1 element into a table(It contains 3 columns).

code:

<?php
require 'connect.db.php';

$msg = 'msg';
mysql_query("INSERT INTO messages('Message') VALUES ('$msg')");
$result1 = mysql_query("SELECT * FROM messages ORDER by Msg_ID DESC");
while ($extract = mysql_fetch_array(result1)) {
echo $extract['Message'];
}


?>


When i run it I am getting this error:


Notice: Use of undefined constant result1 - assumed 'result1' in C:\xampp\htdocs\SocialNetwork\chat\chat.php on line 7

Warning: mysql_fetch_array() expects parameter 1 to be resource, string given in C:\xampp\htdocs\SocialNetwork\chat\chat.php on line 70


Data is not getting inserted to the db..

Error after using mysqli (replaced mysql):


Warning: mysqli_query() expects at least 2 parameters, 1 given in C:\xampp\htdocs\SocialNetwork\chat\chat.php on line 6

Warning: mysqli_query() expects at least 2 parameters, 1 given in C:\xampp\htdocs\SocialNetwork\chat\chat.php on line 7

Notice: Use of undefined constant result1 - assumed 'result1' in C:\xampp\htdocs\SocialNetwork\chat\chat.php on line 8

Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, string given in C:\xampp\htdocs\SocialNetwork\chat\chat.php on line 8

Answer

Wrong quotes. Use back-ticks ` for column names:

INSERT INTO messages(`Message`) VALUES ('$msg')
-- ------------------^-------^

Note: mysql_* is deprecated. Use either mysqli_* or PDO.

Also, for the other error, you forgot to add a $:

while ($extract = mysql_fetch_array($result1)) {

Okay, so now you switched to mysqli_ function, it is a different story here:

$conn = mysqli_connect($host, $user, $pass, $db);

// And change all the functions to:
mysqli_query($conn, "SELECT ...");
mysqli_query($conn, "INSERT ...");