SQL statement in php variable? - php

Ok so I realized this probably looks crazy to good programers but I'm a noob and just trying to figure out the basics. I'm trying to build a simple question/answer site. I can submit a question to the db just fine but when I direct a user to answer I need to put the correct question id (q_id) as it's a foreign key in my answers table. I cant find anything online to solve this problem. I'm sure I'll get "dont use mysqli_query" or something but if anyone can just help me understand how to get the correct value passed into q_id it would be a great help. Seeing my php code below it will probably make sense what I'm attempting to do:
//set up connection credentials
$servername = "127.0.0.1";
$username = "root";
$password = "";
$dbname = "ask";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
//gather the data from the form
$answer = $_POST["answer"];
$q_id = mysqli_query($conn,"select q_id from questions order by q_id
desc limit 1");
$sql = "INSERT INTO answers (answer, q_id) VALUES ('$answer',
'$q_id')";
if (mysqli_query($conn, $sql)) {
echo "answer submitted";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);}
?>

When you open the page that display question, you already use the q_id, just use it again.
Like the stackoverflow URL, question ID is on the URL:
https://stackoverflow.com/questions/44896448/sql-statement-in-php-variable
Because you do not know re-write yet so you can use $_GET method to get q_id.
EDITED:
User insert_id; to get last id after question submitted then you got the id for the question
if (mysqli_query($conn, $sql)) {
$last_id = $conn->insert_id;
echo "answer submitted, id is ".$last_id;
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);}
?>

Related

PHP mysqli increase value

I need to say that I'm a beginner on php, mysqli, but I want to learn.
I am trying to build an quiz script which store "SCORE" information into database.
I have the following "final.php" page script, which collects and inserts into the database, the current score of user.
What I need is that I want to keep the current score from database "eg: 213", and increase with current session score which will be "eg :10", so total score after that will be "213(old) + 10(current) = 223(total)
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE users SET scor='".$_SESSION['score']."' WHERE id=2";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
Everything working fine with that code, but all what I need is that to increase score.
Thank you to everyone for you patience and because you understand me that I am beginner.
You can update the existing value in the database by adding your amount to it. There is no need to select the score first.
So in your example:
UPDATE users SET scor=scor + '".$_SESSION['score']."' WHERE id=2
This can be exploited by sql injection, but its out of the scope of the question.
you can use the following statement
$sql = "SELECT scor FROM users (UPDATE users SET scor= scor + '".$_SESSION['score']."' WHERE id=2)";

(MYSQL) How to insert a record only if it doesn't exist in a table

Hi maybe this question has already been answered but nothing has been helpful.
I'm using Mysql and I want to insert some data in a table but i want to check for duplicated records before inserting .
I'm very confused about how to achieve this.
I need to check if "RFC==$Expediente AND Diagonal ==10 or Diagonal==20" and show something like "Record already Exist",
or insert all the data if record doesn't exist
this is my script :
<?php
$Person_name=$_POST['Person_name'];
$Expediente=$_POST['Expediente'];
$Sexo=$_POST['Sexo'];
$Edad=$_POST['Edad'];
$Domicilio=$_POST['Domicilio'];
$numero=$_POST['Numero'];
$colonia=$_POST['Colonia'];
$Ciudad=$_POST['Ciudad'];
$Parentesco=$_POST['Parentesco'];
$ClinicaAds=$_POST['ClinicaAds'];
$Dependencia=$_POST['Dependencia'];
$Entidad=$_POST['Entidad'];
$Foraneo=isset($_POST['Foraneo']) ? 1 : 0;
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "issste";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = " INSERT INTO paciente (RFC, Nombre, Sexo, FechaNacimiento, Calle, NumeroDomiciliario, Colonia, Ciudad, Dependencia, ClinicaAdscrip, Entidad, Foraneo, Diagonal)
SELECT '$Expediente', '$Person_name', '$Sexo', '$Edad', '$Domicilio', '$numero', '$colonia', '$Ciudad', '$Dependencia', '$ClinicaAds', '$Entidad', '$Foraneo', '$Parentesco' FROM paciente
WHERE NOT EXIST(
SELECT RFC, Diagonal FROM paciente WHERE RFC = '$Expediente' AND Diagonal='10' OR Diagonal='20') LIMIT 1 ";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
when i run my program i get this error
"you have an error in your sql syntax check the manual that corresponds to your mysql server version"
Modified your query, try something like this:
INSERT INTO paciente (RFC, Nombre, Sexo, FechaNacimiento, Calle, NumeroDomiciliario,
Colonia, Ciudad, Dependencia, ClinicaAdscrip, Entidad, Foraneo, Diagonal)
SELECT '$Expediente', '$Person_name', '$Sexo', '$Edad', '$Domicilio', '$numero',
'$colonia', '$Ciudad', '$Dependencia', '$ClinicaAds', '$Entidad', '$Foraneo',
'$Parentesco'
WHERE NOT EXISTS( SELECT RFC, Diagonal FROM paciente
WHERE RFC = '$Expediente' AND Diagonal='10' OR Diagonal='20' LIMIT 1 )

PHP Update MySQL, form input coming through as column name

So I am sorry as I feel I ask stupid questions a lot. I am learning as I go but getting there.
I've created a basic HTML form and with the help of a previous answer I've made the PHP and MySQL query. However when I submit the form the input values from the form come up as column names rather than the information to be updated in the row.
In simple terms when the form is submitted if the input is to change first name from James to Josh the error message is:
"Error updating record: Unknown column 'Josh' in 'field list'"
I though in my SQL query below it would pick up the column name as first_name but this is obviously not happening.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "Users";
//Create variables
$first_name=$_POST['first_name'];
$last_name=$_POST['last_name'];
$ID=$_POST['ID'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE Users SET first_name=$first_name, last_name=$last_name WHERE
ID=$ID";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
I don't know PHP, but I suspect that your problem is that you arent't quoting the value in your update statment. So try something like:
"UPDATE Users SET first_name='$first_name', last_name='$last_name' WHERE ID=$ID"

Update points of a user in mysql database using php [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am trying to take a string username from my android app and use that username to add 5 points to that specific users account.
Example:
My database now: user_id name username password points
1 test test test 0
What I want: user_id name username password points
1 test test test 5
Here is the php code I'm using right now, something must be wrong with it:
<?php
$con = mysqli_connect("localhost", "id177667_root", "***", "id177667_loginb");
$username = $_POST["username"];
$sql = "UPDATE user ". "SET points = points + 5 ". "WHERE username = $username" ;
$response = mysqli_query($sql, $con);
?>
You confused the parameters for mysqli_query. It should be mysqli_query($con, $sql); instead. Also there are a couple of other problems - this should work:
<?php
$con = mysqli_connect("localhost", "id177667_root", "***", "id177667_loginb");
$username = mysqli_real_escape_string($con, $_POST["username"]);
$sql = "UPDATE user SET points = points + 5 WHERE username = '$username'" ;
$response = mysqli_query($con, $sql);
?>
As it was suggested, prepared statements are the preferred way to go. So you could do this... tested it now, and it works for me:
<?php
$points = 5;
// Connect to database (credentials should not be stored in code...)
$con = new mysqli("localhost", "id177667_root", "***", "id177667_loginb");
// Check if connection succeeded
if ($con->connect_error)
die("Connection error: " . $con->connect_error);
// Prepare statement
if ($st = $con->prepare("UPDATE user SET points = points + ? WHERE username = ?")) {
// Bind parameters (i for integer value, s for string)
$st->bind_param("is", $points, $_POST["username"]);
// Execute statement
$st->execute();
// Close statement
$st->close();
} else {
// Prepare failed: report error
die("Prepare failed: " . $con->error);
}
// Close DB connection
$con->close();
?>

How to use SET and INSERT in one php variable?

This is not duplicated question, since I am asking how to use SET and INSERT in one PHP variable, there no any questions about AUTO_INCREMENT...
I have below page:
<?php
function genWO(){
$dbtype = "MySQL";
$username = "user";
$password = "pass";
$hostname = "10.10.10.10";
$dbname = "TABLES";
//connection to the database
$conn = new mysqli($hostname, $username, $password);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$insertNewWONum = "SET #MAX_WO = (SELECT max(WO_NUM) + 1 from GENERIC_TABLES.WO_NUMBERS); INSERT INTO GENERIC_TABLES.WO_NUMBERS (WO_NUM, WO_REQUESTOR) values (#MAX_WO, `test`)";
if ($conn->query($insertNewWONum) === TRUE) {
echo "New record created successfully". "<br>";
} else {
echo "Error: " . $insertNewWONum . "<br>" . $conn->error;
}
$getWONum = "SELECT LPAD(max(WO_NUM) ,6,0) as NEW_WO_NUM from GENERIC_TABLES.WO_NUMBERS";
$result = $conn->query($getWONum);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "New WO Number: " . $row["NEW_WO_NUM"]. "<br>";
}
} else {
echo "0 results";
}
//close the connection
$conn->close();
}
?>
Since it is not allowed to use INSERT and SELECT for the same table in one query, I am trying to set variable and use it in INSERT query:
$insertNewWONum = "SET #MAX_WO = (SELECT max(WO_NUM) + 1 from GENERIC_TABLES.WO_NUMBERS); INSERT INTO GENERIC_TABLES.WO_NUMBERS (WO_NUM, WO_REQUESTOR) values (#MAX_WO, `test`)";
But it doesnt work, though it works fine if I am using this query in terminal.
Can anyone let me know how to achieve it please?
Since it is not allowed to use INSERT and SELECT for the same table in one query
All issues with your approach aside of course you can use INSERT and SELECT in one statement
INSERT INTO WO_NUMBERS (WO_NUM, WO_REQUESTOR)
SELECT COALESCE(MAX(WO_NUM), 0) + 1, 'Test'
FROM WO_NUMBERS;
Here is SQLFiddle demo.
Now what you need to realize is that your approach is unsafe for concurrent access. If this code is executed from two or more sessions simultaneously some or all of them may generate the same number effectively breaking your application.
Use AUTO_INCREMENT instead.
CREATE TABLE WO_NUMBERS
(
WO_NUM INT PRIMARY KEY AUTO_INCREMENT,
WO_REQUESTOR VARCHAR(32)
);
INSERT INTO WO_NUMBERS (WO_REQUESTOR) VALUES ('Test');
Here is SQLFiddle demo.
If for some reason you can't use AUTO_INCREMENT directly (and I honestly don't see why you couldn't) i.e. you need to add prefixes or augment the generated id/code in some way you can look this answer.

Categories