简体   繁体   English

无法使用php将数据插入mysql

[英]unable to insert data into mysql using php

i know this is a beginner's question .I am working on a bloodbank database project with html,php and mysql. 我知道这是一个初学者的问题。我正在使用html,php和mysql进行血库数据库项目。 Here as an administrator,i am trying to send messages to users.At first i am trying to see if the user with the username is present in the database.if he is present i am inserting the username and messages into the table called usermessages But i am not able to insert the data.i am getting the message "message sent successfully",but in reality it is not getting updated in the database.So here is my code,i can assure all that no spelling mistake is present in database or in phpcode. 在这里作为管理员,我正在尝试向用户发送消息。首先,我试图查看用户名是否存在于数据库中。如果他在场,我将用户名和消息插入名为usermessages的表中但是我无法插入data.i我收到消息“消息发送成功”,但实际上它没有在数据库中更新。所以这是我的代码,我可以保证所有数据库中没有拼写错误或者在phpcode中。

<?php
session_start();
$host="localhost"; // Host name 
$username="root"; // Mysql username 
$password=""; // Mysql password 
$db_name="bloodbank"; // Database name 
$tbl_name="users"; // Table name 
$tblname="usermessages"; 
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");

// username and messages is sent from form 
$username=$_POST['username']; 
$sql="SELECT * FROM $tbl_name WHERE username='$username'";
$result=mysql_query($sql);

// Mysql_num_row is counting table row
$count=mysql_num_rows($result);

if($count==1)
{
$mysql="INSERT INTO tblname(username, messages)
VALUES
('$_POST[username]','$_POST[messages]')";
echo "Message Sent Successfully";
}
else
{
echo "No user with that username found in the database";
}

?>

Try to execute the query 尝试执行查询

$mysql="INSERT INTO $tblname(username, messages)
VALUES ('$_POST[username]','$_POST[messages]')";
$return = mysql_query($my_sql);
echo "Message Sent Successfully";

You just forgotted to execute this insert query 您刚忘记执行此插入查询

And my advice is dont use mysql_* functions as they are depricated,use either mysqli_* functions or PDO Statements,and while you are playing with the post variables try to escape them like 我的建议是不要使用mysql_ *函数,因为它们被描述,使用mysqli_ *函数或PDO语句,当你正在玩post变量时试着逃避它们就像

mysql_real_escape_string($_POST['messages']);

Your query is good but you haven't executed it. 您的查询很好,但您还没有执行。 Use mysql_query to execute your query. 使用mysql_query执行查询。

Second please be careful about sql injection . 关于sql注入请注意。 Your code is shouting that come and hack me. 你的代码大喊大叫来攻击我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM