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
Related
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,...);
The first example will add data to mysql database without any issue. The second block of code - where I try to use variables wont. Can someone please explain where I am going wrong?
<?php
$query = "INSERT INTO subjects (menu_name,position,visible) VALUES ('Edit me',4,1)";
$result = mysqli_query($connection, $query);
Problem CODE:
<?php
$menu_name = "TEST";
$position = 5;
$visible = 1;
$query = "INSERT INTO subjects (menu_name,position,visible)
VALUES ('{menu_name}',{position}, {visible})";
$result = mysqli_query($connection, $query);
*Answer updated with MySQLi prepare statement, thanks #h2ooooooo
<?php
//Open a new connection to the MySQL server
$db = new mysqli('host','username','password','database_name');
//Output connection errors
if ($db->connect_error) {
die('Error : ('. $db->connect_errno .') '. $db->connect_error);
}
$sql = "INSERT INTO subjects (menu_name, position, visible) VALUES (?, ?, ?)";
if (!$stmt = $db->prepare($sql)) {
echo 'Database prepare error';
exit;
}
$stmt->bind_param('sss', $menu_name, $position, $visible);
if (!$stmt->execute()) {
echo 'Database execute error';
exit;
}
$stmt->close();
I'd say for you to take a look in the many tutorials thorugh net, like these:
http://markonphp.com/simple-insert-mysqli/ and
http://www.sanwebe.com/2013/03/basic-php-mysqli-usage
$query = "INSERT INTO subjects (menu_name,position,visible) VALUES
('".$menu_name."','".$position."', '".$visible."')";
try this
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";
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.
I am trying to insert image path into an existing databse. The code below works, but inserts a new row.
$address= htmlentities($_SESSION['address']);
$city= htmlentities($_SESSION['city']);
$zip_code= htmlentities($_SESSION['zip_code']);
$query =
"INSERT INTO property(name, size, type_picture, file_path, username) VALUES (?,?,?,?,?)";
$conn = $db->prepare($query);
if ($conn == TRUE) {
$conn->bind_param("sisss", $myfile, $fileSize, $fileType, $path, $username);
if (!$conn->execute()) {
echo 'error insert';
}else {
echo 'Success!<br/>';
echo '<img src="' . DISPLAY_PATH . $myfile . '"/>';
}
} else {
die("Error preparing Statement");
When I try the same as above but UPDATE, i get the "Error preparing Statement". I need to update empty cells (if this matters).
$query =
"UPDATE property(name, size, type_picture, file_path, username)
SET(?,?,?,?,?)
WHERE address = '$address' // with or without ''
city = '$city' ";
$conn = $db->prepare($query);
if ($conn == TRUE) {
$conn->bind_param("sisss", $myfile, $fileSize, $fileType, $path, $username);
if (!$conn->execute()) {
echo 'error insert';
} // etc. etc.
Thank you so much. Tried for a day, need some help.
Your update query is wrong, try this instead:
$query = "UPDATE property SET name = ?, size = ?, type_picture = ?, file_path = ?, username = ?
WHERE address = ? AND city = ?"
$conn = $db->prepare($query);
if ($conn == TRUE) {
$conn->bind_param("sisss", $myfile, $fileSize, $fileType, $path, $username,$address,$city);
if (!$conn->execute()) {
echo 'error update';
}
}
You need an AND or OR in the WHERE statement:
WHERE address = '$address' AND // with our without ''
city = '$city' ";
I also don't think you should mix parameters with string substitution. Make $address and $city parameters as well.