Related
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.
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')");
}
i'm need help about sql query to select multiple table with multiple "or" condition. this is my database schema.
Hotel
id_hotel
id_state
id_city
hotel_name
State
id_state
state_name
City
id_city
city_name
thi is the query that i'm have been try, but result nothing.
$sql=mysqli_query($connection,"select * from hotel h, state s, city c where h.id_state=s.id_state and h.id_city=c.id_city and (h.hotel_name='$_GET[data]' or s.state_name='$_GET[data]' or c.city_name='$_GET[data]')");
I was try with that code.. and there is no result. Please help me guys.. tq
There are so many issues with your code that telling you and explaining everything you have to fix would take awhile, so I will list the basic and what you need to do.
You're not using any error handler at all, you should always use it while testing / developing, for instance MySQL error, code error and the such, which would have told you some of the issues you currently have.
You can read this page for more information on How to get useful error messages in php.
Continuing, you're using $_GET[data] inside double quotes which makes it loses its boundaries as you have not defined any for it, if you had any error handling it would have been pointed out.
You could have concatenated it " . $_GET['data'] . " or even used the curly brackets to define its boundaries like so {$_GET['data']}
You're injecting GET elements directly in your query without sanitizing it, which is a big mistake and a welcome to SQL injection.
All the above is based in the small portion of code you showed us and I am afraid to see the rest of it.
Here is a sample of how it would look like to use JOINs in your query along with parametized MySQLi.
<?php
// yes we want to see errors
ini_set('error_reporting', E_ALL);
// Your database info
$db_host = 'your database host address';
$db_user = 'your database username';
$db_pass = 'your database user password';
$db_name = 'your database name';
$con = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if ($con->connect_error)
{
die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
}
$sql = "SELECT h.id_hotel,
h.hotel_name,
s.id_state,
s.state_name,
c.id_city,
c.city_name
FROM hotel h
JOIN state s
ON h.id_state = s.id_state
JOIN city c
ON h.id_city = c.id_city
WHERE h.hotel_name = ? OR
s.state_name = ? OR
c.city_name = ?";
if (!$result = $con->prepare($sql))
{
die('Query failed: (' . $con->errno . ') ' . $con->error);
}
if (!$result->bind_param('sss', $_GET['data'], $_GET['data'], $_GET['data']))
{
die('Binding parameters failed: (' . $result->errno . ') ' . $result->error);
}
if (!$result->execute())
{
die('Execute failed: (' . $result->errno . ') ' . $result->error);
}
$result->bind_result($hotel_id, $hotel_name, $state_id, $state_name, $city_id, $city_name);
while ($result->fetch())
{
echo $hotel_id, " - ", $hotel_name, " - ", $state_id, " - ", $state_name, " - ", $city_id, " - ", $city_name, "\n";
}
$result->close();
$con->close();
More about bind_result, click me...
More about bind_param, click me...
Is not giving me any error, I am already linked with server but I am still unable to get it work.
It's still unable to add message, do you see any errors?
function pridaj_tovar() {
if ($link = spoj_s_db()) {
$sql = "INSERT INTO `Auto-Moto`".
"(`Tovar`, `Kategoria`,`Mesto`, `Cena`, `ID`, `Popis`)".
"VALUES".
"('$_POST['nazov']', '$_POST['kategorie']', '$_POST['mesta']',' $_POST['cena']', NULL,'$_POST['popis']')";
$result = mysql_query($sql, $link);
if ($result) {
// unable to add
echo '<p>inserting was successful.</p>'. "\n";
} else {
// unable to add!
echo '<p class="chyba">Nastala chyba pri pridávaní tovaru.</p>' . "\n";
}
mysql_close($link);
} else {
// NEpodarilo sa spojiť s databázovým serverom!
echo '<p class="chyba">NEpodarilo sa spojiť s databázovým serverom!</p>';
}
}
This is how you should handle field and table names with spaces,dashes (etc) :
$sql = "INSERT INTO `Auto-Moto`".
"(`Tovar`, `Kategoria`,`Mesto`, `Cena`, `ID`, `Popis`)".
"VALUES".
"('Something', 'Something1', 'word', '50', NULL, 'anotherword')";
$sql = "INSERT INTO `Auto-Moto`".
"(`Tovar`, `Kategoria`,`Mesto`, `Cena`, `ID`, `Popis`)".
"VALUES". "
('{$_POST['nazov']}', '{$_POST['kategorie']}', '{$_POST['mesta']}','{$_POST['cena']}',
NULL,'{$_POST['popis']}')";
You have several problems in your way of making query.
Firstly, your table name is quite non standard (Auto-Moto) so you might need to add quotes around it.
Secondly, it is always a good practice to add some space on proper locations so you could change:
"VALUES"
with
" VALUES "
But you need to provide which error you have received and your table structure.
You missed a lot of space in your Query :
Copy this :
$sql = "INSERT INTO Auto-Moto ".
"(Tovar, Kategoria, Mesto, Cena, ID, Popis) ".
"VALUES ".
"('Something', 'Something1', 'word', '50', NULL, 'anotherword')";
If you want to see an error message change this line:
$result = mysql_query($sql, $link);
To this:
$result = mysql_query($sql, $link) or die ("Error in query: $query. " . mysql_error());
But you should really learn to use mysqli_* extensions since mysql_* extensions—such as what you are using—will be depreciated in PHP 5.5. So change that to this:
$result = mysqli_query($sql, $link) or die ("Error in query: $query. " . mysqli_error());
And be sure to change any other mysqli_* extensions you code might have in place, such as in the spoj_s_db() function you are calling as the $link for a DB connection.
Additionally, your $sql has a few formatting errors. Try this instead:
$sql = "INSERT INTO Auto-Moto"
. " (Tovar, Kategoria, Mesto, Cena, ID, Popis)"
. " VALUES"
. " ('Something', 'Something1', 'word', '50', NULL, 'anotherword')"
;
Note the spaces in the query around the . " concatenation strings. In your original query the formatting had no spaces at all. Which would cause MySQL to choke on the query.
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();