I am very new to php programming. I have tried googling and searching this website for a fix to this but I don't know what to even type into google to really find my answer.
I get the error:
unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING
I am unsure what I can do avoid this.I know it is caused by the ['userid'] but I need that as part of my coding.
Here is my code:
<?php
include ('auth/userInfo.php');
$servername = "example";
$username = "example_1";
$password = "example";
$dbname = "example_enter";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$userprofile['userid'] = mysqli_real_escape_string($userprofile['userid']);
$sql="INSERT INTO today (accessed)
VALUES ('$userprofile['userid']')";
if ($conn->query($sql) === TRUE) {
echo "Success";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
In case my coding is so bad that no one knows what it is attempting to do. I am attempting to write to a MySQL DB when a user has signed in.
The problem is caused by the fact that you are (a) using quotes to reference an array index inside a literal string (b) inserting a line break inside that same string:
$sql="INSERT INTO today (accessed)
VALUES ('$userprofile['userid']')";
What you probably meant to write is:
$sql="INSERT INTO today (accessed) VALUES ('" . $userprofile['userid'] . "')";
However even this is problematic due to SQL injection attacks - I recommend you read up on parameterized queries (mysqli_prepare).
Related
I am following the last part of the following video tutorial "How to create a database website with PHP and mySQL 07 - Add in input form" :
https://www.youtube.com/watch?v=MGIG00d1Xzc&list=PLhPyEFL5u-i0zEaDF0IPLYvm8zOKnz70r&index=7
At the end here is my code, for the inserting portion to the database for the new_jokes.php script (everything up to this point of the series I have gotten to work fine so far)
Basically I am getting the seemingly classic "INSERT INTO" not working although all my syntax looks correct. Am I missing something obvious here? I get no errors, just the row isn't added.
<?php
include "db_connect.php";
$new_joke_question = $_GET["newjoke"];
$new_joke_answer = $_GET["newanswer"];
// Search the database for the word chicken
echo "<h2>Trying to add a new joke and answer: $new_joke_question
$new_joke_answer </h2>";
$sql = "INSERT INTO Jokes_table (JokeID, Joke_question, Joke_answer) VALUES
(NULL, '$new_joke_question', '$new_joke_answer' )";
$result = $mysqli->query($sql);
include "search_all_jokes.php";
?>
Return to the main page
Here is the db_connect.php code as requested:
<?php
// four variables to connect the database
$host = "localhost";
$username = "root";
$user_pass = "usbw";
$database = "test";
// create a database connection instance
$mysqli = new mysqli($host, $username, $user_pass, $database);
?>
Here is search_all_jokes.php (which has minor error checking):
// if there are any values in the table, select them one at a time
if ($mysqli->connect_errno) {
echo "Connection to MySQL failed: (" . $mysqli->connect_errno . ") " .
$mysqli->connect_error;
}
echo $mysqli->host_info . "<br>";
$sql = "SELECT JokeID, Joke_question, Joke_answer FROM Jokes_table";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "JokeID: " . $row["JokeID"]. " - Joke_question: " .
$row["Joke_question"]. " " . $row["Joke_answer"]. "<br>";
}
} else {
echo "0 results";
}
?>
Also here is the table structure screenshot viewed in myPHPAdmin:
I added error capturing into new_jokes.php inspired by this Stack Overflow post:
INSERT INTO SYNTAX ERROR
And get the following error:
Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 't jump.' )' at line 1localhost via TCP/IP
Thank you everyone for helping out with this! Syntax can really throw a wrench in everything. I also will read up on prepared statements since that also could have prevented the issue. The ultimate help to this I found the solution to by adding the function referenced here for MySQLi real_escape_string to clean the single quote I had within the answer I was submitting to my joke table:
(Can a kangaroo jump higher than the empire state building? Of course, the empire state building can't jump.)
As shown in the documentation #miken32 linked as a comment here it is says: "But if $val1 or $val2 contains single quotes, that will make your SQL be wrong. So you need to escape it before it is used in sql; that is what mysql_real_escape_string is for. (Although a prepared statement is better.)"
But now the code for this part 7 of the tutorial on you tube I found works and adds it into a row on the database table, then displaying the full new table on the next webpage. I spent a good while shooting in the dark on while the answer ended up being fairly simple. Again special thanks to #miken32 for pointing me the right direction.
Here is my completed code that ended up working to at least achieve the goal of the tutorial:
<?php
include "db_connect.php";
$new_joke_question = $_GET["newjoke"];
$new_joke_answer = $_GET["newanswer"];
$new_joke_question = $mysqli->real_escape_string($new_joke_question);
$new_joke_answer = $mysqli->real_escape_string($new_joke_answer);
// Search the database for the word chicken
echo "<h2>Trying to add a new joke and answer: $new_joke_question $new_joke_answer
</h2>";
if ($mysqli->connect_errno) {
echo "Connection to MySQL failed: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "<br>";
$sql = "INSERT INTO Jokes_table (JokeID, Joke_question, Joke_answer) VALUES (' ',
'$new_joke_question', '$new_joke_answer' )";
$result = $mysqli->query($sql);
if ($mysqli->query($sql) === TRUE) {
echo 'users entry saved successfully';
}
else {
echo 'Error: '. $mysqli->error .'<br>';
}
include "search_all_jokes.php";
?>
Return to the main page
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 4 years ago.
I have a problem, I can't upload anything to database. In my database in the jelenlet table there is a jelen which is integer and a gyerekneve which is text.
Here is my php code:
<?php
$servername = "...";
$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 = "INSERT INTO 'jelenlet' ('gyerekneve', 'jelen') VALUES ('barmi', 0)";
if ($conn->query($sql) === TRUE) {
echo "Hozzaadtad ezt a nevet: ";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
And don't know what is the problem with the code. The page says:
Error: INSERT INTO 'jelenlet' ('gyerekneve', 'jelen') VALUES ('barmi',
0) You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near ''jelenlet' ('gyerekneve', 'jelen') VALUES ('barmi', 0)' at line
1
$sql = "INSERT INTO jelenlet (gyerekneve, jelen) VALUES ('barmi', 0)";
This will work. BUT make sure to use prepared statements when you will try to pass variables to this one and not static values. The problem was that you were using single-quotes when you didn't have to. If you want to escape fields in a query you can use this : `
This query would also work :
$sql = "INSERT INTO `jelenlet` (`gyerekneve`, `jelen`) VALUES ('barmi', 0)";
This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 5 years ago.
First off, yes I have done research and have seen tons of posts like this one. I see the post this is supposed to be a duplicate of but it was not helpful. I am very new with this and do not know how to apply their results to mine.
I'm getting this result when running:
Parse error: syntax error, unexpected '$_GET' (T_VARIABLE) in /storage/ssd4/269/2113269/public_html/updateuser.php on line 12
Here is my script:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// 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 Status = '"$_GET["status"]"' ".
"WHERE Username = '"$_GET["username"]"'";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
Thank you a bunch for taking a look. I might be missing a semi-colon somewhere but I've looked over the code for a while. Please let me know!
You have to concatenate string using .
$sql = "UPDATE Users ". "SET Status = '".$_GET["status"]."' ".
"WHERE Username = '".$_GET["username"]."'";
You need to concatenate string and variable using dot(.) properly like this
$sql = "UPDATE Users
SET Status = '".$_GET["status"]."'
WHERE Username = '".$_GET["username"]."'";
This is because you end and start the statement with " before and after the the GET statement declaration; but haven't put the concatenation . in between the " and GET.
"SELETCT tb FROM db WHERE field = '".GET ['something']."'";
It's also a good habit to wrap the two GET in a IF statement and run the full code if bot Get has some value. Reduce the unnecessar SQL and PHP execution.
I have a small issue with my syntax, I am trying to accomplish a project and I have a slight issue.
<?php
include('includes/db_credentials.php');
// connection
$conn = new mysqli($servername, $username, $password, $dbname);
// connection chck
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Check strings for strings
$primary_name = mysqli_real_escape_string($conn, $_POST['primary_name']);
$primary_mobile = mysqli_real_escape_string($conn, $_POST['primary_mobile']);
$primary_country = mysqli_real_escape_string($conn, $_POST['primary_country']);
$primary_state = mysqli_real_escape_string($conn, $_POST['primary_state']);
$rand = rand(1,999999999);
$times = 2;
$rpt = str_repeat("('$primary_name', '$primary_mobile', '$primary_country', '$primary_state', '$rand;'), ", $times);
$sql = "INSERT INTO cards (primary_name, primary_mobile, primary_country, primary_state, card_code)
VALUES $rpt";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
$id = mysqli_insert_id();
echo $id;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Error: INSERT INTO cards (primary_name, primary_mobile, primary_country, primary_state, card_code) VALUES ('John Doe', '000 000 0000', 'Afghanistan', 'Badghis', '23605621;'), ('John Doe', '000 000 0000', 'Afghanistan', 'Badghis', '23605621;'),
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 2
I am getting the following MySQL return message, I have been reading here on stackoverflow on the ways to insert multiple rows at once and this is the closest I can get to it, would anyone be able to give me a slight pointer on where I'm doing wrong and or point me in a better direction.
Thanks.
You have an extra comma after your values. I'd suggest doing an array_fill instead, and then imploding it.
$rpt = array_fill(0,$times,"('$primary_name', '$primary_mobile', '$primary_country', '$primary_state', '$rand') ");
$values = implode(',',$rpt);
Your probably hitting the issue whereby the last of your repeated inserts has a comma at the end of it too when the comma isn't needed. Also there's a semi-colon after $rand (is that suppose to be there?)
Quick fix
I've taken the space off the end of your string then I just trim the very last comma in that final string. This keeps your code pretty much the same.
$rpt = str_repeat("('$primary_name', '$primary_mobile', '$primary_country', '$primary_state', '$rand;'),",$times);
$rpt = rtrim($rpt,",");
I am using the following code to insert Event Logs and User Info from my Mobile App to a mysql database.
I am finding the " Character gives me issues later on when in use with JSON arrays that I pull from the db. What I would like to do is remove the " character in the php code completely before posting to the db.
Removing the " character by Javascript from the Mobile App is not really an option.
<?php
$servername = "localhost";
$username = "Fred";
$password = "Barney";
$dbname = "BamBam";
// Create connection
$conn = new mysqli ($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// escape variables for security
$event_log = mysqli_real_escape_string($conn, $_POST['event_log']);
$logged_by = mysqli_real_escape_string($conn, $_POST['logged_by']);
$sql = "INSERT INTO time_event (event_log, logged_by)
VALUES ('$event_log', '$logged_by')";
if ($conn->query($sql) === TRUE) {
echo "Data entered successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Use mysqli_prepare and mysqli_stmt_bind_param to execute a parameterised query. I strongly advise this approach.
If you really want to just escape special characters for manual interpolation
into a query string, use mysqli_real_escape_string.
Hand-rolling a solution presents a real risk that you will
miss something important, leaving your program vulnerable
to SQL injection attacks.
I did not try, but this should do
$sql = sprintf("INSERT INTO time_event (event_log, logged_by)
VALUES ('%s' ,'%s'",$event_log,$logged_by);