I am trying to use a variable to insert into multiple tables. When I hard code the specific table name it runs properly, when I use a variable I get a QUERY FAILEDSQLSTATE[42000]: Syntax error or access violation: 1064 error. dbname is the variable. I am using a for loop to change the name of the table. For example table 1 is budget1000, then budget 2000 etc. Here is my code
$sql='INSERT INTO ".$dbName." VALUES(:id,:category,:subCategory,
:amount, :today,:description, :year)';
try{
$st= $conn->prepare($sql);
$st->bindValue(":id", $id, PDO::PARAM_INT);
$st->bindValue(":category", $category, PDO::PARAM_INT);
$st->bindValue(":subCategory", $subCategory, PDO::PARAM_INT);
$st->bindValue(":amount", $amount, PDO::PARAM_INT);
$st->bindValue(":today", $today, PDO::PARAM_STR);
$st->bindValue(":description", $description, PDO::PARAM_STR);
$st->bindValue(":year", $year, PDO::PARAM_INT);
$st->execute();
}catch(PDOException $e ){
echo "QUERY FAILED" . $e->getMessage();
}
It looks like there's a quote mismatch, you start off with single quotes but then switch to double quotes when you concatenate the DB name into your string. Try replacing the single quotes at the beginning and end of your $sql string with double quotes and remove the periods around $dbname, or use single quotes all the way through.
Try this instead:
$sql='INSERT INTO '.$dbName.' VALUES(:id,:category,:subCategory,:amount, :today,:description, :year)';
Related
the pdo update statement below doesn't work due the table name ties to a variable. Does anyone know how to make it work?
$stmt1 = $DB_CON_C->prepare('UPDATE `".$account_list."`
SET property_type=:property_type; property_address=:property_address, property_city=:property_city, property_state=:property_state, property_zip=:property_zip WHERE contract_number=:order_list');
$stmt1->bindParam(':account_list', $account_list, PDO::PARAM_STR);
$stmt1->bindParam(':order_list', $order_list, PDO::PARAM_STR);
$stmt1->bindParam(':property_class', $property_class, PDO::PARAM_STR);
$stmt1->bindParam(':property_type', $property_type, PDO::PARAM_STR);
$stmt1->bindParam(':property_address', $property_address, PDO::PARAM_STR);
$stmt1->bindParam(':property_city', $property_city, PDO::PARAM_STR);
$stmt1->bindParam(':property_state', $property_state, PDO::PARAM_STR);
$stmt1->bindParam(':property_zip', $property_zip, PDO::PARAM_STR);
$stmt1->execute();
You will have to user single quotes in stead of double:
$stmt1 = $DB_CON_C->prepare('UPDATE `' .$account_list. '`
SET property_type=:property_type; property_address=:property_address, property_city=:property_city, property_state=:property_state, property_zip=:property_zip WHERE contract_number=:order_list');
Or, just simplify, and do:
->prepare("UPDATE {$account_list} SET...
Ie, use double quotes. The {} isn't needed, but I prefer using them because I personally use this as a prefix to the actual table name (so ("SELECT * FROM {$dbprefix}tablename"))
This way you do not need to concoct strings inside the query, which you shouldn't need to do. Just wrap the query in double quotes instead.
This is the code to connect to my database. I am sure the username, password and database name are correct.
$Myconn = mysqli_connect($this->host, $this->user, $this->pass, $this->DBname);
This is code for prepare statement:
$query =$Myconn->prepare("SELECT * FROM `AD` WHERE name=?");
$query->bind_param('s', $AD_Name);
$query->execute();
$query->store_result();
$query->bind_result($id, $name, $price);
and I am sure that I sent $AD_Name correctly, as well as my query.
I used AMPPS and it was working while using my code.
My problem is that my result is always null when i print $id or $name or $price.
Ali Rasheed is right that you should use fetch() after doing a bind_result(), but there is a bigger issue here. You cannot use bind_result() with SELECT * .... It will not work properly because bind_result() will not know the order of the selected elements and thus it will not know which variable should get which value. Instead, you should revise to something like:
$query =$Myconn->prepare("SELECT id, name, price FROM `AD` WHERE name=?");
$query->bind_param('s', $AD_Name);
$query->execute();
$query->store_result();
$query->bind_result($id, $name, $price);
$query->fetch();
Substitute the column names as necessary of course.
You can see a good explanation about that here: https://stackoverflow.com/a/18753263/2694511
After doing
$query->bind_result($id, $name, $price);
use
$query->fetch();
SO I'm using PHP and PDO to insert data into a MySQL database.
function addLog($id, $wd, $m, $md, $t, $tz, $y, $ilp, $igp)
{
echo "|2|$wd/$m/$md/$t/$tz/$y/$ilp/$igp|";
$connection = connectUserLogfiles();
try
{
$sql = "INSERT INTO `log_meta` (`log_id`, `weekday`, `month`, `month_day`, `time`, `time_zone`, `year`, `inside_local_ip`, `inside_global_ip`) VALUES (log_id=:log_id, weekday=:weekday, month=:month, month_day=:month_day, time=:time, time_zone=:time_zone, year=:year, inside_local_ip=:inside_local_ip, inside_global_ip=:inside_global_ip);";
$stmt = $connection->prepare($sql);
$stmt->bindParam(':log_id', $id, PDO::PARAM_STR);
$stmt->bindParam(':weekday', $wd, PDO::PARAM_STR);
$stmt->bindParam(':month', $m, PDO::PARAM_STR);
$stmt->bindParam(':month_day', $md, PDO::PARAM_STR);
$stmt->bindParam(':time', $t, PDO::PARAM_STR);
$stmt->bindParam(':time_zone', $tz, PDO::PARAM_STR);
$stmt->bindParam(':year', $y, PDO::PARAM_STR);
$stmt->bindParam(':inside_local_ip', $ilp, PDO::PARAM_STR);
$stmt->bindParam(':inside_global_ip', $igp, PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->rowCount();
$stmt->closeCursor();
return $result;
} catch (Exception $ex) {
$_SESSION['error'] = '<p>Error: something went wrong in addLog(), and we have absolutely no idea why. Sorry.</p>';
}
}
the result of the echo statement is as follows:
|1|Sun/Dec/31/12:12:12/Africa/Abidjan/2015/10.0.0.0/9.0.0.0|
Also, a message is displayed which indicates that one row was successfully returned in the Result Set via the $result variable. (this occurs in the index, but i assure you, one row is returned in the Result Set.)
My problem is that the database indicates that every column-value in the inserted row has a value of zero. This also goes for the Primary Key, which is NOT auto-incremented, because that is taken care through the use of PHP. (the lack of auto-increment is a result of how this database is tied to an app and how that app functions.)
After this query is executed, the user is taken to a view which correctly displays all of the associated information as the user inputted the data. However, this is based on the local variables from the user input, and not the database. I felt this was safe to do because at that point, i have confirmed that the user input was valid and that it was inserted into the database correctly.
My primary key, the log_id,is an INT data type.
All other data types are VARCHAR.
There are NO default values set for the table in the database.
NONE of the columns are set as requiring unique values within their respective columns.
NONE of the columns are Foreign Keys.
ALL of the columns are set as nullable, merely because of my lazyness, and because i've already check for null values before this point in the INSERT process.
WHY does the insert not work correctly? I use PHPMyAdmin to operate with the database
Remove the columns from the VALUES (...) of your query -
$sql = "INSERT INTO `log_meta` (`log_id`, `weekday`, `month`, `month_day`, `time`, `time_zone`, `year`, `inside_local_ip`, `inside_global_ip`) VALUES (:log_id, :weekday, :month, :month_day, :time, :time_zone, :year, :inside_local_ip, :inside_global_ip);";
You already defined them in the query, and since there was not space between the equal sign and semicolon - =: your params were not recognized as params.
I have a problem with PDO prepare query. When I try to insert a simple string with double quotes like this 'example string " to be inserted in mysql', the query result is truncated when the double quotes start and the result in MySQL is 'example string'.
Does anyone had this problem with pdo?
This is my query:
$sql = "UPDATE sales
SET note = :note
WHERE id_sale= :id";
$stmt = $db->prepare($sql);
$stmt->bindParam(':note', $this->note, PDO::PARAM_STR, 80);
$stmt->bindParam(':id', $this->id, PDO::PARAM_INT);
$stmt->execute();
Thanks in advance!
You have to escape the quotes properly depending on the underlying database.
PDO can do this for you, check out PDO::quote.
$string = 'Example string';
print "Quoted string: " . $conn->quote($string);
Output will be
Quoted string: 'Example string'
The current error when running this from the command line is "Call to a member function bindParam() on a non-object" which I've worked out to being a problem with the variable $orderPO. Something does not like non-numeric characters which led me to the bindParam PARAM_STR business which does not work either. The database fields are both varchar 50.
My search skills are failing me. I know this must be posted somewhere about a million times but I can't seem to find it. I am completely open to doing this another way if someone has a better idea.
Current attempt code:
try
{
$orderNum = '123456';
$orderPO = '123456-A';
$dbh = new PDO("mysql:host=localhost;dbname=dbname", 'someuser', 'somepass');
$stm = $dbh->prepare("insert into some_table (order_number, order_po)");
$stm->bindParam(':order_number', $orderNum, PDO::PARAM_STR);
$stm->bindParam(':order_po', $orderPO, PDO::PARAM_STR);
$stm->execute();
print_r($stm);
print_r($dbh);
$arr = $stm->errorInfo();
print_r($arr);
$stm->closeCursor();
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
In order to bind parameters using PDO, you will need to use placeholders, like this:
$stm = $dbh->prepare("
INSERT INTO `some_table` SET
`order_number` = :order_number,
`order_po` = :order_po
");
$stm->bindParam(':order_number', $orderNum, PDO::PARAM_STR);
$stm->bindParam(':order_po', $orderPO, PDO::PARAM_STR);
Notice the inclusion of the : character before the named placeholder. I also added column names to your query.
Read further and see examples: PDO bindParam
The correct syntax is
$stm = $dbh->prepare("insert into some_table (order_number, order_po) VALUES (?, ?)");
$stm->bindParam(1,$orderNum);
$stm->bindParam(2,$orderPO);
include the questions marks, the numbers in the bindParam call refer to which question mark you're binding the parameter to
You are trying to use bindparam, but bind param matches ? not cursors :. You have not included any parameters or values.
Also, you are missing your VALUES statement within the query, which is causing the query to fail. This is why you get the "Call to a member function bindParam() on a non-object"
To use the :value syntax, use bindValue, not bindParam. to use bindParam, switch the :value to ? in your query and number them in order is your execute array.
try
{
$orderNum = '123456';
$orderPO = '123456-A';
$dbh = new PDO("mysql:host=localhost;dbname=dbname", 'someuser', 'somepass');
$stm = $dbh->prepare("insert into some_table (order_number, order_po) VALUES (:order_number, :order_po)");
$stm->bindvalue(':order_number', $orderNum, PDO::PARAM_STR);
$stm->bindvalue(':order_po', $orderPO, PDO::PARAM_STR);
$stm->execute();
print_r($stm);
print_r($dbh);
$arr = $stm->errorInfo();
print_r($arr);
$stm->closeCursor();
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}