Can anybody see why this is not inputting into my database..
I did have it working, but now i got the error on mysql A form on this field has more than 1000 fields, but none of them do....
here is the prep statment
$db = new PDO("mysql:host=localhost;dbname=class2", 'root', '');
$query="INSERT INTO `testdata` (`1st name`, `2nd name`, `title`, `info`, `location`, `phone`, `postcode`, `image`, `image2`, `image3`, `image4`, `image5`, `price`, `catagory`, `cond`, `delivery`, `email`, `username`, `youtubevideo`, `paypal`, `facebook`, `twitter`, `feedbackscore`)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
$stat=$db->prepare($query);
$stat->execute(array("$firstname","$lastname","$sellingtitle","$sellinginfo","$town","$phone1","$postcode","$i0url","$i1url","$i2url","$i3url","$i4url","$price","$catagory","$cond","$delivery","","$sellername","$youtubeurl","$paypal","$facebook","$twitter","feedbackscore"));
Your PDO is not prepared correctly.
$database = new PDO("mysql:host=localhost;dbname=class2", 'root', '');
$query = "UPDATE users SET first_name = :first_name, last_name = :last_name
WHERE user_id = :user_id";
$update = $database->prepare($query);
$update->execute([
':first_name' => $_POST['firstname'],
':last_name' => $_POST['lastname'],
':user_id' => $_SESSION['user_id']
]);
$update->fetch();
With PDO you define the keys of the values in the prepare string like :first_name.
So then in the execute function's array, you define the values of these keys.
Hope it helps.
Related
I'm trying to convert mysqli to PDO but I'm getting one string empty, all the rest is fine.
My code mysqli:
$sql="SELECT uid FROM userprofile WHERE `name` = '$_POST[name]'";
$result=mysqli_query($con,$sql);
if($result&&mysqli_num_rows($result)>0){
$dwID = mysqli_fetch_array($result);
$time=time().'000';
$time1=time();
switch($_POST['t3']){
case ''.$mail_9.'':{
$b=bin2hex($_POST['type1'].','.$_POST['ts1'].','.$_POST['ts2']);
$b1=($_POST['type1'].','.$_POST['ts1'].','.$_POST['ts2']);
mysqli_query($con,"INSERT INTO mail (uid, toUser, title, contents, rewardId, itemIdFlag, status, type, rewardStatus, saveFlag, createTime, reply) VALUES (md5($time), '$dwID[0]','$_POST[titlegift]','$_POST[titlegift]', 0x$b,'1','0','13','0','0','$time','0')")or die('2');
And now I'm trying to converto to PDO like this:
$sql = "SELECT * from userprofile where `uid`='$_POST[name]'";
$query = $dbh2 -> prepare($sql);
$query->execute();
$result=$query->fetch(PDO::FETCH_OBJ);
$cnt=1;
$uid = $query->$result;
$time = time().'000';
$gifttitle = $_POST['gifttitle'];
$b = bin2hex($_POST['type1'].','.$_POST['itemid'].','.$_POST['quantity']);
$sql1 = "INSERT INTO mail (uid, toUser, title, contents, rewardId, itemIdFlag, `status`, `type`, rewardStatus, saveFlag, creatTime, reply) VALUES (md5($time), '$uid', '$_POST[gifttitle]', '$_POST[gifttitle]', 0x$b, '1', '0', '13', '0', '0', '$time', '0')";
$query = $dbh2 -> prepare($sql1);
$query -> execute();
But when I run var_dump (SQL) it add all the fields and only $uid is empty.
Sorry for the code mysqli I know it is a messy.
This is wrong:
$uid = $query->$result;
$result is an object containing the row that was fetched from the table. It's not the name of a property of the $query object.
That should be:
$uid = $result->uid;
You should also use a prepared statement rather than substituting variables into the SQL string.
$sql1 = "INSERT INTO mail (uid, toUser, title, contents, rewardId, itemIdFlag, `status`,
`type`, rewardStatus, saveFlag, creatTime, reply)
VALUES (md5(:time), :uid, :gifttitle, :gifttitle, UNHEX(:rewardid), '1', '0',
'13', '0', '0', :time, '0')";
$query = $dbh2 -> prepare($sql1);
$query->bindParam(':time', $time);
$query->bindParam(':uid', $uid);
$query->bindParam(':rewardid', $b);
$query->bindParam(':gifttitle', $_POST['gifttitle']);
$query->execute();
I am trying to execute the following query using a PDO Prepared Statement, but when I call $query->fetch(); it throws an exception SQLSTATE[HY000]: General Error.
This is the PHP code (note that class Database - or the variable $db in code - is just a simple wrapper for the class PDO thus all PDO calls have to be done using $db->pdo->{some PDO function}();):
$db = new Database(); //Create a new object of type Database establishing a connection to the MySQL database
$query = $db->pdo->prepare("INSERT INTO `orders` (`order_type`, `item`, `amount`, `price`, `price_btc`, `status`, `timestamp`, `placed_by`, `secret`, `first_name`, `last_name`, `address_1`, `address_2`, `city`, `zip_code`, `country`, `state`, `phone_number`)
VALUES(:order_type, :item, :amount, :price, :price_btc, :status, :timestamp, :placed_by, :secret, :first_name, :last_name, :address_1, :address_2, :city, :zip_code, :country, :state, :phone_number);
SELECT * FROM `orders` WHERE `ID`=LAST_INSERT_ID();"); //Prepare the two queries to be executed
/*HERE IS SOME CODE TO BIND PLACEHOLDERS TO SOME VALUES*/
if(!$query->execute()){
error(); //Handle the error and terminate execution
}
if($query->rowCount() != 1){
error(); //Handle the error and terminate execution
}
$query->setFetchMode(PDO::FETCH_ASSOC);
$order = $query->fetch(); //THIS IS WHERE THE EXCEPTION IS THROWN!
I have tried executing the query manually through PHPMyAdmin and it worked fine. I've also read that PDO doesn't support multiple queries in the same statement, but shouldn't it then throw and exception when running $query->execute();?
Also, $query->rowCount(); DOES return 1, but when I try to fetch the result it throws a general error exception.
I have tried a lot of other things like replacing the SELECT statement with a SELECT LAST_INSERT_ID();, but nothing seems to work.
I would appreciate your help!
Run your first query which is the insert then after success on that one get the last insertid then use the id on your next query.. Eg.
<?php
try {
$db = new Database(); //Create a new object of type Database establishing a connection to the MySQL database
$query = $db->prepare("INSERT INTO orders (order_type`, `item`, `amount`, `price`, `price_btc`, `status`, `timestamp`, `placed_by`, `secret`, `first_name`, `last_name`, `address_1`, `address_2`, `city`, `zip_code`, `country`, `state`, `phone_number`) VALUES(:order_type, :item, :amount, :price, :price_btc, :status, :timestamp, :placed_by, :secret, :first_name, :last_name, :address_1, :address_2, :city, :zip_code, :country, :state, :phone_number)");
$query->execute(array( /* your values*/ ));
$lastId = $db->lastInsertId(); // fetch last insert id, after success.
$order = $db->prepare("SELECT * FROM `orders` WHERE `ID`=?");
$order->bindValue(1, $lastId);
$order->execute();
//Fetch your records and display.
}
catch (PDOException $e) {
echo "Error : " . $e->getMessage();
}
?>
I left some part of the codes like you did, but the important thing is to run the insert first then collect the last
You don't need a multiple statement.
So just run your queries one by one
$db = new Database(); //Create a new object of type Database establishing a connection to the MySQL database
$query = $db->pdo->prepare("INSERT INTO `orders` (`order_type`, `item`, `amount`, `price`, `price_btc`, `status`, `timestamp`, `placed_by`, `secret`, `first_name`, `last_name`, `address_1`, `address_2`, `city`, `zip_code`, `country`, `state`, `phone_number`)
VALUES(:order_type, :item, :amount, :price, :price_btc, :status, :timestamp, :placed_by, :secret, :first_name, :last_name, :address_1, :address_2, :city, :zip_code, :country, :state, :phone_number)"
); //Prepare the first query
/*HERE IS SOME CODE TO BIND PLACEHOLDERS TO SOME VALUES*/
$query->execute();
$order = $db->pdo->query("SELECT * FROM `orders` WHERE `ID`=LAST_INSERT_ID()")->fetch(PDO::FETCH_ASSOC);
You would be correct in that PDO (and I believe any PHP method?) does not allow for multiple queries in a single by default. There are some workarounds which you can read about more, such as:
PDO support for multiple queries (PDO_MYSQL, PDO_MYSQLND)
but they do increase the risk of SQL injection so it is ill-advised.
I'm making a simple sign up/in form for a school assignment.
for some reason I can't get it to create a new column in my current table.
All of the information for the $_Get is coming up properly. I imagine its a syntax error i'm not seeing. Any help would be great. Thank you.
if ( $_GET['action'] == "create" )
{
print('test');
// -----------------------
// PERFORM DATABASE UPDATE
$fn = $_GET['fn'];
$ln = $_GET['ln'];
$id = $_GET['id'];
$user = $_GET['user'];
$tel = $_GET['tel_num'];
$email = $_GET['email'];
$bday = $_GET['birthday'];
$password = $_GET['password'];
$address = $_GET['address'];
print('test1');
mysql_select_db("advweb2");
$sql="INSERT INTO `account` (`user`, `password` , `email` , `first_name` , `last_name` , `address` , `tel_num` , `birthday`)
VALUES ('$user', '$password', '$email', '$fn', '$ln', '$address', '$tel', '$bday')";
print_r($sql);
print("<div style='color:green'>update successful</div>");
// -----------------------
$action = "signin";
}
You need to execute the query.
You should be using MySQLi or PDO as detailed here as mysql_query is deprecated.
Example with mysqli:
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$stmt = $mysqli->prepare(
"INSERT INTO `account` (`user`, `password` , `email` , `first_name` , `last_name` , `address` , `tel_num` , `birthday`)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
);
$stmt->bind_param('ssssssss', $user, $password, $email, $fn, $ln, $address, $tel, $bday);
$stmt->execute();
/* ... */
$stmt->close()
?>
You need to make sure you clean your $_GET variables before inserting into the database to prevent SQL injection. A good read: how to prevent SQL injection.
Please don't use mysql_query, switch to mysqli or PDO instead.
$dbh = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);
$name = 'one';
$value = 1;
$stmt->execute();
$dbh = null;
Use Mysqli or PDO as explained by others but if you insist execute your query like this:
$sql=mysql_query("INSERT INTO `account` (`user`, `password` , `email` , `first_name` , `last_name` , `address` , `tel_num` , `birthday`)
VALUES ('$user', '$password', '$email', '$fn', '$ln', '$address', '$tel', '$bday')");
Because You prepared query and assigned it to the variable but for missed to execute it.
function save($gmt, $name, $address, $phone, $remark)
{
$query= "INSERT INTO `user` (`gmt`, `name`, `address`, `phone`, `remark`) VALUES ('$gmt', '$name', '$address', '$phone', '$remark')";
mysql_query($query);
}
Here, address, phone, and remark can be NULL. I need it to save NULL whenever the variable is set to NULL and the column is nullable, instead of inserting an empty string.
How can I insert NULL value into the database using PHP?
This is PHP solution, but you have to use mysqli because mysql deprecated, please read more about mysqli.
Also, you must consider SQL injection
function save($gmt, $name, $address, $phone, $remark)
{
if(empty($phone)){
$phone = 'NULL';
}else{
$phone = "'".$phone."'";
}
if(empty($remark)){
$remark = 'NULL';
}else{
$remark = "'".$remark."'";
}
$query= "INSERT INTO `user` (`gmt`, `name`, `address`, `phone`, `remark`) VALUES ('$gmt', '$name', '$address', $phone, $remark)";
mysql_query($query);
}
//tests
save("a", "b", "c", "", "")."<br>";
save("a", "b", "c", "d", "")."<br>";
save("a", "b", "c", "d", "e")."<br>";
/*
INSERT INTO `user` (`gmt`, `name`, `address`, `phone`, `remark`) VALUES ('a', 'b', 'c', NULL, NULL)
INSERT INTO `user` (`gmt`, `name`, `address`, `phone`, `remark`) VALUES ('a', 'b', 'c', 'd', NULL)
INSERT INTO `user` (`gmt`, `name`, `address`, `phone`, `remark`) VALUES ('a', 'b', 'c', 'd', 'e')
*/
?>
DEMO
Try switching to prepared statements (which as a bonus is less prone to SQL injections).
function save($gmt, $name, $address, $phone, $remark)
{
if(!isset($phone) || empty($phone)) { $phone = null; }
if(!isset($remark) || empty($remark) { $remark = null; }
$db = new PDO(...);
$stmt = $db->prepare("INSERT INTO `user` (`gmt`, `name`, `address`, `phone`, `remark`) VALUES (:gmt, :name, :address, :phone, :remark)");
$stmt->bindValue("gmt", $gmt, PDO::PARAM_STR);
$stmt->bindValue("name", $name, PDO::PARAM_STR);
$stmt->bindValue("address", $address, PDO::PARAM_STR);
$stmt->bindValue("phone", $phone, PDO::PARAM_STR);
$stmt->bindValue("remark", $remark, PDO::PARAM_STR);
$stmt->execute();
}
This will handle the null values correctly in MySQL
PHP doesn't print NULL - it is just an empty string. So in your example you will try to insert '', which in SQL again is an empty string.
You have to use NULL (without quotes).
And the best practice to achieve that is to use an ORM or a PHP framework with a database abstraction layer which does this for you.
Using ternary operator, you can also use this
$add = ($address == '' ? NULL : $address);
$phn = ($phone == '' ? NULL : $phone);
$rmk = ($remark == '' ? NULL : $remark);
fields can be NULL
-> qtd_aulas_previstas
-> qtd_aulas_dadas
$qtd_aulas_previstas = ( empty($qtd_aulas_previstas) ? 'NULL' : "'".$qtd_aulas_previstas."'");
$qtd_aulas_dadas = ( empty($qtd_aulas_dadas) ? 'NULL' : "'".$qtd_aulas_dadas."'");
//insere os dados na tabela
$inserir_tb = mysqli_query($conexao, "INSERT INTO tb_turma_bimestre VALUES('', '$cod_turma', '$cod_bimestre', $qtd_aulas_previstas, $qtd_aulas_dadas, '$data_abertura', '$data_encerramento', '$date_time', '$nome_login')")or die("Error2: " .mysqli_error($conexao));
I'm guessing I'm missing something, but I can't seem to get this statement to work. When I load it into the page I get the white screen of death.
Here is what I'm trying to get to run
$statement = $db-> prepare("INSERT INTO `simplyaccomplished`.`blog_comment` (`ID`, `comment`, `date`, `ip_address`, `valid`, `name`, `blogcomment_ID`) VALUES (NULL, ?, NOW(), ?, 0, ?, ? );");
$statement -> bind_param("sssi",$comment, $ipaddress, $name , $comment_id);
$statement -> execute($statement);
$statement -> close();
The weird thing is this runs perfectly
$query = ("INSERT INTO `simplyaccomplished`.`blog_comment` (`ID`, `comment`, `date`, `ip_address`, `valid`, `name`, `blogcomment_ID`) VALUES (NULL,'$comment' , NOW(), '$ipaddress', '0', '$name', '$comment_id');");
$result =$db->query($query);
If someone could tell me where I'm going wrong I would greatly appreciate it!
The PDO method you're looking for is named bindParam, not bind_param :)
Try mysqli method,
$statement = $db-> prepare("INSERT INTO `simplyaccomplished`.`blog_comment` (`ID`,
`comment`, `date`, `ip_address`, `valid`, `name`, `blogcomment_ID`)
VALUES (?, ?, ?, ?,?, ?, ?)");
$statement -> bind_param("ssssisi",
null,$comment,NOW(),$ipaddress, 0,$name , $comment_id);
Take a look at PDO and MySqlI.