I want to GET user id FROM players WHERE username='$username' and post it into another MySQLi query and post it as pid but it shows error somehow, did I miss something?
if(isset($_POST["add"])) {
$content = $_POST['content'];
$sql = "SELECT id FROM players WHERE username='$username'";
$sql1 = "INSERT INTO bulletinboard (pid,content) VALUES ('$sql','$content')";
if (mysqli_query($conn, $sql1)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
This is the error I am receiving.
Error: SELECT id FROM players WHERE username='nasty93'
Thanks
You need to execute the query so it needs to not be quoted. You also should familiarize yourself with the insert...select syntax. http://dev.mysql.com/doc/refman/5.7/en/insert-select.html
You also should use parameterized queries. Here it is altered (untested) (I also only use mysqli on SO so likely to be an error here).
if(isset($_POST["add"])) {
$content = $_POST['content'];
$sql1 = "INSERT INTO bulletinboard (pid,content) SELECT id, ? FROM players WHERE username=?";
$stmt = mysqli_prepare($conn, $sql1) or die(mysqli_error($conn));
mysqli_stmt_bind_param($stmt, "ss", $content, $username) or die(mysqli_error($conn));
mysqli_stmt_execute($stmt) or die(mysqli_error($conn));
}
Related
I have an auto incrementing ID called deviceID in one of my fields. I was wanting to pass this to a session in php to use later on and was planning on using scope_identity() as I understand that this is the best way to get the current Primary key ID. However anytime I have attempted to use it I have had a error message saying that it is an undefined function. Here is my code so without the scope_identity():
<?php
session_start();
include 'db.php';
$screenWidth = $_POST['screenWidth'];
$screenHeight = $_POST['screenHeight'];
$HandUsed = $_POST['HandUsed'];
$_SESSION["screenWidth"] = $screenWidth;
$_SESSION["screenHeight"] = $screenHeight;
if (isset($_POST['submit'])) {
$screenWidth = $_POST['screenWidth'];
$screenHeight = $_POST['screenHeight'];
$phoneType = $_POST['phoneName'];
$HandUsed = $_POST['HandUsed'];
$_SESSION["HandUsed"] = $HandUsed;
$_SESSION["phoneName"] = $phoneType;
echo 'hello';
$sql = "
INSERT INTO DeviceInfo (DeviceID, screenWidth, phoneType, screenHeight, HandUsed)
VALUES ('$screenWidth','$phoneType', '$screenHeight', '$HandUsed')
SELECT SCOPE_IDENTITY() as DeviceID
";
if (sqlsrv_query($conn, $sql)) {
echo ($sql);
echo "New record has been added successfully !";
} else {
echo "Error: " . $sql . ":-" . sqlsrv_errors($conn);
}
sqlsrv_close($conn);
}
?>
You need to fix some issues in your code:
The INSERT statement is wrong - you have five columns, but only four values in this statement. I assume, that DeviceID is an identity column, so remove this column from the column list.
Use parameteres in your statement. Function sqlsrv_query() does both statement preparation and statement execution, and can be used to execute parameterized queries.
Use SET NOCOUNT ON as first line in your statement to prevent SQL Server from passing the count of rows affected as part of the result set.
SCOPE_IDENTITY() is used correctly and it should return the expected ID. Of course, depending on the requirements, you may use IDENT_CURRENT().
The following example (based on the code in the question) is a working solution:
<?php
session_start();
include 'db.php';
if (isset($_POST['submit'])) {
$screenWidth = $_POST['screenWidth'];
$phoneType = $_POST['phoneName'];
$screenHeight = $_POST['screenHeight'];
$HandUsed = $_POST['HandUsed'];
$params = array($screenWidth, $phoneType, $screenHeight, $HandUsed);
$sql = "
SET NOCOUNT ON
INSERT INTO DeviceInfo (screenWidth, phoneType, screenHeight, HandUsed)
VALUES (?, ?, ?, ?)
SELECT SCOPE_IDENTITY() AS DeviceID
";
$stmt = sqlsrv_query($conn, $sql, $params);
if ($stmt === false) {
echo "Error: " . $sql . ": " . print_r(sqlsrv_errors());
exit;
}
echo "New record has been added successfully !";
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
echo $row["DeviceID"];
}
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn);
}
?>
I did 3 queries (SELECT, INSERT, UPDATE) it works but at the current state looks ugly and not safe.
Is there any way to make these SELECT, INSERT, UPDATE queries more readable and safer than this with the prepared statement?
$email = $_SESSION['email'];
$query = "SELECT username FROM users WHERE email='$email'";
$result = mysqli_query($connect, $query);
$row = mysqli_fetch_assoc($result);
$username = $row['username'];
if(!empty($_POST["comment"])){
$id = $_GET['id'];
$sql = "INSERT INTO user_comments (parent_id, comment, username, custom_id) VALUES ('".$_POST["commentID"]."', '".$_POST["comment"]."', '$username', '$id')";
mysqli_query($connect, $sql) or die("ERROR: ". mysqli_error($connect));
/// I need this update query to make every inserted comment's ID +1 or can I do this more simple?
$sql1 = "UPDATE user_comments SET id = id +1 WHERE custom_id = '$id'";
mysqli_query($connect, $sql1) or die("ERROR: ". mysqli_error($connect));
Give this a try. You can use $ex->insert_id to get the last entered ID. This may come in handy when mass inserting into a DB. I generally use PDO as I find the code looks cleaner but it's all preference I suppose. Keep in mind for the ->bind_param line that "isii" is referring to the type(s) of data which you are entering. So, in this case, its Integer, String, Integer, Integer (I may have got this wrong).
$email = $_SESSION['email'];
$query = "SELECT username FROM users WHERE email='$email'";
$result = mysqli_query($connect, $query);
$row = mysqli_fetch_assoc($result);
$username = $row['username'];
if(!empty($_POST["comment"])){
$id = $_GET['id'];
$commentID = $_POST["commentID"];
$comment = $_POST["comment"];
$sql = "INSERT INTO user_comments (parent_id, comment, username, custom_id) VALUES (?, ?, ?, ?)";
$ex = $connect->prepare($sql);
$ex->bind_param("isii", $commentID, $comment, $username, $id);
if($ex->execute()){
// query success
// I need this update query to make every inserted comment's ID +1 or can I do this more simple?
$lastInsertID = $ex->insert_id;
$sql1 = "UPDATE user_comments SET id = id + 1 WHERE custom_id = ?";
$ex1 = $connect->prepare($sql1);
$ex1->bind_param("i",$lastInsertID);
if($ex1->execute()){
// query success
}else{
// query failed
error_log($connect->error);
}
}else{
//query failed
error_log($connect->error);
}
I am Android developer and trying to make one API for register user using PHP and Mysqli. I have made API like below
<?php
include("dbconnection.php");
$email= $_GET['email'];
$query = mysqli_query($conn, "SELECT * FROM tbl_user WHERE email='".$email."'");
if (!$query){
die('Error: ' . mysqli_error($con));
}
if(mysqli_num_rows($query) > 0){
$response='success';
}else{
$sql = "INSERT INTO tbl_user(email)VALUES ('".$email."')";
if (mysqli_query($conn, $sql)) {
$response='success';
}else {
$response='error';
}
}
echo json_encode($response);
?>
basically I am passing email as parameter like example.com/login?=abc#gmail.com
and I want check that email is already in database table or not. if email exist in database I want return user_id in response and if email is not in database than I want add that email in database and want return user_id. I have made API is working fine as I require but I do not know how to return user_id located with that email. Let me know if someone can give me idea to solve my puzzle. Thanks
The below code will create an array with message and user_id.
include("dbconnection.php");
$email= $_GET['email'];
$query = mysqli_query($conn, "SELECT * FROM tbl_user WHERE email='".$email."'");
if (!$query){
die('Error: ' . mysqli_error($con));
}
if(mysqli_num_rows($query) > 0){
// assign message to response array
$response['message']='success';
// Get the results data
while($row = mysqli_fetch_assoc($query)) {
// assign user_id to response array
$response['user_id'] = $row['user_id'];
}
}else{
$sql = "INSERT INTO tbl_user(email) VALUES ('".$email."')";
if (mysqli_query($conn, $sql)) {
$response['message']='success';
// assign last inserted id to response array
$response['user_id'] = mysqli_insert_id($conn);
}else {
$response['message']='error';
}
}
echo json_encode($response);
Prepared statements help you secure your SQL statements from SQL Injection attacks.
First of all, you should use PreparedStatement to avoid sql injection.
Then, second you can use PDO::lastInsertId()
I have an issue with MySQLi and PHP.
I created a form, and once I type the desired values in and hit submit, the values are right away sent to the database. Nothing wrong with this.
What I want to happen is that: after hitting the submit button, PHP shall echo the result of the just-submitted entry. That is to say:
`INSERT INTO table VALUES (x, x, y) -> SELECT x, x, y FROM table ORDER BY id DESC LIMIT 1`
I have tried many methods to do this, but all of them either echo the previous entry (the one before the one just submitted) or plainly don't work.
I have tried mysqli_insert_id($conn) but this returns nothing.
This is where my code rests at at the moment:
$conn = mysqli_connect($server, $user, $pw, $BD);
if (!$conn) {
die ('<span style="color: #FF0000;">"connection failed: "</span>' . mysqli_connect_error());
}
$nome = $_POST['nome'];
$preco = $_POST['preco'];
$query = "INSERT INTO produtos(nome, preco) VALUES ('$nome', '$preco')";
$result = mysqli_insert_id($conn);
var_dump ($result);
if (mysqli_query($conn, $query)){
echo '<br>'."Succeeded!";
} else {
echo '<br>'."ERROR!" .'<br>'. $query ."<br>". mysqli_error($conn) .'<br><br>'. '<span style="color: #FF0000;">You have to fill all the fields.</span>';
}
mysqli_close($conn);
to note, if of any help, var_dump outputs int(0) at the moment.
Thanks in advance. I've been struggling like mad with this.
You can't get mysqli_insert_id without executing the query. Better use prepare statement to prevent from sql injection
$stmt = $conn->prepare("INSERT INTO produtos(nome, preco) VALUES (?,?)");
$stmt->bind_param('ss', $nome, $preco);
$stmt->execute();// execute query
$conn->insert_id;// get last insert id
Please see that you haven't even executed your query. On a side note, you should be aware of SQL injections and follow the below pattern:
$nome = mysqli_real_escape_string($conn, $_POST['nome']);
$preco = mysqli_real_escape_string($conn, $_POST['preco']);
$sql = "INSERT INTO produtos (nome, preco) VALUES ('".$nome."', '".$preco."')";
$query = mysqli_query($conn, $sql) or die(mysqli_error($conn));
$result = mysqli_insert_id($conn);
echo $result; // Check your result.
Use this:
$query = "INSERT INTO produtos(nome, preco) VALUES ('$nome', '$preco')";
$res=mysqli_query($conn,$query);
$result = mysqli_insert_id($conn);
var_dump ($result);`
I'm trying to find a person in my table and update their score. This is the code I have right now. For some reason it's not working. Instead of changing the person's score, it will just make a new row with the same name of the person.
$name = $_POST["strtolower(name)"];
$team = $_POST["team"];
$num = $_POST["number"];
$goals = $_POST["goals"];
if($query = mysqli_query("SELECT goals FROM goalscorers WHERE name=$name ", $db)){
while($row = mysqli_fetch_assoc($query)){
$origgoals = $row['goals'];
$newgoals = (int)$origgoals + (int)$goals;
mysqli_query($db, "UPDATE goalscorers SET goals=$newgoals WHERE name=$name ");
echo "<h1>Thank you for submitting your details! <br /> Add another</h1>";
}
mysqli_free_result($query);
}
else {
$query = "INSERT INTO goalscorers (name, team, num, goals) VALUES ('$name','$team','$num','$goals') ";
$result = mysqli_query($query, $db);
if (mysqli_error()) { print "Database ERROR: " . mysql_error(); }
echo "<h1>Thank you for submitting your details! <br /> Add another</h1>";
}
I'm very new to both PHP and MySQL so it's probably a basic mistake.
Also, I already am connected to the database.
Your immediate problem is that you don't have quotes around string values in your sql queries. Change
"SELECT goals FROM goalscorers WHERE name=$name "
to
"SELECT goals FROM goalscorers WHERE name = '$name'"
^ ^
and
"UPDATE goalscorers SET goals=$newgoals WHERE name=$name "
to
"UPDATE goalscorers SET goals=$newgoals WHERE name = '$name'"
^ ^
On a side note: learn and use prepared statements. Your code is vulnerable to sql injections.
UPDATE1: You can drastically simplify your code with INSERT ... ON DUPLICATE KEY UPDATE. In order for it to work properly you have to have a UNIQUE (PRIMARY KEY) index on name column.
Your insert statement then should look like
INSERT INTO goalscorers (`name`, `team`, `num`, `goals`)
VALUES (?, ?, ?, ?)
ON DUPLICATE KEY UPDATE goals = goals + VALUES(goals)
Here is SQLFiddle demo
UPDATE2: Now your code with INSERT ... ON DUPLICATE KEY UPDATE and prepared statement can look like this
$name = $_POST['name'];
$team = $_POST['team'];
$num = $_POST['number'];
$goals = $_POST['goals'];
/* connect to the database*/
$db = new mysqli('localhost', 'user', 'userpwd', 'test');
/* check connection */
if ($db->connect_errno) {
die('Connection failed: ' .$db->connect_error);
}
$sql = 'INSERT INTO goalscorers (`name`, `team`, `num`, `goals`)
VALUES (?, ?, ?, ?)
ON DUPLICATE KEY UPDATE goals = goals + VALUES(goals)';
/* create a prepared statement */
if ($stmt = $db->prepare($sql)) {
/* bind parameters for markers */
$stmt->bind_param("ssii", $name, $team, $num, $goals);
/* execute query */
if ($stmt->execute()) {
echo '<h1>Thank you for submitting your details! <br /> Add another</h1>';
} else {
die('Insert failed: ' .$db->error);
}
/* close statement */
$stmt->close();
} else {
die('Statement prepare failed: ' .$db->error);
}