How to put an array to DB (php, pdo)? - php

Need your help. Got some problems with putting an array's data to DB via php pdo. I'm amateur frond-end dev. that's quite far from backend, so there are no people except you to help me! In the DB table I've got some columns, among others "myActions" - need to put all the data from my inputs with the names name="action[]" to this column row by row.
In html code I have inputs' names like that:
<div id="field">
<input autocomplete="off" class="input form-control" id="field1" name="action[]" type="text" placeholder="Type something" data-items="8"/>
<button id="b1" class="btn add-more" type="button">+</button>
</div>
In php file :
<?php
$incident_number = $_POST['incident_number'];
$incident_type = $_POST['incident_type'];
$incident_subject = $_POST['incident_subject'];
$incident_time = $_POST['incident_time'];
$status = $_POST['status'];
$wasdone = $_POST['action'];
try {
/*** connect to SQLite database ***/
$dbh = new PDO("sqlite:myDB2");
/*** echo a message saying we have connected ***/
//echo 'Connected to database<br />';
/*** The SQL SELECT statement ***/
$Log = date(DATE_RFC2822)." Creation".PHP_EOL;
//echo $Log;
$sql = "INSERT INTO myData
(incident_number,incident_type,incident_subject,incident_time,status) values
(:incident_number,:incident_type,:incident_subject,:incident_time,:status);"
$query = $dbh->prepare($sql);
$query->bindParam(':incident_number', $incident_number);
$query->bindParam(':incident_type', $incident_type);
$query->bindParam(':incident_subject', $incident_subject);
$query->bindParam(':incident_time', $incident_time);
$query->bindParam(':status', $status);
//$query->bindParam(':Log', $Log, PDO::PARAM_STR);
$query->execute();
//$query->execute(array(':NameImp'=>$NameImp));
// Close file db connection
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
try {
/*** connect to SQLite database ***/
$dbh = new PDO("sqlite:myDB2");
/*** echo a message saying we have connected ***/
//echo 'Connected to database<br />';
/*** The SQL SELECT statement ***/
$Log = date(DATE_RFC2822)." Creation".PHP_EOL;
//echo $Log;
$sql = "INSERT INTO myActions (action) values (:wasdone);";
foreach ($wasdone as $key => &$value) { //pass $value as a reference to the array item
$query->bindParam($key, $value); // bind the variable to the statement
}
//$query->bindParam(':Log', $Log, PDO::PARAM_STR);
$query->execute();
//$query->execute(array(':NameImp'=>$NameImp));
// Close file db connection
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>

You could use PHP's implode() function which joins the elements of an array into a single string, delimited by a custom substring.
You can later use explode() to turn your string back into a workable array when you query it from the database.
Note: while this is a quick solution that could work for your use case, if the arrays in the dataset become too large or your project increases in complexity, you should look into data normalization and make additional tables for your actions array elements as good data management practice.

Related

php function with mysqli

This is my fonction.php :
<?php
function connect(){
$servername = "localhost";
$username = "xxx";
$password = "xxxx";
$dbname = "xxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
}
?>
But it does not works with my code when I want to call this function :
<?php
include("fonctions.php");
?>
<html>
<form name="inscription" method="post" action="form.php">
xxx : <input type="text" name="xxx"/> <br/>
xxx: <input type="text" name="xxx"<br/>
<input type="submit" name="valider" value="OK"/>
</form>
<?php
if (isset ($_POST['valider'])){
$titre=$_POST['xxx'];
$auteur=$_POST['xxx'];
connect();
$sql = 'INSERT INTO xxx (`xxx`, `xxx`) VALUES("'.$xxx.'","'.$xxx.'")';
}
?>
</body>
</html>
Before I was using mysql_connect and it was more simple, my fonction was like this :
<?php
function connect(){
$base = mysql_connect ('localhost', 'root', '');
mysql_select_db ('MaBase', $base) ;
}
?>
What is the best way to create a good include with my mysql params ? THanks all for any help.
Include obligatory statement about using PDO or mysqli and prepared statements when using variables in your SQL statements...
You aren't passing your function a SQL statement to use, or otherwise defining $sql in the function.
function connect($sql){
For defining it, and then to call it
$sql_statement="select foo from bar where bee=1";
$res=connect($sql_statement);
You'll also need your function to return some sort of value.
What I've done is create a generic function that takes a SQL statement and an array of positional parameters, the function then uses PDO and prepared statement to execute the query using the parameters, and then returns an array with appropriate data. $ret[0] is a bool to indicate success, if false then [2..N] contain(s) error message(s), if true then [2..N] contains returned record set for a select, number of rows affected for update, delete, and last_insert_id for an insert statement (detected by using regular expression on the query string)
This is written once, and require_once()'d all across 15 web apps for the college I work at.
To this you i suggest you to use OOP approach i am just suggesting this with my own way you can try it with different ways no problem in my answer i am using two class first class does all the database connection and mysqli real escape conversion and staff other class is query class it's handle all the querying staff
database.class.php
//databaseconnection
class DatabaseConnections{
function connect($databaseNaem){
try{
return $connection=mysqli_connect("localhost","user","password",'database');
}catch(Exception $e){
echo 'Message:'.$e->getMessage();
}
}
function CloseConnection($dataObject){
if(mysqli_close($dataObject)){
return 1;
}else{
echo "coudn't Close the Database Connection";
}
}
function convert($connection , $vari){
return mysqli_real_escape_string($connection,$vari);
}
}
//queryclass
class Query{
function queryNoresult($stmt){
if($stmt->execute()){
return 1;
}
}
function queryNumOfRows($stmt){
$stmt->execute();
$result = $stmt->get_result();
return mysqli_num_rows($result);
}
function QueryResult($stmt){
$stmt->execute();
$result = $stmt->get_result();
return $result;
}
function illcallothers($stmt,$callto){
if($callto == 1){
return $this->queryNoresult($stmt);
}if ($callto==2) {
return $this->queryNumOfRows($stmt);
}
if($callto == 3){
return $this->QueryResult($stmt);
}
}
}
as you can see at the end i have created a function call illcallothers and this function takes what you want do with your query it's takes only 2 parameters
Created statement
The function number
there 3 option in this
if you call $query->illcallothers($stmt,1) this call the function
only for execute best for delete and insert because it's return 1 if
it's success
if you call $query->illcallothers($stmt,2) this call the function that return number of rows that returned nothing else best for check it data is availbe before using while
if you call $query->illcallothers($stmt,3) this will return result set from your query
Now lets go to your problem execution
//first you have to require the database file
require_once('database.class.php');
//Then you have to create object from them
$mymainObj = new DatabaseConnections();//obj from database
$connetion = $mymainObj->connect('databasename');//this will return a connection Object
$stmt = $connection->stmt_init(); //then the statement you need the connection object to this
$query = new Query();//object from the query class
//i am not going to put form part in here it will get messy
$titre= $mymainObj->convert($connection,$_POST['xxx']);//calling mysqli realescape funciton in databaseconnection
$auteur=$mymainObj->convert($connection,$_POST['xxx']);
//now you have create the sql
$sql = 'INSERT INTO xxx (`xxx`, `xxx`) VALUES(?,?)';//when using stmt this how we tell mysql that we have this much parameters and then we pass them after preparing
if($stmt->prepare($sql)){
$stmt->bind_param('ss',$title,$author);
if($query->illcallothers($stmt,1)){
echo "Query Success";
}
}
It should be,
<?php
function connect(){
$servername = "localhost";
$username = "xxx";
$password = "xxxx";
$dbname = "xxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
return false;
}else{
return $conn;
}
}
?>
Your query should be,
<?php
if (isset($_POST['valider'])){
$titre=$_POST['xxx'];
$auteur=$_POST['xxx'];
$connection = connect();
if($connection != false){
$sql = 'INSERT INTO xxx (`xxx`, `xxx`) VALUES("'.$xxx.'","'.$xxx.'")';
$result=$connection->query($sql);
if($result){
echo "done";
}else{
echo "faild";
}
}
}
?>
You should take a tour/learn the basics of OOP
It seems like all the above answers missed that you have two variables with the same name:
$sql = 'INSERT INTO xxx (`xxx`, `xxx`) VALUES("'.$xxx.'","'.$xxx.'")';
Both are called $xxx
IF YOU thought that the names of your public variables shoulden't be shown publicly here, and changed them to 'xxx', then please edit your question and don't change them to the same name (e.g change to $name and $password for example)

Want to fetch data from database based on dropdown list selection using php [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 6 years ago.
I have a php file and mysql database with fields named planname and price,and i want a dropdown list of all the planname from database and according to the planname the price of particular planname should be shown in text box below.
Here is my php file;
<?php
$servername = xxxxxxx;
$username = xxxxxx;
$password = xxxxxx";
try {
$conn = new PDO("mysql:host=$servername;dbname=vnet", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
$sql="SELECT id,planname,price FROM plan";
/* You can add order by clause to the sql statement if the names are to be displayed in alphabetical order */
echo "<select name=planname value=''>Plan Name</option>"; // list box select command
foreach ($conn->query($sql) as $row){//Array or records stored in $row
echo "<option value=$row[id]>$row[planname]</option>";
/* Option values are added by looping through the array */
}
echo "</select>";// Closing of list box
if(isset($_REQUEST['planname'])){
// connection should be on this page
$sql = mysql_query("select price from plan where planname =".$_REQUEST['planname']);
$res = mysql_fetch_assoc($sql);
echo $res['price'];die;
}
echo '<input type="text3" name="price[]" id="price" value="', $row['price'], '" disabled="disabled" />';
?>
I got the list in dropdown but not able to get price according to planname dynamically.can anyone help me out of this?
$sql = mysql_query("select price from plan where planname =".$_REQUEST['planname']);
You are searching in the column planname, but by defining the <option>'s as
echo "<option value=$row[id]>$row[planname]</option>";
You are sending the id as value.
So your query should be:
$sql = mysql_query("select price from plan where id =".$_REQUEST['planname']);
// better: pdos prepared statements
$stmt = $conn->prepare("select sub_id from sub where sub_id = ?");
$stmt->execute(array($_GET['planname']));
Also read the other comments. You are mixing the mysql_* api and PDO, you should only use PDO. Why shouldn't I use mysql_* functions in PHP? And see this when you are at it: How can I prevent SQL injection in PHP?
The structure of your code will make maintainance really troublesome, you should first do all the logical work, gather all the data and then display your html and the data in the next step.
How to do implement your plan
You need / might want to use two different scripts, to get your dynamic ui. (You could use the same file but things could get messy and it is better to split tasks)
1. The frontend:
As previously said, you should structure code in a meaningful order. You can see I am first setting up the database connection, then doing the querying and already fetching of the result. This way I already have all the data needed before I start to output other stuff (if something goes wrong as in I notice there is something invalid with the data/whatever I could still redirect to another page as there has not been a header sent).
To start the output, I added some basic HTML structure to your script, don't know if you already had it, at least it is not in your snippet.
So I added header and body, in the header is the javascript code which will execute the request to the backend and receive the response to act accordingly.
Note:
I am not really familiar with vanilla javascript, so I just followed a
tutorial http://www.w3schools.com/ajax/ajax_php.asp
I think you should check out jQuery if you haven't yet, it makes things really really easy.
Other than that I reduced some noise and used other code formatting than you, basically I don't like to use echo to output my HTML as some IDEs are not able to do syntax highlighting when done so.
I also added a <p></p> in which the error message can be displayed to the user, if something in the backend goes wrong.
<?php
$servername = 'xxxxxxx';
$username = 'xxxxxx';
$password = 'xxxxxx';
try {
$conn = new PDO("mysql:host=$servername;dbname=vnet", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
trigger_error("Connection failed: " . $e->getMessage());
}
$selectPlans = "SELECT id, planname, price FROM plan";
$rows = $conn->query($selectPlans)->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function getPrice(id){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
var jsonObj = JSON.parse(xmlhttp.responseText);
if(jsonObj.success === true){
document.getElementById("price").value = jsonObj.price;
}else{
document.getElementById("price").innerHTML = jsonObj.message;
}
}
};
xmlhttp.open("GET", "ajax.php?id=" + id, true);
xmlhttp.send();
}
</script>
</head>
<body>
<select name="planname" id="plannameSelect" onchange="getPrice(this.value)">
<?php foreach ($rows as $row): ?>
<option value="<?= $row['id'] ?>"><?= $row['planname'] ?></option>
<?php endforeach; ?>
</select>
<input type="text" name="price[]" value="" id="price" disabled="disabled">
<p id="error"></p>
</body>
2. The backend: (in this case called ajax.php)
A simple piece of code, nothing special to do.
First step: validating the input. In this case, I simply check if there is an id in the $_GET-Array. I used json_encode() on an array in which I tell the frontend whether the operation was successfull or not. The first case of failure would be if there was no id.
Then connect to the database, ask for errors and if so return them immediately to the user (by using echo), again via the json_encoded array.
Prepare the statement for selecting the price of the id (I skipped the error check here, you might want to add it). Then execute it.
Check if it was successfull -> return the json_encoded array as success and with the price, or set success false again and return the array with an error message.
<?php
$servername = 'xxxxxxx';
$username = 'xxxxxx';
$password = 'xxxxxx';
if(!isset($_GET['id'])){
echo json_encode(array('success' => false, 'price' => '', 'message' => 'no id given'));
exit;
}
try {
$conn = new PDO("mysql:host=$servername;dbname=vnet", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
trigger_error("Connection failed: " . $e->getMessage());
echo json_encode(array('success' => false, 'price' => '', 'message' => 'shit happened' . $e->getMessage()));
exit;
}
$stmt = $conn->prepare("SELECT price FROM plan WHERE id = ?");
$stmt->execute(array($_GET['id']));
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if($result === false){
trigger_error('Query failed: ' . $conn->errorInfo());
echo json_encode(array('success' => false, 'price' => '', 'message' => 'shit happened'));
exit;
} else {
echo json_encode(array('success' => true, 'price' => $result['price'], 'message' => ''));
exit;
}

when adding a title that stores in database, create slug automatically

I have a basic insert record that inserts the data captured by a user into the database. It is a very simple form with a title, article and date. I want to create a slug entry as well though. So, if I type: this is a news title then I want it store that in the title column but also store, this-is-a-news-title in the slug column.
I'm using this which does work for creating the hyphens:
function create_url_slug($string){
$slug=preg_replace('/[^A-Za-z0-9-]+/', '-', $string);
return $slug;
}
And I have an insert like this:
$hostname_slugs = "localhost";
$database_slugs = "slugs";
$username_slugs = "root";
$password_slugs = "root";
try{
$conn = new PDO('mysql:host=$hostname_slugs;dbname=$database_slugs', '$username_slugs', '$password_slugs');
$slug = create_url_slug($_POST['newsarticle']);
//we'll use a prepared statement, which will sanitize our strings for us!
$stmt = $conn->prepare('INSERT INTO news (articledate, newsheadline, headlineslug, newsarticle) VALUES (:articledate, :newsheadline, :headlineslug, :newsarticle)');
$stmt->bindParam(':articledate', $_POST['articledate']);
$stmt->bindParam(':newsheadline', $_POST['newsheadline']);
$stmt->bindParam(':headlineslug', $_POST['headlineslug']);
$stmt->bindParam(':newsarticle', $slug);
$stmt->execute();
echo 'Successfully saved article!';
} catch(PDOException $e){
echo "There was an error: ".$e->getMessage();
exit();
}
But I am not sure how to achieve what I want.
Looks like you have the headline slug, which is what you want anyway. right? So let's just wrap that in our function create_url_slug()
create_url_slug(GetSQLValueString($_POST['headlineslug'], "text"))
Should be all you need.
Let's do it using PDO as the gentlemen above suggested!
try{
$conn = new PDO('mysql:host=host;dbname=yourdatabasename', 'user', 'pass');
$slug = create_url_slug($_POST['newsarticle']);
//we'll use a prepared statement, which will sanitize our strings for us!
$stmt = $conn->prepare('INSERT INTO news (articledate, newsheadline, headlineslug, newsarticle) VALUES (:articledate, :newsheadline, :headlineslug, :newsarticle)');
$stmt->bindParam(':articledate', $_POST['articledate']);
$stmt->bindParam(':newsheadline', $_POST['newsheadline']);
$stmt->bindParam(':headlineslug', $_POST['headlineslug']);
$stmt->bindParam(':newsarticle', $slug);
$stmt->execute();
echo 'Successfully saved article!';
} catch(PDOException $e){
echo "There was an error: ".$e->getMessage();
exit();
}
Resources
PDO connection
PDO Prepared Statements

Update query not working using PDO

I tried updating my data like so but it doesn't work
<?php
require("config.inc.php");//this piece of code us for authentication and it works fine.
if(!empty($_POST))
{
/**
the values below in the POST are valid not empty values
**/
$shell = $_POST['shell'];
$reporter = $_POST['reporter'];
//query
$query = "UPDATE `shellingdb`
SET `likes` = `likes` + 1
WHERE `shell` = :shell AND `reporter` = :reporter";
try {
$query_params = array(':shell' => $_POST['shell'], ':reporter' => $_POST['reporter']);//Updates likes
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
$affected = $stmt->rowCount();//counts the number of affected rows during the update query
if($affected > 0)
{
$response["success"] = 1;
$response["message"] = "Updated! this number of rows were affected".$affected;
echo json_encode($response);
}else
{
$response["success"] = 2;
$response["message"] = "Not Updated! huh!".$affected;
echo json_encode($response);
}
}
catch (Exception $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!".$ex->getMessage();
die(json_encode($response));
}
}
?>
the config.inc.php
<?php
// These variables define the connection information for your MySQL database
$username = "xmnj3jh0jhtheu_14265914";
$password = "jhikjskjiavethew";
$host = "sqlkjnlkkjlk101.x3kuhiu0lkj.us";
$dbname = "x3lnklj0u_1426jbkb5914_gbabbjkhjajhlert";
// UTF-8 is a character encoding scheme that allows you to conveniently store
// a wide varienty of special characters, like � or �, in your database.
// By passing the following $options array to the database connection code we
// are telling the MySQL server that we want to communicate with it using UTF-8
// See Wikipedia for more information on UTF-8:
// http://en.wikipedia.org/wiki/UTF-8
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
// A try/catch statement is a common method of error handling in object oriented code.
// First, PHP executes the code within the try block. If at any time it encounters an
// error while executing that code, it stops immediately and jumps down to the
// catch block. For more detailed information on exceptions and try/catch blocks:
// http://us2.php.net/manual/en/language.exceptions.php
try
{
// This statement opens a connection to your database using the PDO library
// PDO is designed to provide a flexible interface between PHP and many
// different types of database servers. For more information on PDO:
// http://us2.php.net/manual/en/class.pdo.php
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}
catch(PDOException $ex)
{
// If an error occurs while opening a connection to your database, it will
// be trapped here. The script will output an error and stop executing.
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code
// (like your database username and password).
die("Failed to connect to the database: " . $ex->getMessage());
}
// This statement configures PDO to throw an exception when it encounters
// an error. This allows us to use try/catch blocks to trap database errors.
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// This statement configures PDO to return database rows from your database using an associative
// array. This means the array will have string indexes, where the string value
// represents the name of the column in your database.
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
// This block of code is used to undo magic quotes. Magic quotes are a terrible
// feature that was removed from PHP as of PHP 5.4. However, older installations
// of PHP may still have magic quotes enabled and this code is necessary to
// prevent them from causing problems. For more information on magic quotes:
// http://php.net/manual/en/security.magicquotes.php
if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
{
function undo_magic_quotes_gpc(&$array)
{
foreach($array as &$value)
{
if(is_array($value))
{
undo_magic_quotes_gpc($value);
}
else
{
$value = stripslashes($value);
}
}
}
undo_magic_quotes_gpc($_POST);
undo_magic_quotes_gpc($_GET);
undo_magic_quotes_gpc($_COOKIE);
}
// This tells the web browser that your content is encoded using UTF-8
// and that it should submit content back to you using UTF-8
header('Content-Type: text/html; charset=utf-8');
// This initializes a session. Sessions are used to store information about
// a visitor from one web page visit to the next. Unlike a cookie, the information is
// stored on the server-side and cannot be modified by the visitor. However,
// note that in most cases sessions do still use cookies and require the visitor
// to have cookies enabled. For more information about sessions:
// http://us.php.net/manual/en/book.session.php
session_start();
// Note that it is a good practice to NOT end your PHP files with a closing PHP tag.
// This prevents trailing newlines on the file from being included in your output,
// which can cause problems with redirecting users.
?>
don't know what's wrong and it gives no error it goes into the else statement, meaning the values were not updated. i tried the same code in sqlfiddle and it works but not in my PhpMyAdmin.
I know the updated value is supposed to be passed into the $query_params but am incrementing the value of likes each time it is run, and am not sure how to do that in the $query_params unless i use a seperate query to get the numberof likes and then increament it but that could be costly.
Query without PDO still it does not work this time it give update unsuccessful
<?php
$username = "x3jbhiukhkj0u426jbhjnbvh591mbhb4";
$password = "savjiuejbiuhilkmthljiew";
$host = "sqlnjhbjhnkjjjhbj";
$dbname = "x3hjbh0ukjioiuhgbjhvhgvh";
$shell = "Rustig";
$reporter = "davies";
//query
$query = "UPDATE `shellingdb`
SET `favs` = 1
WHERE `shell` = 'Rustig'";
$link = mysql_connect($host, $username, $password);
if (!$link)
{
die('Could not connect: ' . mysql_error());
}else
{
echo 'Connected successfully';
$db_selected = mysql_select_db($dbname, $link);
if (!$db_selected)
{
die ('Can\'t use foo : ' . mysql_error());
}else
{
echo 'Connected to database successfully';
if(empty($_POST))
{
$retval = mysql_query( $query, $link )or die(mysql_error($link));;
if(! $retval )
{
die('Could not query database: ' . mysql_error());
}else
{
if(mysql_affected_rows() > 0)
{
echo "Updated data successfully\n";
}else
{
//echo "shell=".$shell." reporter=".$reporter';
echo "Updated data Unsuccessfully\n";
}
}
}
}
}
mysql_close($link);
?>
The below is the output of the PDOStatement::debugDumpParams(); for the first php syntax
SQL: [124] UPDATE shellingdb SET likes = likes + 1 WHERE shell = :shell AND reporter >= :reporter Params: 2 Key: Name: [6] :shell paramno=-1 name=[6] ":shell" is_param=1 param_type=2 Key: Name: [9] :reporter paramno=-1 name=[9] ":reporter" is_param=1 param_type=2
I used bindParam. bindParam is a method on PDOStatement.
Try:
<?php
require("config.inc.php");//this piece of code us for authentication and it works fine.
if(isset($_POST))
{
/**
the values below in the POST are valid not empty values
**/
$shell = $_POST['shell'];
$reporter = $_POST['reporter'];
//query
$query = "UPDATE `shellingdb`
SET `likes` = `likes` + 1
WHERE `shell` = :shell AND `reporter` = :reporter";
try {
$stmt = $db->prepare($query);
$stmt->bindParam(":shell", $shell);
$stmt->bindParam(":reporter", $reporter);
$stmt->execute();
$affected = $stmt->rowCount();//counts the number of affected rows during the update query
if($affected > 0)
{
$response["success"] = 1;
$response["message"] = "Updated! this number of rows were affected".$affected;
echo json_encode($response);
}else
{
$response["success"] = 2;
$response["message"] = "Not Updated! huh!".$affected;
echo json_encode($response);
}
}
catch (Exception $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!".$ex->getMessage();
die(json_encode($response));
}
}
?>
some how, after long hours of try and error(Brut Forcing) this finally worked
$query = "UPDATE `shellingdb` SET `likes`=`likes`+1 WHERE `shell` = :shell AND `reporter` = :reporter";
Thanks all those who tried to help. :)

Why won't this PHP script insert form data in MySQL db?

On form submit, I'm getting a blank page (insert.php) with no error and no success message.
This is the form:
<form action="insert.php" method="post">
Firstname: <input type="text" name="first_name" id="first_name" />
Lastname: <input type="text" name="lastname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
This is the script:
mysql_select_db("my_db", $con);
$stmt = $db->prepare('INSERT INTO my_table (first_name) VALUES (:first_name)');
$stmt->execute(':first_name', $first_name);
if (!mysql_query($stmt,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>
Youre trying to use 2 different MySQL interfaces at the same time. The mysql_* family of functions use the ext/mysql extension... The prepared statement stuff is PDO. You need to choose one or the other. Since PDO is really the way to go ill give you an example with that:
$db = new PDO($dsn, $user, $password);
try {
$stmt = $db->prepare('INSERT INTO my_table (first_name) VALUES (:first_name)');
if($stmt->execute(array(':first_name' => $first_name))) {
echo "1 record added";
}
} catch (PDOException $e) {
die('Error: ' . $e->getMessage());
}
The docs on the Mysql DSN (the first argument to the PDO constructor) can be found here.
You need to create a PDO object to be able to use prepared statements. Instead you have opened a connection with mysql_connect(). The two do not mix, and PDO is preferred between them as it is more easily secured through the use of prepared statements (among other reasons).
From the PDO docs:
// This establishes your connection using PDO.
// The PDO connection object is $db
/* Connect to an ODBC database using driver invocation */
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
try {
$db = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
Pass an associative array to execute(), rather than a list of arguments representing your placeholders. The
// Now that the PDO object is successfully created, prepare your statement
$stmt = $db->prepare('INSERT INTO my_table (first_name) VALUES (:first_name)');
// Arg to execute() should be an associative array
$stmt->execute(array(':first_name' => $first_name));
The following call to mysql_query() is unnecessary, as you have already executed the prepared statement with PDO.
// Don't do this
// mysql_select_db("my_db", $con);
// Or this...
//if (!mysql_query($stmt,$con))
//{
// die('Error: ' . mysql_error());
//}
// Or this...
// mysql_close($con)

Categories