Reputation: 45
I am trying to get what should otherwise be a simple but of php to insert sample data into a table, but something just isn't having any of it.
Table Definition:
CREATE TABLE IF NOT EXISTS teams (
token varchar(12) COLLATE utf8_unicode_ci NOT NULL,
tname varchar(48) COLLATE utf8_unicode_ci NOT NULL,
captain varchar(64) COLLATE utf8_unicode_ci NOT NULL,
email varchar(64) COLLATE utf8_unicode_ci NOT NULL,
phone varchar(14) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (token),
UNIQUE KEY name (tname),
KEY id (token)
)
ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Code:
$con = mysqli_connect("localhost","username","password","database");
$tname = "Big Bang";
$cname = "Mike";
$cemail = "[email protected]";
$cphone = "123-456-7898";
$teamToken = strtoupper(bin2hex(mcrypt_create_iv(6, MCRYPT_DEV_URANDOM)));
$query = "INSERT INTO teams (token, tname, captain, email, phone) VALUES ('" . $teamToken . "', '" . $tname . "', '" . $cname . "', '" . $cemail . "', '" . $cphone . "')";
if (mysqli_query($con, $query))
{
echo "Pass!";
}
else
{
echo $query;
}
mysqli_close($con);
What's odd is the php echos the query, because the mysqli_query result is false, yet the echoed query, when copied and pasted right into phpMyAdmin's terminal, works fine.
I am at my qit's end.
Upvotes: 4
Views: 7777
Reputation: 1
using following to connect:
username="root" password=""
Your code works fine in my system.
I used varchar
as datatype. Maybe the length of the varchar
which you have taken as 12 is less to store the $teamToken
variable. Try increasing the size.
Upvotes: 0
Reputation: 49
I will suggest go step by step step 1 : $con = mysqli_connect("localhost","username","password","database"); comment everything other than this statement. then below write
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
verify your username password and database name (by default:username=="root" password=="" )
step 2 : add the query statements and print it. also check that all values are within their bounds as specified id DB.
step 3 :if $con and $query are valid then you will get your o/p as you req.
If still you have an error please paste your error statement.
Upvotes: 0
Reputation: 460
Your Code:
$con = mysqli_connect("localhost","username","password","database");
Edited code:
$con = mysqli_connect("localhost","root","","database");
if(!$con):
die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
endif;
Its worked fine on my localhost
Upvotes: 2
Reputation: 1930
Maybe the datatypes of our columns make any problems.
I have once a similar "error" where my token field was to short. phpMyAdmin simply cut the long string to fit (or some thing this) and so it worked inside phpMyAdmin but not with my program.
Please post the CREATE statement of your table.
Upvotes: 1
Reputation: 862
Try this
mysqli_query($con, $query) or die(mysqli_error($con));
Upvotes: 0