-1

Im trying to take input from a form, then check table (user) if that name exsits and I need to grab the uid colum.

Input (username / MSG) > Check for username > if so get uid > else add user(This I got) > take uid and use when i INSERT the msg into its table (message)

Table structure: user: uid (Unique) | name

Heres where in at PHP whise:

<?php
$name = $_GET["name"];
$message = $_GET["message"];

$checkn = "SELECT 1 FROM user WHERE name = $name";
$sql = "INSERT INTO user (uid, name) VALUES ('','$name')";
$msg = "INSERT INTO message (uid, message) VALUES ('$uid','$message')";
$uid = "SELECT uid FROM user WHERE name = $name";
$result = $conn->query($checkn);

if ($conn->query($checkn) === TRUE) {
    echo "Checkn TRUE";
}else {
    echo "<br> SHEEET" . $checkn . $conn->error;
}

$conn->close();?>

I erased the bulk to start over and get this fixed so once I can get this portion done I have the add if user doesn't exist. Thank you.

2toetommy
  • 11
  • 4
  • Explain us what is not working? – u_mulder Dec 02 '16 at 06:51
  • I'd think `WHERE name = $name` would cause errors (and opens you to SQL injections). The question doesn't explain what the exact issue is though. To prevent SQL injections use parameterized queries. – chris85 Dec 02 '16 at 06:51

2 Answers2

1

I think You are writing the query wrong, when using PHP you should write the query inside ' if it contains variable. " won't parse the variable value.

Replace :

$checkn = "SELECT 1 FROM user WHERE name = $name";

With:

$checkn = 'SELECT 1 FROM user WHERE name = $name';

And it should work. Do the same with other queries too. Use ' instead of "

Hope it helps.

Ravi Shankar Bharti
  • 8,922
  • 5
  • 28
  • 52
  • `'` is strict and does not allow vars `"` allows vars all in all you should never have vars inserted like that anyways. – KatsuoRyuu Dec 02 '16 at 07:14
0

Just from the top of my head

<?php

$name = $_GET["name"];
$message = $_GET["message"];

$checkn = sprintf('SELECT 1 FROM `user` WHERE `name` = \'%s\'', $name);
$sql = sprintf('INSERT INTO `user` (`uid`, `name`) VALUES (\'\',\'%s\')', $name);
$msg = sprintf('INSERT INTO `message` (`uid`, `message`) VALUES (\'%s\',\'%s\')', $uid, $message);
$uid = sprintf('SELECT `uid` FROM `user` WHERE `name` = \'%s\'', $name);

$result = $conn->query($checkn);

if ($conn->query($checkn) == TRUE) {
    echo "Checkn TRUE";
} else {
    echo "<br> SHEEET" . $checkn . $conn->error;
}

$conn->close();

?>

for some reason i have sometimes had problems when i did not put ` around table names. I have also separated the variable interpolation so it makes it easier to secure it for sql injection (i did not secure it).

You used triple === this means its strict but mysql would pass 1 back which when using strict is not true.

Hope it helps

KatsuoRyuu
  • 321
  • 4
  • 19