How to get variables from URL and insert into database - php

So I am trying to get the variables from the URL (http://example.com/pb.php?id=123&affiliate=abd123&lp1=dun.com&lp2=dun2.com&lp3=dun3.com) and Ive tried this code but I receive this error
Prepare failed: (1136) Column count doesn't match value count at row 1
Fatal error: Call to a member function bind_param() on boolean in /home/recondes/public_html/postback.php on line 25
and also
<?php
define("MYSQL_HOST", "localhost");
define("MYSQL_PORT", "3306");
define("MYSQL_DB", "db");
define("MYSQL_TABLE", "tbl");
define("MYSQL_USER", "user");
define("MYSQL_PASS", "pass");
$mysqli = new mysqli(MYSQL_HOST, MYSQL_USER, MYSQL_PASS, MYSQL_DB);
if ($mysqli->connect_errno)
{
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$id = $_GET['id'];
$affiliate = $_GET['affiliate'];
$lp1 = $_GET['lp1'];
$lp2 = $_GET['lp2'];
$lp3 = $_GET['lp3'];
if (!($stmt = $mysqli->prepare("INSERT INTO ".MYSQL_TABLE." VALUES (id, affiliate, lp1, lp2, lp3);")))
{
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
$stmt->bind_param('dds', $id, $affiliate, $lp1, $lp2, $lp3 );
if (!$stmt->execute())
{
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
else
{
printf("%d Row updated, added ".$id." to ".$affiliate." .\n", mysqli_stmt_affected_rows($stmt));
}
?>

Your query doesn't list the columns to be inserted into, so it expects you to supply values for all the table columns. You haven't shown the table schema, but it doesn't have only 5 columns.
You're also missing the placeholders that will get filled in by bind_param(). I suspect the values you listed in VALUES() were intended to be the table columns. So try:
if (!($stmt = $mysqli->prepare("INSERT INTO ".MYSQL_TABLE." (id, affiliate, lp1, lp2, lp3) VALUES (?, ?, ?, ?, ?)")))
Also, in your call to bind_param, the string that specifies the datatypes needs to have as many letters as there are parameters. So it should be:
$stmt->bind_param('dssss', $id, $affiliate, $lp1, $lp2, $lp3 );
Finally, when you get an error in one step, and you print the error message, you should stop this script rather than going on to the next step. It makes no sense to use the prepared statement if prepare() fails.

Related

how to combine query for multiple able to save data

can it be combine into 1 query?
this is the query that im trying to combine? or is there a better way to relate these to table?
$insert_row = $mysqli->query("INSERT INTO orderlist
(TransactionID,ItemName,ItemNumber, ItemAmount,ItemQTY)
VALUES ('$transactionID','$itemname','$itemnumber', $ItemTotalPrice,'$itemqty')");
$insert_row1 = $mysqli->query("INSERT INTO order
(BuyerName,BuyerEmail,TransactionID)
VALUES ('$buyerName','$buyerEmail','$transactionID')");
when i run these both only one query is functional, so what im trying to do is to make them both works.
im open to any suggestion
The reason why your second query isn't working is because of the use of order and not escaping it; it is a MySQL reserved word:
https://dev.mysql.com/doc/refman/5.5/en/keywords.html
Sidenote: ORDER is used when performing a SELECT... ORDER BY...
https://dev.mysql.com/doc/refman/5.0/en/select.html
Checking for errors would have shown you the syntax error such as:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax near 'order
http://php.net/manual/en/mysqli.error.php
Therefore, wrap it in ticks:
$insert_row1 = $mysqli->query("INSERT INTO `order` ...
or rename your table to something other than a reserved word, say orders for example.
If you wish to combine both queries, you can use multi_query()
http://php.net/manual/en/mysqli.quickstart.multiple-statement.php
Example from the manual:
<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT)")) {
echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
$sql = "SELECT COUNT(*) AS _num FROM test; ";
$sql.= "INSERT INTO test(id) VALUES (1); ";
$sql.= "SELECT COUNT(*) AS _num FROM test; ";
if (!$mysqli->multi_query($sql)) {
echo "Multi query failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
do {
if ($res = $mysqli->store_result()) {
var_dump($res->fetch_all(MYSQLI_ASSOC));
$res->free();
}
} while ($mysqli->more_results() && $mysqli->next_result());
?>
I also need to point out that your present code may be open to SQL injection since I do not know if you are escaping your data.
If not, then use prepared statements, or PDO with prepared statements, they're much safer.
try to add IF statement.
if ($insert_row = $mysqli->query("INSERT INTO orderlist(TransactionID,ItemName,ItemNumber, ItemAmount,ItemQTY)VALUES ('$transactionID','$itemname','$itemnumber', $ItemTotalPrice,'$itemqty')"));
{
$insert_row1 = $mysqli->query("INSERT INTO order (BuyerName,BuyerEmail,TransactionID) VALUES ('$buyerName','$buyerEmail','$transactionID')");
}

Attempt to get a php prepare to work with two different tables

I am attempting to do my first query where I send to two different db tables. I am trying to update the 'group' in the users and user_request table. I am getting an id from an AJAX call, I am using that id to find the record I am trying to update.
In the users table the id will need to find the id field.
In the user_requests table the id will need to associate with the user_id.
This is the line I am trying to change to make this send to two different db tables..
$stmt = $con->prepare("UPDATE users,user_reuqests SET `group`=? WHERE id, user_id=?");
I'm getting an error responce saying the error is by the user_id part.
$approved_id = $_POST['id'];
$change_group = $_POST['update_group'];
$con = mysqli_connect("localhost","root","","db");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $con->prepare("UPDATE users,user_reuqests SET `group`=? WHERE id, user_id=?");
if ( !$stmt || $con->error ) {
// Check Errors for prepare
die('User Group update prepare() failed: ' . htmlspecialchars($con->error));
}
if(!$stmt->bind_param('ii', $change_group, $approved_id)) {
// Check errors for binding parameters
die('User Group update bind_param() failed: ' . htmlspecialchars($stmt->error));
}
if(!$stmt->execute()) {
die('User Group update execute() failed: ' . htmlspecialchars($stmt->error));
}
What am I doing wrong to not get this to work and conjoin?
UPDATE: After I changed the prepare part of this, I'm now getting errors in my bind_param part of my prepared statement. How can I change this?
$stmt = $con->prepare("UPDATE users,user_requests SET users.group=?, user_requests.group=? WHERE users.id=? AND user_requests.user_id=?");
First, The WHERE clause in your query doesn't specify an id for the first constraint.
Second, group is ambiguous and will cause errors when you try to update it.
Your query should read:UPDATE users,user_reuqests SET users.group=?, user_request.group=? WHERE users.id=? AND user_request.user_id=?
Now, since we've updated the query with more place holders, we need to bind these additional placeholders to PHP variables. The new query uses both $change_group and $approved_id twice - so we need to bind each of them twice.
if(!$stmt->bind_param('iiii', $change_group, $change_group, $approved_id, $approved_id)) {
// Check errors for binding parameters
die('User Group update bind_param() failed: ' . htmlspecialchars($stmt->error));
}
When all is said and done, the final code should look like this:
$approved_id = $_POST['id'];
$change_group = $_POST['update_group'];
$con = mysqli_connect("localhost","root","","db");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $con->prepare("UPDATE users,user_reuqests SET users.group=?, user_request.group=? WHERE users.id=? AND user_request.user_id=?");
if ( !$stmt || $con->error ) {
// Check Errors for prepare
die('User Group update prepare() failed: ' . htmlspecialchars($con->error));
}
if(!$stmt->bind_param('iiii', $change_group, $change_group, $approved_id, $approved_id)) {
// Check errors for binding parameters
die('User Group update bind_param() failed: ' . htmlspecialchars($stmt->error));
}
if(!$stmt->execute()) {
die('User Group update execute() failed: ' . htmlspecialchars($stmt->error));
}
More info on binding parameters to a mysqli_stmt here: http://php.net/manual/en/mysqli-stmt.bind-param.php
There's a problem with your syntax:
WHERE id, user_id=?
It should be something like this:
WHERE id = ? AND user_id = ?

Call Stored procedure (which returns two table) in php

I am working in a GUI tool development using php. There are STORED PROCEDURES already present in the database. Those stored procedures cannot be changed. (other tool dependency).
My Question: There is a procedure which returns two tables when called in mysql directly. (maybe 2 select statement inside it).
How can I use 'mysqli -- php' to display the data from two tables returned?
NOTE : Both table returned has same columns(name,id,status) in it
Make use of mysqli::use_result
$mysqli = new mysqli("localhost", "root", "password", "db_name");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") ";
}
$query = "CALL sp_multiple results (?, ?)";
$stmt = $mysqli->prepare($query);
if (!$stmt) {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
$stmt->bind_param("ss", $param1, $param2);
$stmt->execute();
/* get first result set */
if ($result1 = $mysqli->use_result()) {
//fetch data
$result1->close();
}
/* get second result set */
if ($result2 = $mysqli->use_result()) {
//fetch data
$result2->close();
}
$mysqli->close();

MySQL Syntax error on Insert Query from PHP

I'm getting a non-descriptive syntax error on a MYSQL query from PHP. If I "echo" the text of the query and paste it into a MySQL query window, the code works. Here is the SQL for the query, the error code, and the error message...
INSERT INTO ADVERTISEMENTS (`user_id`, `ad_name`, `click_url`, `img_url`, `bg_color`, `start_date`, `end_date`, `timer_delay`, `add_date`) VALUES (2, 'Test New Ad', 'http://www.google.com', 'red_arrow.png', '#000000', '1980-05-11 00:00:00', '2020-05-01 00:00:00', 5, '2013-07-14 22:21:59');
Error Code: 1064
Error Msg: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
Here is the PHP code I am using...
$link = mysqli_connect($UM_Settings["database_options"]["server_name"], $UM_Settings["database_options"]["username"], $UM_Settings["database_options"]["password"], $UM_Settings["database_options"]["database_name"]);
$advertisementNameNew = mysqli_real_escape_string($link, $_POST['advertisementNameNew']);
$destinationURLNew = mysqli_real_escape_string($link, $_POST['destinationURLNew']);
$dropboxUploadFile = mysqli_real_escape_string($link, $_POST['dropboxUploadFile']);
$backgroundColorNew = mysqli_real_escape_string($link, $_POST['backgroundColorNew']);
$bannerStartDateNew = DateStringToMySQL($_POST['bannerStartDateNew']);
$bannerEndDateNew = DateStringToMySQL($_POST['bannerEndDateNew']);
$bannerSetTimerNew = intval($_POST['bannerSetTimerNew']);
$tmpUserID = UM_GetCookie("UM_UserID");
$tmpAddDate = DateStringToMySQL('now');
echo "INSERT INTO ADVERTISEMENTS(`user_id`, `ad_name`, `click_url`, `img_url`, `bg_color`, `start_date`, `end_date`, `timer_delay`, `add_date`) VALUES ($tmpUserID, '$advertisementNameNew', '$destinationURLNew', '$dropboxUploadFile', '$backgroundColorNew', '$bannerStartDateNew', '$bannerEndDateNew', $bannerSetTimerNew, '$tmpAddDate');<br />";
if (!mysqli_query($link, "INSERT INTO ADVERTISEMENTS(`user_id`, `ad_name`, `click_url`, `img_url`, `bg_color`, `start_date`, `end_date`, `timer_delay`, `add_date`) VALUES ($tmpUserID, '$advertisementNameNew', '$destinationURLNew', '$dropboxUploadFile', '$backgroundColorNew', '$bannerStartDateNew', '$bannerEndDateNew', $bannerSetTimerNew, '$tmpAddDate');")) {
printf("Error Code: %s\n", mysqli_errno($link));
echo "<br />";
printf("Error Msg: %s\n", mysqli_error($link));
}
I know that the database connection is working. I am able to select and update tables. I can also insert into other tables with different queries.
I am open to any suggestions.
Thank you in advance for your help!
I see a few errors in your query strings.
First, all your variables are passed as literal strings: "... VALUES ($tmpUserID, '$advertisementNameNew', ..." should be "... VALUES (".$tmpUserID.", '".$advertisementNameNew."', ...".
Second, I see missing quotes around $bannerSetTimerNew.
Third, there is an extra ;.
here's how I would write the query:
if (!mysqli_query($link, "INSERT INTO ADVERTISEMENTS (user_id, ad_name, click_url, img_url, bg_color, start_date, end_date, timer_delay, add_date) VALUES (".$tmpUserID.", '".$advertisementNameNew."', '".$destinationURLNew."', '".$dropboxUploadFile."', '".$backgroundColorNew."', '".$bannerStartDateNew."', '".$bannerEndDateNew."', '".$bannerSetTimerNew."', '".$tmpAddDate."')")) { ...
I didnt test it though.
hope this helps.
I see a ; at the end of the query. Are you sure that should be there?
There are two things
1. Remove the ; from at the end of the query.
2. I hope timer_delay field has datatype "Int" if its a VARCHAR then you will have to include quotes for that field value.
I hope this will help.
Passerby, thank you for your comment. This was my first experience with using mysqli, I changed my query to use the "bind_param" method, and everything works now. For anyone else with a similar problem, here is the corrected code...
$mysqli = new mysqli($UM_Settings["database_options"]["server_name"], $UM_Settings["database_options"]["username"], $UM_Settings["database_options"]["password"], $UM_Settings["database_options"]["database_name"]);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$advertisementNameNew = $_POST['advertisementNameNew'];
$destinationURLNew = $_POST['destinationURLNew'];
$dropboxUploadFile = $_POST['dropboxUploadFile'];
$backgroundColorNew = $_POST['backgroundColorNew'];
$bannerStartDateNew = DateStringToMySQL($_POST['bannerStartDateNew']);
$bannerEndDateNew = DateStringToMySQL($_POST['bannerEndDateNew']);
$bannerSetTimerNew = intval($_POST['bannerSetTimerNew']);
$tmpUserID = UM_GetCookie("UM_UserID");
$tmpAddDate = DateStringToMySQL('now');
/* Prepared statement, stage 1: prepare */
if (!($stmt = $mysqli->prepare("INSERT INTO `ADVERTISEMENTS` (`user_id`, `ad_name`, `click_url`, `img_url`, `bg_color`, `start_date`, `end_date`, `timer_delay`, `add_date`) VALUES (?,?,?,?,?,?,?,?,?)"))) {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
if (!$stmt->bind_param("issssssis",$tmpUserID, $advertisementNameNew, $destinationURLNew, $dropboxUploadFile, $backgroundColorNew, $bannerStartDateNew, $bannerEndDateNew, $bannerSetTimerNew, $tmpAddDate)) {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
$_GET['ad_id'] = $stmt->insert_id;
$stmt->close();

Access the id of the object inserted after a prepared statement in PHP using MYSQLi

I need the id of the last inserted object. I use prepared statements to avoid sql injection.
But i'm not sure how to obtain the id.
$sql = "INSERT IGNORE INTO faculty (id, term, role, prefix, first_name,
middle_name, last_name, suffix) VALUES (?,?,?,?,?,?,?,?)";
if (!($stmt = $mysqli->prepare($sql)))
echo "Faculty Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
$stmt->bind_param('sissssss',
$faculty['id'],
$faculty['term'],
$faculty['role'],
$faculty->name->prefix,
$faculty->name->first,
$faculty->name->middle,
$faculty->name->last,
$faculty->name->suffix
);
if (!$stmt->execute())
echo "Faculty Execute failed: (" . $mysqli->errno . ") " . $mysqli->error;
$result = $stmt->insert_id;
echo "\n Result:" . $result;
$stmt->close();
The result is 0 always despite there being an entry in the database
Solution
The element was being inserted into the database. The problem was when I had created the table id wasn't an integer it was a varchar which represented an employee id. To fix this, i added the employee id as an additional column in the table and used the default id int auto_increment primary key and it worked.
Try changing $result = $stmt->get_result(); to $result = $stmt->insert_id;
get_result() is more for SELECT queries, rather than INSERTs.
http://php.net/manual/en/mysqli-stmt.get-result.php
http://php.net/manual/en/mysqli-stmt.insert-id.php

Categories