PDO insert query not inserting data - php

I am trying to insert some data using PDO like below
$sql = "INSERT INTO tbl_category SET `category_title` = :cat_name , `category_alias` = :category_alias , `category_status`= :cat_status, `category_parent_id` = $parent_id, "
. "category_description = '$cat_description'";
$statement = $this->db->conn_id->prepare($sql);
$statement->bindParam(':cat_name', $cat_name, PDO::PARAM_STR);
$statement->bindParam(':cat_status', $cat_status, PDO::PARAM_STR);
$statement->bindParam(':category_alias', $category_alias, PDO::PARAM_STR);
$statement->bindParam(':parent_id', $parent_id, PDO::PARAM_INT);
if ($statement->execute()) {
echo "executed"; exit;
return $this->db->conn_id->lastInsertId();
} else {
echo "not executed"; exit;
}
it always shows me "Not Executed", but when I run the query manually, it works fine

The problem is that you are mixing bind and strings.
Bind
$parent_id
$cat_description
You have typos my friend. Clean up your code.
$sql = "INSERT INTO tbl_category SET `category_title` = :cat_name , `category_alias` = :category_alias , `category_status`= :cat_status, `category_parent_id` = :parent_id, category_description = :cat_description";

Related

getting session into each page

i want to insert into a table depending on the id of the session:
here the code in class.php:
public function activate($activation, $id,$change,$userID){
$stm1= $this->conn->prepare("INSERT INTO `log` (`date`,`change`) VALUES(CURRENT_TIMESTAMP(),'$change') WHERE `user_id` =$userID");
($stm1->execute());
$stmt = $this->conn->prepare("UPDATE `segments` SET `activation` = '$activation' WHERE `id` = '$id'")
or die($this->conn->error);
if ($stmt->execute()) {
$stmt->close();
$this->conn->close();
return TRUE;
}
}
at the top of the page i have this:
require './config.php';session_start();$userID = $_SESSION['user_id'];
and in action.php where the action go i have this:
$conn = new db_class();
$conn->activate($activation, $id,$change,$userID);
echo "Updated successfully.";
exit;
the first query insert into log is not working \ please help
This should be a comment but I don't have the rep yet...
Primarily, you don't do that type of insert with a WHERE clause. The insert will fail.
As an aside, that insert is open to sql injection. Bind your your parameters. Also, you should add error handling. If you had that, you would see the insert fails. Quick example (1 way...there are other ways...and I assumed $change is a string and $userId is an int...)
$sql = 'INSERT INTO log
SET `date` = CURRENT_TIMESTAMP(),
change = :change,
user_id = :user_id;';
$stmt = $this->conn->prepare( $sql );
$stmt->bindParam( ':change', $change, PDO::PARAM_STR );
$stmt->bindParam( ':user_id', $userID, PDO::PARAM_INT );
$result = $stmt->execute();
if (!$result) {
// failure -> get and handle the error
$error_array = $stmt->errorInfo();
} else {
// do something
}
The docs can help > pdo::execute, pdo::errorinfo

PHP: Is this safe?

I've made the following script that shows blogposts. $_MULT[0] shows 'blog', $_MULT[1] shows the ID of the blogpost.
I'm wondering:
1) Is this script safe for SQL injection?
2) What if I removed ctype_digit() ? Would it still be safe then?
<?php
error_reporting(E_ALL);
$db = new PDO('mysql:host=localhost;dbname=blablabla','blablabla','passwd');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
echo '<h2>Blog</h2>';
$iTijd = time();
$_MULT = explode("/", $_GET['p']);
if($_MULT[0] == 'blog' AND isset($_MULT[1]))
{
if(ctype_digit($_MULT[1]))
{
// query
$sql = "SELECT Titel, Post, Datum FROM Blog WHERE Id = :Id AND Status = :Status AND Datum < :Tijd LIMIT 1";
// prepare query
$stmt = $db->prepare($sql);
// bind values
$stmt->bindParam(':Id', $a=$_MULT[1], PDO::PARAM_INT);
$stmt->bindParam(':Status', $a='1', PDO::PARAM_INT);
$stmt->bindParam(':Tijd', $a=$iTijd, PDO::PARAM_INT);
// execute query
$stmt->execute();
// select data from db
$aRow = $stmt->fetch(PDO::FETCH_ASSOC);
// show blogpost
echo '<h4>'. $aRow['Titel'] .'</h4><br />';
$datum = $aRow['Datum'];
$datum = date("d-m-Y", $datum);
echo '<i>'. $datum.'</i> - '. $aRow['Post'];
}
else
{
echo "<h2>404 - Pagina niet gevonden</h2>";
}
}
else
{
// query
$sql = "SELECT Id, Titel FROM Blog WHERE Status = :Status AND Datum < :Tijd ORDER BY Id DESC LIMIT 10";
// prepare query
$stmt = $db->prepare($sql);
// bind values
$stmt->bindParam(':Status', $a='1', PDO::PARAM_INT);
$stmt->bindParam(':Tijd', $a=$iTijd, PDO::PARAM_INT);
// execute query
$stmt->execute();
echo '<br /><ul>';
// select data from db
while($aRow = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo '<h4><li>'. $aRow['Titel'] .'</li>
</h4>';
}
echo '</ul>';
if($stmt->rowCount() == 0)
{
echo '<p>Er zijn nog geen blogposts toegevoegd.</p>';
}
}
?>
Is that safe? And what should I do with this? Just leave it?
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
Strange code, but if You want use it change if statement to:
if($_MULT[0] == 'blog' && ! empty($_MULT[1])) { ... }
if(ctype_digit( (string) $_MULT[1])) { ... }

Fatal error: Call to a member function execute() on a non-object

$sql = "UPDATE Student ".
"SET score = $total_score ".
"WHERE student_id = $student_id";
$stmt = $mysqli->prepare($sql);
$stmt->execute();
$query = "SELECT faculty_id ".
"From Student s ".
"WHERE student_id =$student_id";
$state =$mysqli->prepare($query);
$state->execute();
$state->bind_result($faculty_id);
if ($state->fetch())
{if (strpos($faculty_id, '1') > 0) {
include ('./Registration_Step_3_Student.php');
} else
{
include ('./Registration_Step_3_Mentor.php');
}
}
So whenever i try to run my second query called $state, i get this error that states it cannot be execute. I am relatively new to SQL and PHP so any help would be appreciated. Thanks!
Since you are using mysqli you should learn how to bind properly, please read up on bind_Param
mysqli_stmt::prepare returns an false when failing, you should never execute the statement when it does:
$sql = "UPDATE Student SET score = ? WHERE student_id = ?";
$stmt = $mysqli->prepare($sql);
if($stmt){
$stmt->bind_param('si', $total_score, $student_id);
if($stmt->execute()){
$query = "SELECT faculty_id From `Student s` WHERE student_id = ?";
$state =$mysqli->prepare($query);
$stmt->bind_param('i', $student_id);
if($state->execute()){
var_dump($state->fetch());
}else{
echo 'SELECT failed';
printf("Error: %s.\n", $state->error);
}
}else{
echo 'failed to execute UPDATE';
}
}else{
echo 'failed to prepare() UPDATE \n';
printf("Error: %s.\n", $stmt->error);
}
Hope this helps

Mysqli Prepared Statement Troubleshooting

I'm stumped, I recently had this working in plain Mysqli statements, but was told to avoid injection to write it using prepared statements. The truncate is the only thing that seems to work. Any advice?
$con=mysqli_connect(localhost,"username","password","db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$deletetable = $con->prepare('TRUNCATE TABLE twitch_streams');
$deletetable->execute();
$deletetable->close();
$result = $con->prepare("SELECT field_value
FROM xf_user_field_value
WHERE field_id = 'twitch'
AND field_value != ''");
$result->bind_result($twitchfield);
while($result->fetch())
{
printf("%s\n", $twitchfield);
$username[] = $twitchfield;
$data = json_decode(file_get_contents('http://api.justin.tv/api/stream/l ist.json?channel=' . $username[0]));
$viewer[] = $data[0]->channel_count;
$insert = $con->prepare("INSERT INTO twitch_streams (twitchuser, viewercount)
VALUES (?, ?)");
$insert->bind_param('si', $twitchuser, $viewercount);
$twitchuser = $username[0];
$viewercount = $viewer[0];
$insert->execute();
echo $twitchuser;
echo $viewercount;
$insert->close();
}
$result->close();$deletetable = $con->prepare('TRUNCATE TABLE twitch_streams');
$deletetable->execute();
$deletetable->close();
$result = $con->prepare("SELECT field_value
FROM xf_user_field_value
WHERE field_id = twitch
AND field_value != ''");
$result->bind_result($twitchfield);
while($result->fetch())
{
printf("%s\n", $twitchfield);
$username[] = $twitchfield;
$data = json_decode(file_get_contents('http://api.justin.tv/api/stream/l ist.json? channel=' . $username[0]));
$viewer[] = $data[0]->channel_count;
$insert = $con->prepare("INSERT INTO twitch_streams (twitchuser, viewercount)
VALUES (?, ?)");
$insert = bind_param('si', $twitchuser, $viewercount);
$twitchuser = $username[0];
$viewercount = $viewer[0];
$insert->execute();
echo $twitchuser;
echo $viewercount;
$insert->close();
}
$result->close();
mysqli_close($con);
There is no function bind_param(), it is a method of mysqli_stmt
You use it like so:
$insert->bind_param()
Check here for more information on mysqli_stmt

How to put PDO bindParam in if statement?

How to put PDO bindParam in if statement? I tried to do a different variations, but none of them worked.
function get_all_pages($subject_id, $public = true)
{
$db = new PDO('mysql:host=localhost;dbname=name;charset=utf8', 'root', 'whatewer');
$query = "SELECT * ";
$query.= "FROM pages ";
$query.= "WHERE subject_id =:id ";
if ($public)
{
$query.= " AND visible =:visible ";
}
$query.= "ORDER BY position ASC";
$query.= "ORDER BY position ASC";
$stmt = $db->prepare($query);
if ($public)
{
$stmt->bindParam(':id', $subject_id, PDO::PARAM_INT);
$stmt->bindValue(':visile', 2, PDO::PARAM_INT);
}
else
{
$stmt->bindParam(':id', $subject_id, PDO::PARAM_INT);
}
$stmt->execute();
$affected_rows = $stmt->rowCount();
if ($affected_rows == 1)
{
$subject = $stmt->fetch(PDO::FETCH_ASSOC);
return $subject;
}
}
else
{
return null;
}
}
Ok there was misunderstanding I got my cod "Wright" it was stackoverflow that messed my code up. i was struggling to put code in code area. In reality it looks like this.
http://imagizer.imageshack.us/v2/800x600q90/593/zvf8.png
$affected_rows = $stmt->rowCount(); might give you unexpected results as according to the manual:
For most databases, PDOStatement::rowCount() does not return the
number of rows affected by a SELECT statement.
You should fetch a row directly and see what the result is:
$stmt->execute();
if ($subject = $stmt->fetch(PDO::FETCH_ASSOC))
{
return $subject;
}
else
{
return null;
}
And I would recommend opening your database connection as I mentioned in my comment:
$db = new PDO('mysql:host=localhost;dbname=name;charset=utf8', 'root',
'whatewer', array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
That will cause PDO to throw exceptions and that will give you a clear error message whenever something goes wrong on any of the db calls.

Categories