my code running correctly but if $file have three item then after successful insert success message print three time.But I need to print message for one time at all.
for($i = 1; $i <= count($file); $i++){
$insert=mysqli_query($con,"INSERT INTO song (song_name, song_url, album,artist)
VALUES ('".current(explode(".", $file))."', '".$file."','".$album."','".$artist."')");
if($insert){
print'Success';
}else{
print''.mysql_error().'';
}
}
Write it this way:
$success = true;
for($i = 1; $i <= count($file); $i++)
{
$insert=mysqli_query($con,"INSERT INTO song (song_name, song_url, album,artist)
VALUES ('".current(explode(".", $file))."', '".$file."','".$album."','".$artist."')");
if(!$insert)
{ $success = false;
print''.mysql_error().'';
}
}
if($success){
print'Success';
}
This only prints "Success" only, if all queriey succeeded, and it will only print it once.
You should consider mysqli_*
instead of mysql_*
, as this functions are already deprecated due to security issues.
try this: (you also wrote mysql_error instead of mysqli_error, this fixes it as well.)
$success = 0;
for($i = 1; $i <= count($file); $i++)
{
$insert=mysqli_query($con,"INSERT INTO song (song_name, song_url, album,artist)
VALUES ('".current(explode(".", $file))."', '".$file."','".$album."','".$artist."')");
if($insert)
{
$success = 1;
}
else
{
print''.mysqli_error($con).'';
$success = 0;
break;
}
}
if($success)
print'Success';
Stop using mysql_* functions, they are deprecated.
Try This:
$error = false;
for($i = 1; $i <= count($file); $i++){
$insert=mysqli_query($con,"INSERT INTO song (song_name, song_url, album,artist)
VALUES ('".current(explode(".", $file))."', '".$file."','".$album."','".$artist."')");
if($insert){
$error = true;
}
else{
$error = false;
print''.mysql_error().'';
}
}
if($error) {
print 'Success';
}
use in this way
function abc(){
$flag = "";
for($i = 1; $i <= count($file); $i++)
{
$insert=mysqli_query($con,"INSERT INTO song (song_name, song_url, album,artist)
VALUES ('".current(explode(".", $file))."', '".$file."','".$album."','".$artist."')");
if($insert)
{
$flag = true;
}
else
{
print''.mysql_error().''; return;
}
}
if($flag == true){
print 'success';
}
}
You could do something like the following:
$errors = array();
for ($i = 1, $n = count($file); $i <= $n; ++$i)
{
$insert = mysqli_query($con, $query);
if (!$insert)
{
$errors[] = mysqli_error($con);
}
}
if (empty($errors))
{
echo 'Success';
}
else
{
echo 'Errors:<br><br>' . implode('<br>', $errors);
}
Also note that I fixed your call to mysql_error()
to the correct mysqli_error()
function.