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
https://forums.phpfreaks.com/topic/275691-mysqli-if-it-doesnt-exist-then-add-it/
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

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?

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.