Jump to content

mysqli if it doesnt exist, then add it!


wright67uk

Recommended Posts

<?php
include 'connect.php';
$date = date('Y-m-d H:i:s');

$username = "Ed";
$horse = isset($_GET['horse'])&& $_GET['horse']!=''?$_GET['horse']:'';

echo $horse; // echos fine

$query = "SELECT horse_name, username FROM notes where horse_name = '$horse'";	 												  
$result = $mysqli->query($query); //if table is empty then insert should happen below 

if(!$result){
    $query = "INSERT INTO notes SET horse_name='$horse', username='$username', publish_date='$date'";
    $results = $mysqli->query($query);
}
else{
    echo 'horse is exists';
}

$result->free();
$mysqli->close();
?>

 

Hello, i'm trying to add some details to a database if no records exist for $horse.  At the moment I have an empty table, and nothing is being inserted when I test the code.

 

$horse echo's out fine and all I get is this followed by 'horse exists'.

What am I doing wrong here.   (I'm new to mysqli so I maybe goig a bit wrong here)

I have tested my connection.

Link to comment
Share on other sites

Maybe you could count the results that are returned instead of just checking if $result exists.. I expect that even if the query 'fails', something is returned by the mysqli object, which is assigned to $result.

 

The old way used to be mysql_num_rows(), but I'm not sure what the new way is with mysqli as I haven't looked into it too much. But that's what I suggest using in the if statement :)

 

Hope that helps

 

Denno

Link to comment
Share on other sites

I'm recording the date a horse was added to the database. Later on I will take notes about each horse from visitors. The date will show how relevant the note will be

Well, but the horse is a beautiful animal, that's why I get confused.

You maybe meant hourse?

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.