当前位置: 动力学知识库 > 问答 > 编程问答 >

php - Check exist value in database

问题描述:

My table artist: artistID, name, genreID, avatar, short-decs, view, vnmartist.

artist structure table

I create upload.php to upload mp3 and insert information about song with column: name, artistID, genreID.

Because song name and artist, genre is input by user. I want to checking that name of artist. If name is null -> insert name to database, then get artistID and insert to database. If name is not null -> get artistID and insert data to table artist.

My PHP code below:

$artist = $_POST['artist-name'];

$link = mysql_connect("localhost", "root", "");

mysql_select_db("vnmtest", $link);

$result = mysql_query("SELECT * FROM artist where name='".$artist."'",$link);

if($num_rows = mysql_num_rows($result) == 0)

echo "data is null";

else echo "data okay";

When testing upload 1 file, I input artist-name: "Nhật Trường", this like data in name of the artist, but program still echo "data is null".

My artist table:

[![my artist table][2]][2]

My full code below:

 if (!empty($_FILES["audiofile"])) {

$myFile = $_FILES["audiofile"];

if ($myFile["error"] !== UPLOAD_ERR_OK) {

echo "<p>An error occurred.</p>";

exit;

}

// ensure a safe filename

$name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);

// don't overwrite an existing file

$i = 0;

$parts = pathinfo($name);

while (file_exists(UPLOAD_DIR . $name)) {

$i++;

$name = $parts["filename"] . "-" . $i . "." . $parts["extension"];

}

// preserve file from temporary directory

$success = move_uploaded_file($myFile["tmp_name"],

UPLOAD_DIR . $name);

if (!$success) {

echo "<p>Unable to save file.</p>";

exit;

}

// set proper permissions on the new file

chmod(UPLOAD_DIR . $name, 0644);

$name = $_POST['song-name'];

$artist = $_POST['artist-name'];

$genreID = $_POST['genreID'];

// kiểm tra artist tồn tại hay chưa

$artist = $_POST['artist-name'];

print_r($_POST['artist-name']);

//$sql = "SELECT * FROM artist where name='".$artist."'";

//$result = $conn->query($sql);

$link = mysql_connect("localhost", "root", "");

mysql_select_db("vnmtest", $link);

$result = mysql_query("SELECT * FROM artist where name='".$artist."'",$link);

if($num_rows = mysql_num_rows($result) == 0)

echo "data is null";

else echo "data okay";

// output data of each row

// $artist_select = $conn->query ("SELECT EXISTS(select * from artist where name = '".$artist."') ");

}

?>

网友答案:

I think there could be three possibilities:

1) charset errors: try to set appropriate charset in your page (es: set it with headers: $mysqli->query("SET CHARACTER SET utf8"))

2) query error: try to change your query in

$result = mysql_query("SELECT count(*) num FROM artist where name='".$artist."'",$link);

and modify your if statement to check if "num" field is > 0

3) "if" error: try to change if (leaving current query) in

if(mysql_num_rows($result) == 0)
分享给朋友:
您可能感兴趣的文章:
随机阅读: