This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 7 years ago.
I'm trying to insert a variable into a mysql database. I've read the various posts about how to do this however these don't seem to work for me, the following code doesn't write anything to the database (the variable seems to break the query) however does if I don't use variables, can anyone tell me what I've doing wrong here?
$dbhost = 'zzzzzzzzz';
$dbuser = 'xxxxxxxxx';
$dbpass = 'yyyyyyyyy';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
// VARIABLE SETUP;
$variable = 'variable';
$variable = mysql_real_escape_string($variable);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$sql = 'INSERT INTO db_variables_insert'.
'(time, variable) '.
'VALUES ( "2016-02-19 04:23:44", '$variable')';
mysql_select_db('wwwwww');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($conn);
First of all, for your issue you could try:
$sql = "INSERT INTO db_variables_insert".
"(time, variable) ".
"VALUES ( '2016-02-19 04:23:44', '".$variable."')";
However, you could rewrite this more sane as a prepared statement like:
/* mysqli_* to connect - ** See note on PDO below ** */
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
/* Prepared statement, stage 1: prepare */
$sql = "INSERT INTO db_variables_insert (time, variable) VALUES (?,?)";
if ($stmt = $mysqli->prepare($sql)) {
/* Prepared statement, stage 2: bind parameters and execute */
$time = '2016-02-19 04:23:44';
// Assuming you already define $variable here
if ($stmt->bind_param("ss", $time, $variable)) {
/* Here this bit ^ can be "i" (integer), "s" (string) etc */
$execute = $stmt->execute();
if($execute === FALSE) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
/* ^ you are done executing the sql if no errors */
} else {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
} else {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
/* explicit close recommended */
$stmt->close();
Notes:
/** Recommended: Connect with PDO **/
$conn = new PDO('mysql:host=localhost;dbname=my_db;charset=UTF-8','user', 'pwd');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
^ useful to visit and practice:
PDO Tutorial for MySQL Developers
Prepared Statements
You need to use . to concatenate strings in PHP, you can't just put the variable next to the string. And if the variable column is a string, you need to put its value in quotes.
$sql = 'INSERT INTO db_variables_insert'.
'(time, variable) '.
'VALUES ( "2016-02-19 04:23:44", "' . $variable'")';
You can also write this as a single string with variable substitution, using double quotes around the PHP string.
$sql = "INSERT INTO db_variables_insert
(time, variable)
VALUES ( '2016-02-19 04:23:44', '$variable')";
Related
This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Can I mix MySQL APIs in PHP?
(4 answers)
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 5 years ago.
I have two tables - oldtbldata & tbldata, and want to read a row in the first and insert it into the second table. One new column, txtNotes does not exist in the old table, I want to set that to a space.
The oldtbldata has rows that do not exist in tbldata, and I want to insert these into the tbldata as new rows.
I have established an original connection (conn) to do the initial search for matching txtWoodIDcode entries, if a row is found that does not exist, I want to add that to the tbldata using conn2.
The initial code is:
$conn = mysql_connect('localhost', '***', '*****');
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
echo "Conn connected<br>";
$sql = 'SELECT oldtxtWoodIDcode FROM oldtbldata';
mysql_select_db('scw-db');
If the search does not find the ID, it goes to this code:
{
$conn2 = mysql_connect('localhost', '***', '***');
if(! $conn2 )
{
die('Could not connect #2: ' . mysql_error());
}
echo "Conn2 connected<br>";
$sql_new = 'SELECT txtWoodIDcode FROM tbldata';
mysql_select_db('scw-db');
$retval = mysql_query( $sql, $conn2 );
if(! $retval )
{
die('Could not get data from conn2: ' . mysql_error());
}
$sql_new = "INSERT INTO tbldata
(
'txtWoodIDcode',
'txtProductCode',
'txtNotes',
'txtSpecies',
)
VALUES
{
'oldtxtWoodIDcode',
'oldtxtProductCode',
' ',
'oldtxtSpecies',
)";
echo "past the insert code<br>";
if ($conn2->query($sql_new) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql_new . "<br>" . $conn2->error;
}
mysql_close($conn2);
}
The error I get is on the if ($conn2->query($sql_new) === TRUE) line:
Fatal error: Call to a member function query() on a non-object
And yes, I get the "Conn2 connected" message, so I should be connected to the DB.
I am new to PHP/MySQL, and working with an old version - so I know I need to upgrade - but will need to do that later. I just need to get THIS code working now.
you have few mistakes
- you don't have in mysql ... $conn2->query ... use mysql_query function
- in the query you using single quot for the fields name ' ... you need to use ` , and remove the comma , after the kast field
$conn2 = mysql_connect('localhost', '***', '***');
if(! $conn2 )
{
die('Could not connect #2: ' . mysql_error());
}
echo "Conn2 connected<br>";
$sql_new = 'SELECT txtWoodIDcode FROM tbldata';
mysql_select_db('scw-db');
$retval = mysql_query( $sql, $conn2 );
if(! $retval )
{
die('Could not get data from conn2: ' . mysql_error());
}
$sql_new = "INSERT INTO tbldata
(
`txtWoodIDcode`,
`txtProductCode`,
`txtNotes`,
`txtSpecies`
)
VALUES
{
'oldtxtWoodIDcode',
'oldtxtProductCode',
' ',
'oldtxtSpecies'
)";
echo "past the insert code<br>";
if ($conn2->query($sql_new) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql_new . "<br>" . $conn2->error;
}
mysql_close($conn2);
I have been using the traditional method of query db with out prepared statement. So decided to move to prepared statement now as below are my codes.
$link = new mysqli(dbHost, dbUser, dbPassword, dbDatabase);
if($link->connect_error) {
die('bind_param() failed: ' . htmlspecialchars($link->connect_error));
}
$stmt = $link->stmt_init();
$selectQuery1 ="Select * From tblUser Where tblUser.userName=? ";
$stmt1 = mysqli_prepare($link, $selectQuery1);
if ( false===$stmt1 ) {
die('stmt1 prepare() failed: ' . htmlspecialchars($mysqli->error));
}
$rc1 = $stmt1->bind_param('s', $userName);
if ( false===$rc ) {
die('rc1 bind_param() failed: ' . htmlspecialchars($stmt1->error));
}
$execute1 = $stmt1->execute();
if ( false===$execute1 ) {
die('execute1 execute() failed: ' . htmlspecialchars($stmt1->error));
}
$store1=$stmt1->store_result();
if ( false===$store1 ) {
die('store1() failed: ' . htmlspecialchars($stmt1->error));
}
$count1=$stmt1->num_rows;
$result1 = $stmt1->get_result();
if ( false===$result1 ) {
die('result1 () failed: ' . htmlspecialchars($stmt1->error));
}
The query worked well till this line $count1=$stmt1->num_rows; and the moment I put this codes $result1 = $stmt1->get_result(); my page failed and I found out that I must now change to mysql native driver etc. My biggest worry is by changing the driver it might effect all my other existing application. So what is the best mechanism to mitigate is there any other method to retrieve the result or move to PDO ? I want to be able to use this mechanism mysql_fetch_array($result, MYSQL_ASSOC) to get my select results ?
I got this query and it's not inserting into the database but it's not giving an error either.
try {
$sth = $Db->dbh->prepare("INSERT INTO users (username,password,email,phone,first_name) VALUES (:username,:password,:email,:phone,:firstname)");
$sth->execute(array(':username' => $username,':password' => $password, ':email' => $email,':phone' => $phone,':firstname'=>$firstname));
} catch(Exception $e) {
echo $e->getMessage();
exit();
}
I've tried inserting the query by command and it works fine. There are other insert queries on the site and those work fine too.. I'm not sure what I'm doing wrong here
Can you try something like this?
try
{
// Prepare Statement
if (!($stmt = $mysqli->prepare("INSERT INTO users (username,password,email,phone,first_name) VALUES (?,?,?,?,?)")))
throw new Exception("Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error);
// Bind Parms
if (!$stmt->bind_param("sssss", $username, $password, $email, $phone, $firstname))
throw new Exception("Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error);
// Execute Statement
if (!$stmt->execute())
throw new Exception("Execute failed: (" . $stmt->errno . ") " . $stmt->error);
}
catch (Exception $ex) {
exit('Error: '. $ex->getMessage());
}
P.S. As TiiJ7 suggestion on the comment to your question, are those two columns perm and rank - are they nullable columns? if not, you might have to specify a value at the time of row insertion.
More info here: http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
I'm having a problem with my update script. Basically I enter values into textboxes and when I click on 'Add' these values get added to the database.
At the moment it is allowing me to enter intergers and these getting added to the database but when I try to add text it doesn't. The database field types are set to varchar(20) and this is my PHP code:
public function insert($tableName,$fieldArray,$fieldValues) {
$pdo = new SQL();
$dbh = $pdo->connect(Database::$serverIP, Database::$serverPort, Database::$dbName, Database::$user, Database::$pass);
$this->sql = "INSERT INTO " . $tableName . " (".implode(',', $fieldArray).") VALUES (".implode(',', $fieldValues).")";
try {
// Query
$stmt = $dbh->prepare($this->sql);
$stmt->execute();
$count = $stmt->rowCount();
echo $count.' row(s) inserted by SQL: '.$stmt->queryString;
$stmt->closeCursor();
}
catch (PDOException $pe) {
echo 'Error: ' .$pe->getMessage(). 'SQL: '.$stmt->queryString;
die();
}
// Close connection
$dbh = null;
}
Please let me know what I am doing wrong! :)
Change the sql query line to:
$this->sql = "INSERT INTO " . $tableName . " (`".implode('`, `', $fieldArray)."`) VALUES ('".implode("', '", $fieldValues) . "')";
The thing is you are not escaping strings with quotes. Like 'someText'
You need to enclose your fields into quotes.
Put the text as such
$text = "text"; //How you're doing it now
$text = "'text'"; //How you ought to (after sql escaping)
Or try this:
$this->sql = "INSERT INTO " . $tableName . " (`".implode('`,`', $fieldArray)."`) VALUES ('".implode("','", $fieldValues)."')";
I am trying to use mysqli for the first time because i have some problems with multiple Query's in one php file. for start im just trying to retrieve data from the stored procedure and print it. but it looks like the code get's stuck somewhere it printed 'succesfull localhost' but it never get's to the code under it. The data never get printed neither the failed.
<?php
$link = mysqli_init();
if (!$link) {
die('mysqli_init failed');
}
if (!mysqli_options($link, MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0')) {
die('Setting MYSQLI_INIT_COMMAND failed');
}
if (!mysqli_options($link, MYSQLI_OPT_CONNECT_TIMEOUT, 5)) {
die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed');
}
if (!mysqli_real_connect($link, 'localhost', 'root', '', 'fabiola')) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
echo 'Success... ' . mysqli_get_host_info($link) . "\n";
//require 'header.php';
$resID = mysqli_real_escape_string($_REQUEST['resID']);
$materialen_id = mysqli_real_escape_string($_REQUEST['materialen_id']);
$aantal = mysqli_real_escape_string($_REQUEST['aantal']);
$effectief_gebruikt = mysqli_real_escape_string($_REQUEST['effectief_gebruikt']);
$opmerking = mysqli_real_escape_string($_REQUEST['opmerking']);
$datum_van = $_REQUEST['datum_van'];
$datum_tot = $_REQUEST['datum_tot'];
$sqm = "CALL aantal_besch_mat_van_tot($datum_van,$datum_tot,$materialen_id,$resID)";
//$result = $mysqli->query($sqm) or die('Query Failed!');
/* Select queries return a resultset */
if ($result = $mysqli->query($sqm)) {
printf("Select returned %d rows.\n", mysqli_num_rows($result));
/* free result set */
mysqli_free_result($result);
}else{
echo 'failed';
}
mysqli_close($link);
?>
Where is $mysqli set or initialized?
There should be something like:
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
but I can't see it.
btw it's weird that you're mixing the function calling convention 'mysqli_real_escape_string(...)' with the object-orientated functions '$mysqli->query(...)' I'm not sure it's safe to do both.
Also, you will save yourself a lot of heartache by using the MySQLi prepared statements rather than trying to make all your input safe by hand e.g.
$query = "CALL aantal_besch_mat_van_tot(?, ?, ?, ?);";
$statement = $mysqli->prepareStatement($query);
$statement->bind_param('iiii', $datum_van, $datum_tot, $materialen_id, $resID);
$statement->execute();
//get the results.
$statement->close();
$mysqli->close();
It's just so much easier, and more secure to use prepared statements (at the cost of a few percent of performance) that really you should almost always use them.