Query isn't getting executed - php

Can some onw please explain what is wrong with this ... this worked completely fine with procedural php
function foo(){
$incomingtime = date('Y-m-d H:i:s', time());
$stmt = $db->stmt_init();
$id = "Abc123" ;
$u_id = 1;
$c_id = 1;
$query = "INSERT INTO table (indate, myid, uniqueid, commonid)
VALUES (?, ?, ?, ?)";
$stmt = $db->prepare($query);
$stmt->bind_param('ssii', $incomingtime, $id, $u_id, $c_id);
$stmt->execute();
printf("Affected rows (UPDATE): %d\n", $db->affected_rows); // Always return 1
$stmt->close();
}
But nothing goes in the database.
Datatype in mysql db for indate is datetime

There's several issues with this code.
$stmt_4 is used before it's defined.
$u_id and $c_id are both defined then not used.
Trying to execute $stmt without supplying parameters.
$db is not defined.
$id is not defined.
If you are trying to convert working code to a function make sure that either the function gets these passed in as an argument, they are marked as global or the function creates/ retrieves them.

Check changing:
$query = "INSERT INTO table (indate, myid, uniqueid, commonid)
VALUES (?, ?, ?, ?)";
$stmt = $db->prepare($query);
$stmt->bind_param('ssii', $incomingtime, $id, $u_id, $c_id);
$u_id = 1;
$c_id = 1;
$stmt->execute();
to:
$u_id = 1;
$c_id = 1;
$query = "INSERT INTO table (indate, myid, uniqueid, commonid)
VALUES (CURRENT_TIMESTAMP, ?, ?, ?)"
$stmt = $db->prepare($query);
$stmt->execute(array($id, $u_id, $c_id));
NOTE: I deleted the parameter ssii because it's not considered in the query. It only expects 4 parameters.

Related

(PHP) What's my mistake here?

The data on the form failed to saved on the database. I cannot find what's wrong here. I already checked the name of the input forms an it is all correct. I'm using PDO
if ($_POST) {
$accountuname = ($_POST['accountuname']);
$accountpassword = ($_POST['accountpassword']);
$accounttype = ($_POST['accounttype']);
$companyname = ($_POST['companyname']);
$companyproduct = ($_POST['companyproduct']);
$companyaddress = ($_POST['companyaddress']);
$companycontactnum = ($_POST['companycontactnum']);
$query = "INSERT INTO user_accounts SET USER_NAME=?, USER_PASS=?, USER_ACC_TYPE=?, COMPANY_NAME=?, COMPANY_PRODUCT=?, COMPANY_ADDRESS=?, COMPANY_CONTACTNUM=?";
$stmt = $conn->prepare($query);
$stmt -> bindParam(1,$accountuname);
$stmt -> bindParam(2,$accountpassword);
$stmt -> bindParam(3,$accounttype);
$stmt -> bindParam(4,$companyname);
$stmt -> bindParam(5,$companyproduct);
$stmt -> bindParam(6,$companyaddress);
$stmt -> bindParam(7,$companycontactnum);
$stmt -> execute();
}else{
header("location:index.php");
}
Change the SQL query from:
INSERT INTO user_accounts SET USER_NAME=?, USER_PASS=?, USER_ACC_TYPE=?, COMPANY_NAME=?, COMPANY_PRODUCT=?, COMPANY_ADDRESS=?, COMPANY_CONTACTNUM=?
To:
INSERT INTO user_accounts (USER_NAME, USER_PASS, USER_ACC_TYPE, COMPANY_NAME, COMPANY_PRODUCT, COMPANY_ADDRESS, COMPANY_CONTACTNUM) VALUES (?, ?, ?, ?, ?, ?, ?)
INSERT INTO syntax.
If you are using mysqli, acording to the documentation, the bind_param (instead of bindParam... maybe you are using a framework?) function expects the first parameter to be a string, instead of an int:
bind_param ( string $types , mixed &$var1 [, mixed &$... ] )
types
A string that contains one or more characters which specify the types
for the corresponding bind variables:
i corresponding variable has type integer
d corresponding variable has type double
s corresponding variable has type string
b corresponding variable is a blob and will be sent in packets
You should change the 1,2,3,4... to 'd,s,b' (the variable type), and it should work.
Hope it helps!
You have to specify the binded parameter type, and also your query was incorrect.
Here is the correct version in MySQLi:
$query = "INSERT INTO user_accounts (USER_NAME, USER_PASS, USER_ACC_TYPE, COMPANY_NAME, COMPANY_PRODUCT, COMPANY_ADDRESS, COMPANY_CONTACTNUM) VALUES (?, ?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($query);
$stmt->bindParam("sssssss", $accountuname, $accountpassword, $accounttype, $companyname, $companyproduct, $companyaddress, $companycontactnum);
// Set parameters and execute
$accountuname = $_POST['accountuname'];
$accountpassword = $_POST['accountpassword'];
$accounttype = $_POST['accounttype'];
$companyname = $_POST['companyname'];
$companyproduct = $_POST['companyproduct'];
$companyaddress = $_POST['companyaddress'];
$companycontactnum = $_POST['companycontactnum'];
$stmt->execute();
Here is the correct version in PDO:
$query = "INSERT INTO user_accounts (USER_NAME, USER_PASS, USER_ACC_TYPE, COMPANY_NAME, COMPANY_PRODUCT, COMPANY_ADDRESS, COMPANY_CONTACTNUM) VALUES (:uname, :upass, :utype, :cname, :cproduct, :caddress, :ccontactnum)";
$stmt = $conn->prepare($query);
$stmt->bindParam(':uname', $accountuname);
$stmt->bindParam(':upass', $accountpassword);
$stmt->bindParam(':utype', $accounttype);
$stmt->bindParam(':cname', $companyname);
$stmt->bindParam(':cproduct', $companyproduct);
$stmt->bindParam(':caddress', $companyaddress);
$stmt->bindParam(':ccontactnum', $companycontactnum);
// Set parameters and execute
$accountuname = $_POST['accountuname'];
$accountpassword = $_POST['accountpassword'];
$accounttype = $_POST['accounttype'];
$companyname = $_POST['companyname'];
$companyproduct = $_POST['companyproduct'];
$companyaddress = $_POST['companyaddress'];
$companycontactnum = $_POST['companycontactnum'];
$stmt->execute();
For MYSQLi: In this example I assumed all the posted data are string, otherwise you would have to change the 'sssssss' in the bindParam function.
Read more about prepared statements here
Read more about MySQLi INSERT syntax here

What to put in a MySQL auto-increment primary key field when inserting a row?

I'm new to PHP and I'm having a little trouble setting up my code to auto increment IDs for SQL. I'm aware that the method that I am attempting isn't a very good approach and know about the risks of race conditions etc. This will be temporary until I sort the rest of my code out properly.
Could somebody please tell me what I am doing wrong here? Or help me to get valid code?
My Class:
<?php
$user = 'root';
$pass = '';
$db = 'testuser';
$con=mysqli_connect('localhost', $user, $pass, $db) or die('Unable to connect');
$data = json_decode(trim(key($_POST), '[]'), true);
$email = $data['email'];
$name = $data['name'];
$shortDes = $data['shortDes'];
$longDes = $data['longDes'];
$max = mysqli_prepare($con, 'SELECT MAX(society_id) FROM society');
$society_id = $max + 1;
$statement = mysqli_prepare($con, 'INSERT INTO society(society_id, name, email, short_des, long_des) VALUES (?, ?, ?, ?, ?)');
mysqli_stmt_bind_param($statement, 'issss', $societyId, $name, $email, $shortDes, $longDes);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_close($statement);
mysqli_close($con);
?>
Focusing on the following snippet:
$max = mysqli_prepare($con, 'SELECT MAX(society_id) FROM society');
$society_id = $max + 1;
$statement = mysqli_prepare($con, 'INSERT INTO society(society_id, name, email, short_des, long_des) VALUES (?, ?, ?, ?, ?)');
mysqli_stmt_bind_param($statement, 'issss', $societyId, $name, $email, $shortDes, $longDes);
Just needed to remove the value for the auto incremented field altogether.

How to write PHP file to update database without ID or name?

I am new to writing php file and are currently trying to create a database which stores heart rate measured together with the timestamp.
However I got confused how should I write for the update php file. Anyone knows how to write it given my situation where my
$statement = mysqli_prepare($con, "UPDATE `User` SET timestamp = ?, heartrate = ?, WHERE ***what to include here*** = ?"); // I am not sure what to include here.
Code of my store data in database:
$con = mysqli_connect("server27.000webhost.com" , "a6244607_history" , "123" , "a6244607_history");
$timestamp = $_POST["timestamp"];
$heartrate = $_POST["heartrate"];
$statement = mysqli_prepare($con, "INSERT INTO `User` (timestamp, heartrate) VALUES (?, ?) ");
mysqli_stmt_bind_param($statement, "ss", $timestamp, $heartrate);
mysqli_stmt_execute($statement);
mysqli_stmt_close($statement);
mysqli_close($con);?>
Code to fetch data from database:
$con = mysqli_connect("server27.000webhost.com" , "a6244607_history" , "123" , "a6244607_history");
$timestamp = $_POST["timestamp"];
$heartrate = $_POST["heartrate"];
$statement = mysqli_prepare($con, "SELECT * FROM `User` WHERE timestamp = ? AND heartrate = ?");
mysqli_stmt_bind_param($statement, "ss", $timestamp, $heartrate);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $userID, $timestamp, $heartrate);
$user = array();
while(mysqli_stmt_fetch($statement))
{
$user[timestamp] = $timestamp;
$user[heartrate] = $heartrate;
}
echo json_encode($user);
mysqli_stmt_close($statement);
mysqli_close($con);?>
Code to update database:
$con = mysqli_connect("server27.000webhost.com" , "a6244607_history" , "123" , "a6244607_history");
$timestamp = $_POST["timestamp"];
$heartrate = $_POST["heartrate"];
$statement = mysqli_prepare($con, "UPDATE `User` SET timestamp = ?, heartrate = ?, WHERE username = ?");
mysqli_stmt_bind_param($statement, "ss", $timestamp, $heartrate);
mysqli_stmt_execute($statement);
mysqli_stmt_close($statement);
mysqli_close($con);
?>
On a side note, is my timestamp written correctly? Sorry for asking so much questions at once...
Hope to get some help soon, thank you.
1) You should not include credentials to your MySQL server on the post
2) Considering you only have 3 tables (user_id, heartrate, timestamp) and in this Prepared Statement:
UPDATE `User` SET timestamp = ?, heartrate = ?, WHERE ***what to include here*** = ?
You use timestamp and heart rate, so for what to include here should be user_id.
If you want to insert a brand new heart rate, use INSERT instead of SET.
Also, your statement should look like:
UPDATE `User` SET `timestamp` = ?, `heartrate` = ?, WHERE `user_id` = ?
Use the grave (`) around table names.

SQL INSERT bind not working

When I call the function updatePost($postID, $postTitle, $postContent, $catID) it calls it but fails on the first line $stmt = db::connect()->prepare. I am accessing my database the same way for all other functions but this one is failing. Why?
function updatePost($inPostID, $inPostTitle, $inPostContent, $inCatID)
{
var_dump($stmt);
$stmt = db::connect()->prepare("UPDATE Posts SET postTitle = ?, postContent = ?, postCatID = ?, WHERE postID = ?");
var_dump($stmt);
$stmt->bind_param('ssii', $inPostTitle, $inPostContent, $inPostCatID, $inPostID);
$stmt->execute();
$stmt->close();
}
Lose the last comma in your SQL statement:
UPDATE Posts SET postTitle = ?, postContent = ?, postCatID = ? WHERE postID = ?

mysqli::prepare is not returning an object?

I got some problem with binding some parameters in MYSQL statement in php. It is throwing an error when count($posts) > 1 on the marked line below. Anyone who know what I've done wrong?
The error is: Call to a member function bind_param() on a non-object. It is also reporting comman out of sync?(on the marked line below)
<?php
include '../../main/mainFunctions2.php';
$futurePosts = json_decode($_POST['futurePosts']);
$repeatSerie = null;
if(count($posts) > 1){
//Get new repeatSeries
$stmt = $mysqli->prepare("
SELECT repeatSerie
FROM timeSpaces_futurePosts
ORDER BY repeatSerie DESC
LIMIT 1
");
$stmt->execute();
$stmt->bind_result($repeatSerie);
$stmt->fetch();
$repeatSerie = ((int)$repeatSerie + 1);
}
$timeStamp = time();
foreach($posts as $fp){
$title = $fp->title;
$startDate = $fp->startDate;
$endDate = $fp->endDate;
$startTime = $fp->startTime;
$endTime = $fp->endTime;
$location = $fp->location;
$latLong = $fp->latLong;
$info = $fp->info;
$photoId = $fp->photoId;
$invited = $fp->invited;
if($invited != null){
$invited = 1;
}else{
$invited = 0;
}
$reminderType = $fp->reminderType;
$reminderTimeStamp = $fp->reminderTimeStamp;
$repeatSerie = $repeatSerie;
$stmt = $mysqli->prepare("
INSERT INTO futurePosts (profileId, title, startDate, endDate, startTime, endTime, location, latLong, info, photoId, invited, reminderType, reminderTimeStamp, repeatSerie)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
);
$stmt->bind_param('isssiisssiisii', $profileId, $title, $startDate, $endDate, $startTime, $endTime, $location, $latLong, $info, $photoId, $invited, $reminderType, $reminderTimeStamp, $repeatSerie);
//The line above: Call to a member function bind_param() on a non-object
$stmt->execute();
$futurePostId = $mysqli->insert_id;
if($invited == 1){
foreach($fp->invited as $friendsId){
$friendsId = $friendsId;
$stmt = $mysqli->prepare('
INSERT INTO futurePosts_invited (profileId, futurePostId, timeStamp)
VALUES (?, ?, ?)
');
$stmt->bind_param('iii', $friendsId, $futurePostId, $timeStamp);
$stmt->execute();
}
}
}
echo 'TRUE';
?>
This is most likely because $stmt = $mysqli->prepare(...); line fails due to SQL syntax error. Try echoing $mysqli->error to see what's wrong with it.
Try calling $stmt->store_result(); after execution of your SELECT statement and before issuing any other queries to MySQL.
Side note: you should prepare your statement before foreach loop. That will get you a bit of performance gain, since the statement will only be compiled once and only parameters will be sent to server on each loop run.
mysqli_prepare() returns a statement object or FALSE if an error
occurred.

Categories