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,",");
Related
I'm trying to save an array in a MySQL table, I serialize it and it shows something like a:3:{s:8:"One";s:1:"1";s:6:"Two";s:2:"2";... but I don't want it like this, I want something like this {One = 1, Two = 2} or something similar without those weird characters "a:4", "s:3", I was trying to look up and I was told to deserialize, but it isn't the solution i'm looking for as it shows something like {1,2}. Is there a way to make it look like I'm saying?
This is what I tried to do to deserialize:
$r9 = array("One"=>"1", "Two"=>"2", "Three"=>"3");
$serializedArray = serialize($r9);
$decoded = unserialize($serializedArray);
$respuestaCompleta = $cadena_equipo = implode(",", $decoded);;
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "INSERT INTO encuesta (id, pregunta, respuesta) VALUES ('$id', '$q9', '$respuestaCompleta')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
mysqli_close($conn);
I think you are looking for the following:
$r9 = array("One"=>"1", "Two"=>"2", "Three"=>"3");
$serializedArray = json_encode($r9); // or use serialize() here
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "INSERT INTO encuesta (id, pregunta, respuesta) VALUES ('".$id."', '".$q9."', '".$serializedArray."')";
if($conn->query($sql) === true){
echo "New record created successfully";
}
else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
mysqli_close($conn);
To get the real array again use this code:
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT respuesta FROM encuesta;";
$result = $conn->query($sql);
$row = $result->fetch_array();
$r9 = null;
if(is_array($row) && count($row) > 0){
$r9 = json_decode($row[0], true); // or unserialize() if serialize was used
}
I recommend to use json_encode(). serialize() is a php specific command. This means that other programming languages, which may interact with your database in future, cannot use the data. In addition you json gives you a more genral way. In my opinion it is easier to read. serialize() is more powerful than json_encode(). But you because you are not using objects this is no extra you need.
In general you are converting your array to a string (with eigher the serialize() or the json_encode() method). The database cannot handle an array because there are no arrays in MYSQL. Also this is a structure of the php language.
The generated string is equal to the array representation. MYSQL can handle strings so this string can then be saved to the database.
If you are loading the value from the database again you will receive the saved string. This string can then be converted back to an array by using the opposite command (json_decode() or unserialize()).
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)";
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);
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).