Skip to content
Advertisement

I want to validate two columns from my database “name and group” if it exists display already exists and if it doesn’t exist insert into the database

this the html with ajax and it displays successful and inserts into the database but how can I display error message if the name is already exist after the validation

<form action="" id="manage-project">
                <label for="" class="control-label">Project Title</label>
                <input type="text" class="form-control form-control-sm" name="name"  value="<?php echo isset($name) ? $name : '' ?>">
            </div><div class="form-group">
      <label for="" class="control-label">Project Group </label>
      <input type="text" class="form-control form-control-sm" name="pname" required value="<?php echo isset($pname) ? $pname : '' ?>">

    </div>
<div class="card-footer border-top border-info">
        <div class="d-flex w-100 justify-content-center align-items-center">
            <button class="btn btn-flat  bg-gradient-primary mx-2" form="manage-project">Save</button>
            <button class="btn btn-flat bg-gradient-secondary mx-2" type="button" onclick="location.href='index.php?page=project_list'">Cancel</button>
        </div>
    </div>
$('#manage-project').submit(function(e){
    e.preventDefault()
    start_load()
    $.ajax({
        url:'ajax.php?action=save_project',
        data: new FormData($(this)[0]),   

        cache: false,
        contentType: false,
        processData: false,
        method: 'POST',
        type: 'POST',
        success:function(resp){
            if(resp == 1){
                alert_toast('Data successfully saved',"success");
                setTimeout(function(){
                    location.href = 'index.php?page=project_list'
                },2000)
            }
        }
    })

This is the insertion query and I guess I need select query to validate the name. help me out here

function save_project(){
    extract($_POST);
    $data = "";
    foreach($_POST as $k => $v){
        if(!in_array($k, array('id','user_ids')) && !is_numeric($k)){
            if($k == 'description')
                $v = htmlentities(str_replace("'","’",$v));
            if(empty($data)){
                $data .= " $k='$v' ";
            }else{
                $data .= ", $k='$v' ";
            }
        }
    }
    if(isset($user_ids)){
        $data .= ", user_ids='".implode(',',$user_ids)."' ";
    }
    if(empty($id)){
        $save = $this->db->query("INSERT INTO project_list set $data");
    }else{
        $save = $this->db->query("UPDATE project_list set $data where id = $id");
    }
    if($save){
        return 1;
    }
}

Advertisement

Answer

$check = $this->db->query("select name from project_list where and pname='$pname' or name='$name'")->num_rows;
    if($check > 0){
        return 2;
        exit;
    }
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement