I am trying to insert a row in mysql table using the below php prepared statement, but the code always pass the statement and move to echo "failed". what is missing in the below code?
(My Database has extra columns but I didn't add it as I don't want to insert values inside (one of these columns are auto increment))
<?php
$ActivityDate = $_POST["ActivitytDate"];
$CoreSite = $_POST["CoreSite"];
$ActionAuditor = $_POST["ActionAuditor"];
$DCOSPOC = $_POST["DCOSPOC"];
if($stmt = $mysqli->prepare("Insert INTO DCO_Database (ActivityDate, CoreSite, ActionAuditor, DCOSPOC) Where (ActivityDate=? AND CoreSite=? AND ActionAuditor=? AND DCOSPOC=?)"))
{
$stmt->bind_param("ssss", $ActivityDate, $CoreSite, $ActionAuditor, $DCOSPOC);
$stmt->execute();
$stmt->close();
}
else{
echo ("Failed");
$mysqli->close();
}
?>
I have editied the code to use values instead, it is not echoing Failed but echoing success .. but still not adding values to database
<?php
$ActivityDate = $_POST["ActivitytDate"];
$CoreSite = $_POST["CoreSite"];
$ActionAuditor = $_POST["ActionAuditor"];
$DCOSPOC = $_POST["DCOSPOC"];
$AreaOwner = $_POST["AreaOwner"];
$ActionImplementer = $_POST["ActionImplementer"];
$ActionOwner = $_POST["ActionOwner"];
$MailSubject = $_POST["MailSubject"];
$ActionType = $_POST["ActionType"];
$RequestType = $_POST["RequestType"];
$RequestNumber = $_POST["RequestNumber"];
$OpenTime = $_POST["OpenTime"];
$CloseTime = $_POST["CloseTime"];
$ActionResult = $_POST["ActionResult"];
$Violation = $_POST["Violation"];
$ActionDetails = $_POST["ActionDetails"];
$Snags = $_POST["Snags"];
$SnagDesc = $_POST["SnagDesc"];
$Layout = $_POST["Layout"];
$LayoutDesc = $_POST["LayoutDesc"];
$CabinetLocation = $_POST["CabinetLocation"];
$Mapping = $_POST["Mapping"];
$MappingDesc = $_POST["MappingDesc"];
$Notes = $_POST["Notes"];
if($stmt = $mysqli->prepare("Insert INTO DCO_Database (ActivityDate, CoreSite, ActionAuditor, DCOSPOC, AreaOwner, ActionImplementer, ActionOwner, MailSubject, ActionType, RequestType, RequestNumber, OpenTime, CloseTime, ActionResult, Violation, ActionDetails, Snags, SnagDesc, Layout, LayoutDesc, CabinetLocation, Mapping, MappingDesc, Notes) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"))
{
$stmt->bind_param("ssssssssssssssssssssssss", $ActivityDate, $CoreSite, $ActionAuditor, $DCOSPOC, $AreaOwner, $ActionImplementer, $ActionOwner, $MailSubject, $ActionType, $RequestType, $RequestNumber, $OpenTime, $CloseTime, $ActionResult, $Violation, $ActionDetails, $Snags, $SnagDesc, $Layout, $LayoutDesc, $CabinetLocation, $Mapping, $MappingDesc, $Notes);
$stmt->execute();
$stmt->close();
}
else{
echo ("Failed");
$mysqli->close();
}
echo ("Successful");
?>
// think you should do as follows, insert statement only allows where clause when select statement is used,
<?php
$ActivityDate = $_POST["ActivitytDate"];
$CoreSite = $_POST["CoreSite"];
$ActionAuditor = $_POST["ActionAuditor"];
$DCOSPOC = $_POST["DCOSPOC"];
if($stmt = $mysqli->prepare("Insert INTO DCO_Database (ActivityDate, CoreSite, ActionAuditor, DCOSPOC) values (?,?,?,?)");
{
$stmt->bind_param("ssss", $ActivityDate, $CoreSite, $ActionAuditor, $DCOSPOC);
$stmt->execute();
$stmt->close();
}
else{
echo ("Failed");
$mysqli->close();
}
?>
use values insted of where
<?php
$ActivityDate = $_POST["ActivitytDate"];
$CoreSite = $_POST["CoreSite"];
$ActionAuditor = $_POST["ActionAuditor"];
$DCOSPOC = $_POST["DCOSPOC"];
if($stmt = $mysqli->prepare("Insert INTO DCO_Database (ActivityDate, CoreSite, ActionAuditor, DCOSPOC) values(?,?,?,?)"))
{
$stmt->bind_param("ssss", $ActivityDate, $CoreSite, $ActionAuditor, $DCOSPOC);
$stmt->execute();
$stmt->close();
}
else{
echo ("Failed");
$mysqli->close();
}
?>
You have to use
values
in your query. and remove
AND
from the query too. Please check the following code.
if($stmt = $mysqli->prepare("Insert INTO DCO_Database (ActivityDate, CoreSite, ActionAuditor, DCOSPOC) values (?,?,?,?)"))
{
$stmt->bind_param("ssss", $ActivityDate, $CoreSite, $ActionAuditor, $DCOSPOC);
$stmt->execute();
$stmt->close();
}
else{
echo ("Failed");
$mysqli->close();
}
Please note that where is used for update. so to insert use the query as follows:
INSERT INTO table_name (column1,column2,column3,...) VALUES (value1,value2,value3,...);
Related
I have two or more statements on one page of my site. And it does not work properly.
The first code is like that:
$query = "SELECT gpname FROM guineapigs WHERE fbid=?";
if ($statement = $mysqli->prepare($query)) {
$statement->bind_param('s', $_SESSION[FBID]);
$statement->execute();
$statement->bind_result($gpname);
while($statement->fetch()) {
echo $gpname;
}
}
$statement->close();
The problem is when I try to add the second code to it:
if($_GET[buy]=='ch'){
$statement = $mysqli->prepare("UPDATE users SET `money` = `money`+ 22000 WHERE gpname=?");
$statement->bind_param('s', $gpname);
$results = $statement->execute();
header( "Location: /test.php?bsuccess=ch" );
}
if($_GET[bsuccess]=='ch'){
echo "Successfully added 22000 money..";
}
My code looks like this, but not working:
$query = "SELECT gpname FROM guineapigs WHERE fbid=?";
if ($statement = $mysqli->prepare($query)) {
$statement->bind_param('s', $_SESSION[FBID]);
$statement->execute();
$statement->bind_result($gpname);
while($statement->fetch()) {
if($_GET[buy]=='ch'){
$statement2 = $mysqli->prepare("UPDATE users SET `money` = `money`+ 22000 WHERE gpname=?");
$statement2->bind_param('s', $gpname);
$statement2->execute();
header( "Location: /test.php?bsuccess=ch" );
}
if($_GET[bsuccess]=='ch'){
echo "Successfully added 22000 money..";
}
}
}
$statement->close();
What am I doing wrong? I want to add even more UPDATE querys after selecting.
Ohh, I'm an idiot! That was the mistake:
Instead of
while ($stmt1->fetch()){
};
needs only:
while ($stmt1->fetch());
Here's a working example with some development:
<?php
ob_start();
session_start();
include_once 'dbtest.php';
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
$mysqli->autocommit(FALSE); //turn on transactions
$stmt1 = $mysqli->prepare("SELECT fbname,fbemail FROM users WHERE fbid = ?");
$stmt1->bind_param("s", $_SESSION['FBID']);
$stmt1->execute();
$stmt1->bind_result($fbname,$fbemail);
while ($stmt1->fetch());
$stmt2 = $mysqli->prepare("INSERT INTO test (name,email) VALUES (?, ?)");
$stmt2->bind_param("ss", $fbname, $fbemail);
$stmt2->execute();
$stmt2->close();
$stmt1->close();
$mysqli->autocommit(TRUE); //turn off transactions + commit queued queries
} catch(Exception $e) {
$mysqli->rollback(); //remove all queries from queue if error (undo)
error_log($e);
}
?>
Thank you anyway!!
I've got a problem in my PHP code whith an SQL statement.
I want to get back the ID of my Indice where my name = 'myname'.
Here is my code :
<?php
include 'Connection.php';
try {
$db = new PDO("$server:host=$host;dbname=$base", $user, $passwd);
//Statement = INSERT INTO indice
$stmtInd = $db->prepare("INSERT INTO indice(ID, Name, IDFormation)
VALUES (:ID, :Name, :IDFormation)");
$stmtInd->bindParam(':ID', $id);
$stmtInd->bindParam(':Name', $name);
$stmtInd->bindParam(':IDFormation', $idformation);
//Statement = INSERT INTO note
$stmtNote = $db->prepare("INSERT INTO note(ID, Valeur, Valeurtext, IDIndice)
VALUES (:ID, :Valeur, :Valeurtext, :IDIndice)");
$stmtNote->bindParam(':ID', $ID);
$stmtNote->bindParam(':Valeur', $valeur);
$stmtNote->bindParam(':Valeurtext', $valeurtext);
$stmtNote->bindParam(':IDIndice', $IDindice);
$noteIdindice = $db->prepare("SELECT ID FROM indice WHERE Name = :Name");
$noteIdindice->bindParam(':Name', $name);
$noteIdindice->execute();
$resultat = $noteIdindice->fetch(\PDO::FETCH_ASSOC);
var_dump($resultat);
//Indice 1
$name = "Equilibre theorie / pratique";
$idformation = "1";
$stmtInd->execute();
$valeur = $_POST["indice1"];
$valeurtext = "";
$IDindice = $resultat['ID'];
$stmtNote->execute();
echo "Success";
}
catch (PDOException $e) {
die("Impossible de se connecter a la source de donnees...");
}
?>
There is other Indice but you dont need it cuz its the same as "//Indice 1".
Everything works and i have no failure. But my query give me a wrong return. It returns me "0" instead of the ID i want.
Do you guys know why ?
Your prepared statement is never executed, you should add execute :
$noteIdindice = $db->prepare("SELECT ID FROM indice WHERE Name = :Name");
$noteIdindice->bindParam(':Name', $name);
$noteIdindice->execute();//Add this row
$resultat = $noteIdindice->fetch();
EDIT :
You are trying to binding params with null values.
$stmtInd = $db->prepare("INSERT INTO indice(ID, Name, IDFormation)
VALUES (:ID, :Name, :IDFormation)");
$stmtInd->bindParam(':ID', $id);
$stmtInd->bindParam(':Name', $name); //$name variable not exists
$stmtInd->bindParam(':IDFormation', $idformation);//$idformation variable not exists
Try to do this :
<?php
include 'Connection.php';
try {
$db = new PDO("$server:host=$host;dbname=$base", $user, $passwd);
//Indice 1
$name = "Equilibre theorie / pratique";
$idformation = "1";
$valeur = $_POST["indice1"];
$valeurtext = "";
//Statement = INSERT INTO indice
$stmtInd = $db->prepare("INSERT INTO indice(ID, Name, IDFormation)
VALUES (:ID, :Name, :IDFormation)");
$stmtInd->bindParam(':ID', $id);
$stmtInd->bindParam(':Name', $name);
$stmtInd->bindParam(':IDFormation', $idformation);
$stmtInd->execute();
//Statement = INSERT INTO note
$stmtNote = $db->prepare("INSERT INTO note(ID, Valeur, Valeurtext, IDIndice)
VALUES (:ID, :Valeur, :Valeurtext, :IDIndice)");
$stmtNote->bindParam(':ID', $ID);
$stmtNote->bindParam(':Valeur', $valeur);
$stmtNote->bindParam(':Valeurtext', $valeurtext);
$stmtNote->bindParam(':IDIndice', $IDindice);
$stmtNote->execute();
$noteIdindice = $db->prepare("SELECT ID FROM indice WHERE Name = :Name");
$noteIdindice->bindParam(':Name', $name);
$noteIdindice->execute();
$resultat = $noteIdindice->fetch(\PDO::FETCH_ASSOC);
var_dump($resultat);
$IDindice = $resultat['ID'];
echo "Success";
}
catch (PDOException $e) {
die("Impossible de se connecter a la source de donnees...");
}
?>
I've the following php code
$riziv = $_GET["riziv"];
$answer1 = (int)$_GET["answer1"];
$answer2 = (int)$_GET["answer2"];
$name = $_get["name"];
$first_name = $_get["first_name"];
$city = $_get["city"];
if (empty($riziv)) {
$stmt = $this->db->prepare("INSERT INTO Doctors
(name,first_name,city,answer1,answer2)
VALUES (?,?,?,?,?)");
$stmt->bind_param("sssdd",$name,$first_name,$city,$answer1,$answer2);
}else{
$stmt = $this->db->prepare("UPDATE Doctors SET answer1 = ?, answer2 = ? WHERE riziv=?");
$stmt->bind_param("dds",$answer1,$answer2,$riziv);
}
$stmt->execute();
$stmt->close();
$this->db->commit();
The update is working but the insert breaks on the bind_param line?
Can anybody help?
Thanks !
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
I've a few examples but nothing that I can grasp. I have the below code, the echos work but the insert does not. I believe I'm suppose to explode these? Not sure but maybe someone can give me a hint with my own example.
$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);
You're missing quotes around your string values:
"INSERT INTO twitch_streams (twitchuser, viewercount)
VALUES ($username[0], $viewer[0])"
should be
"INSERT INTO twitch_streams (twitchuser, viewercount)
VALUES ('$username[0]', '$viewer[0]')"
You would spot this error easily if you add error handling to your code. Look into using mysqli_error().
$result = mysqli_query($con,"INSERT INTO twitch_streams (twitchuser, viewercount)
VALUES ('$username[0]', '$viewer[0]')");
if (!result) {
// This should be done better than this
echo mysqli_error();
exit;
}
Since I can't tell from your code what the source of $data[0]->channel_count is I will also mention that you should at least escape your insert variables with mysqli_real_escape_string(). Even better, use prepared statements.