What is proper way to skip a MySQL INSERT - php

I have a foreach statement looping through JSON data and inserting the contents into MySQL. I want to skip the insert if a specific username is shown for $author string. Is the below method ok or is it better to handle at the database level?
foreach ($response['data'] as $data) {
$id = $data['id'];
$created_time = $data['created_time'];
$thumbnail = $data['images']['low_resolution']['url'];
$author = $data['user']['username'];
$caption = mysql_real_escape_string($data['caption']['text']);
$link = $data['link'];
$likes = $data['likes']['count'];
if ($author == 'USERNAME') {
mysql_close($con);
} else {
$query = "INSERT IGNORE INTO pbr (id, created_time, thumbnail, author, caption, link, likes, hash) VALUES ('$id', '$created_time', '$thumbnail', '$author', '$caption', '$link', '$likes', '$hash')";
$result = mysql_query($query) or die(mysql_error());
mysql_close($con);
}
}

Why closing SQL connection at each loop iteration?
Why not simply do:
if ($author == 'USERNAME')
continue; // next iteration
$query = "INSERT IGNORE INTO pbr (id, created_time, thumbnail, author, caption, link, likes, hash)
VALUES ('$id', '$created_time', '$thumbnail', '$author', '$caption', '$link', '$likes', '$hash')";
$result = mysql_query($query) or die(mysql_error());
BTW you should bind parameters to your queries, or at least use mysql_real_escape_string() otherwise will have problems with values containing quotes (currently, you only do it for variable $caption, I guess that $link, $thumbnail and $username can contain single quotes as well).

Related

php page coming up blank when trying to access the database

I am having an issue where it seems my insert code is wrong but i do not know how to fix it.
It keeps resorting to my page being blank with no error_log and error reporting is not working either, below is the code
<?php
$connect = mysqli_connect("localhost","dfhdfhd","dfhdfh","fhgdfh");
$url = 'url';
$banner = 'banner';
$title = 'title';
$date = 'date';
$time = 'time';
$description = 'description';
$region = 'region';
$sponsors = 'sponsors';
mysqli_query($connect,"INSERT INTO information (url, banner, title, date, time, description, region, sponsors)
VALUES ('$url', '$banner', '$title', '$date' '$time', '$description', '$region', '$sponsors')";
?>
There's a few things wrong here.
First, a missing comma after '$date' and a missing bracket for your opening $connect,
Here:
mysqli_query($connect,"INSERT INTO information (url, banner, title, date, time, description, region, sponsors)
VALUES ('$url', '$banner', '$title', '$date', '$time', '$description', '$region', '$sponsors')");
Having checked for errors, it would have told you about those errors.
Consult these following links http://php.net/manual/en/mysqli.error.php and http://php.net/manual/en/function.error-reporting.php
Your present code is open to SQL injection. Use prepared statements, or PDO with prepared statements.
you should add error_reporting and show mysqli error if a query for some reason doesn't work:
<?php
error_reporting(-1);
$connect = mysqli_connect("localhost","dfhdfhd","dfhdfh","fhgdfh");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$url = 'url';
$banner = 'banner';
$title = 'title';
$date = 'date';
$time = 'time';
$description = 'description';
$region = 'region';
$sponsors = 'sponsors';
$result = mysqli_query($connect,"INSERT INTO information (url, banner, title, date, time, description, region, sponsors)
VALUES ('$url', '$banner', '$title', '$date', '$time', '$description', '$region', '$sponsors')");
if (!result)
{
echo("Error description: " . mysqli_error($connect));
}
?>
See for more information: http://www.w3schools.com/php/func_mysqli_error.asp
Also make sure that the php is not executed somewhere, where errors would be echoed but not visible because they are outside html or hidden by css.
You also forgot a comma inbetween '$data' and '$time' and closing the mysqli_query function.

Data not inserting into database to a table

I am trying to insert data into a database after the user clicks on a link from file one.php. So file two.php contains the following code:
$retrieve = "SELECT * FROM catalog WHERE id = '$_GET[id]'";
$results = mysqli_query($cnx, $retrieve);
$row = mysqli_fetch_assoc($results);
$count = mysqli_num_rows($results);
So the query above will get the information from the database using $_GET[id] as a reference.
After this is performed, I want to insert the information retrieved in a different table using this code:
$id = $row['id'];
$title = $row['title'];
$price = $row['price'];
$session = session_id();
if($count > 0) {
$insert = "INSERT INTO table2 (id, title, price, session_id)
VALUES('$id', '$title', '$price', '$session');";
}
The first query $retrieve is working but the second $insert is not. Do you have an idea why this is happening? PS: I know I will need to sanitize and use PDO and prepared statements, but I want to test this first and it's not working and I have no idea why. Thanks for your help
You're not executing the query:
$insert = "INSERT INTO table2 (id, title, price, session_id)
VALUES('$id', '$title', '$price', '$session');";
}
it needs to use mysqli_query() with the db connection just as you did for the SELECT and make sure you started the session using session_start(); seeing you're using sessions.
$insert = "INSERT INTO table2 (id, title, price, session_id)
VALUES('$id', '$title', '$price', '$session');";
}
$results_insert = mysqli_query($cnx, $insert);
basically.
Plus...
Your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements.
If that still doesn't work, then MySQL may be complaining about something, so you will need to escape your data and check for errors.
http://php.net/manual/en/mysqli.error.php
Sidenote:
Use mysqli_affected_rows() to check if the INSERT was truly successful.
http://php.net/manual/en/mysqli.affected-rows.php
Here's an example of your query in PDO if you'req planning to use PDO in future.
$sql = $pdo->prepare("INSERT INTO table2 (id, title, price, session_id) VALUES(?, ?, ?, ?");
$sql->bindParam(1, $id);
$sql->bindParam(2, $title);
$sql->bindParam(3, $price);
$sql->bindParam(4, $session_id);
$sql->execute();
That's how we are more safe.

Can't get mysql_insert_id() method to grab value I need

I'm trying to grab SID from the insert into the first table (stories) so I can insert that SID into the writing table in my second insert.
I think the way to do this is with mysql_insert_id(); after the first query, but the primary key that auto-increments is called SID. If mysql_insert_id() could grab that value I'd be all set.
What I am finding from a var_dump is that the $SID = mysql_insert_id(); is just returning the value "0" and I'm not sure why.
There is a column called ID in stores, but if it was grabbing that, the value would be "1". Either way, I wish this method could be written as mysql_insert_SID();
Any idea what I am doing wrong or how I can fix this? And yes, I know this is a deprecated approach, but first I want to figure out how before I worry about converting to PDO.
// Get values from form
$category = $_POST['category'];
$genre = $_POST['genre'];
$story_name = $_POST['story_name'];
$text = $_POST['text'];
$query = "INSERT INTO stories (ID, category, genre, story_name, active) VALUES
('$user_ID', '$category', '$genre','$story_name', '1')";
$result = mysql_query($query);
$SID = mysql_insert_id();
$SID2 = "select stories.SID from stories where stories.SID=$SID";
$query2 = "INSERT INTO writing (ID, SID, text, position, approved)
VALUES('$user_ID', '$SID2', '$text', '1','N')";
$result = mysql_query($query2);
Retrieves the ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT).
(http://php.net/manual/en/function.mysql-insert-id.php)
But you aren't executing any query (via mysql_query()). You're just assigning your query to a variable. Try following:
$query = "INSERT INTO stories (ID, category, genre, story_name, active) VALUES
('$user_ID', '$category', '$genre','$story_name', '1')";
mysql_query($query);
$SID = mysql_insert_id();
I think you've forgotten to execute the query most probably?
Try
$SID = mysql_insert_id();
after executing the query
$query = "INSERT INTO stories (ID, category, genre, story_name, active) VALUES
('$user_ID', '$category', '$genre','$story_name', '1')";
$result = mysql_query($query); // executing
$SID = mysql_insert_id(); // order of queries is important
If you cannot get the value through mysql_insert_id() then try SELECT LAST_INSERT_ID(). Of course there will be a value if you have executed an insert query with AUTOINCREMENT (which you haven't done yet)

cannot send the string into INSERT query

i have json as input
$page = file_get_contents('http://example.com/products.html');
$items = json_decode($page, true);
if i put echo $page; i get smth like this
{
"productlist":[
{
"id":"1",
"cat":"milk",
"prod_name":"happy milk",
"img_url":"http://example.com/milk.jpg"},
{
"id":"2",
"cat":"bread",
"prod_name":"black bread",
"img_url":"http://example.com/bread.jpg"},
then, i want to put it into MySQL DB
foreach($items['productlist'] as $item) {
$id = $item['id'];
$cat = $item['cat'];
mysqli_query($link, "INSERT INTO table (id, cat) VALUES ($id, $cat)") or die(mysql_error());
}
at this stage i get nothing. if i modify code into
foreach($items['productlist'] as $item) {
$id = $item['id'];
mysqli_query($link, "INSERT INTO table (id) VALUES ($id)") or die(mysql_error());
}
i get the table in DB filled - i have two rows with prod id. Ok, i want to insert into table the $cat = food
foreach($items['productlist'] as $item) {
$id = $item['id'];
$cat = 'food';
mysqli_query($link, "INSERT INTO table (id, cat) VALUES ($id, $cat)") or die(mysql_error());
}
yet this does not work, i get null result. but if i modify query into
foreach($items['productlist'] as $item) {
$id = $item['id'];
mysqli_query($link, "INSERT INTO table (id, cat) VALUES ($id, 'food')") or die(mysql_error());
}
i get the result i seek for - tho rows in table, filled with id and cat
id cat
1 food
2 food
does anyone know how to send string value into insert query via variable?
That doesn't work because cat is a String field, need to be between quotes '...'. try this :
mysqli_query($link, "INSERT INTO table (id, cat) VALUES ($id, '$cat')") or die(mysql_error());
or this :
mysqli_query($link, "INSERT INTO table (id, cat) VALUES ($id, ".$cat.")") or die(mysql_error());
First, I would suggest you to learn how to use prepared statements, as you are getting your strings outside of your code (it may contain some mysql injections).
To answer your question, you need to put some quotes around the variable you want to put in your query as it is a string, so mysql can interpret it correctly
mysqli_query($link, "INSERT INTO table (id, cat) VALUES ($id, '$cat')") or die(mysql_error());
Try this
mysqli_query($link, "INSERT INTO table (id, cat) VALUES ($id, ".mysql_real_escape_string($cat).")") or die(mysql_error());

PHP, Error 1136 : Column count doesn't match value count at row 1 [duplicate]

This question already has answers here:
PHP, MySQL error: Column count doesn't match value count at row 1
(3 answers)
Closed 9 years ago.
I get this Exception:
Error 1136 : Column count doesn't match value count at row 1
Structure of the table :
create table gb_entries (
id int(4) not null auto_increment,
username varchar(40) not null,
name varchar(40),
gender varchar(40),
dob int(40),
email varchar(40),
primary key (id)
);
With this PHP code:
// Add a new entry to the database
function addEntry($username, $name, $gender, $dob, $email) {
$connection = mysql_open();
$insert = "insert into gb_entries " .
"values ('$username', '$name', '$gender', '$dob', '$email')";
$result = # mysql_query ($insert, $connection)
or showerror();
mysql_close($connection)
or showerror();
}
// Return an array of database entries that contain $name anad $email
function getEntries($username,$name,$gender,$dob,$email) {
// Sanitise user input to prevent SQL injection attacks
$username = mysql_escape_string($username);
$name = mysql_escape_string($name);
$gender = mysql_escape_string($gender);
$dob = mysql_escape_string($dob);
$email = mysql_escape_string($email);
// Open connection and select database
$connection = mysql_open();
// Construct query
$query =
"select username, name, gender, dob, email from gb_entries where 0=0 ";
if (! empty($username)) {
$query .= "AND username LIKE '%$username%' ";
}
if (! empty($name)) {
$query .= "AND name LIKE '%$name%' ";
}
if (! empty($gender)) {
$query .= "AND gender LIKE '%$gender%' ";
}
if (! empty($dob)) {
$query .= "AND dob LIKE '%$dob%' ";
}
if (! empty($email)) {
$query .= "AND email LIKE '%$email%' ";
}
$query .= "ORDER BY id";
// echo $query;
// Execute query
$result = # mysql_query($query, $connection)
or showerror();
// Transform the result set to an array (for Smarty)
$entries = array();
while ($row = mysql_fetch_array($result)) {
$entries[] = $row;
}
mysql_close($connection)
or showerror();
return $entries;
}
What does the Exception mean?
As it says, the column count doesn't match the value count. You're providing five values on a six column table. Since you're not providing a value for id, as it's auto increment, it errors out - you need to specify the specific columns you're inserting into:
$insert = "insert into gb_entries (username, name, gender, dob, email) " .
"values ('$username', '$name', '$gender', '$dob', '$email')"
Also, I really hate that WHERE 0=0 line. I know why you're doing it that way, but I personally find it cleaner to do something like this (warning: air code!):
$query = "select username, name, gender, dob, email from gb_entries ";
$where = array();
if (! empty($username)) {
$where[] = "username LIKE '%$username%'"; // add each condition to an array
// repeat for other conditions
// create WHERE clause by combining where clauses,
// adding ' AND ' between conditions,
// and append this to the query if there are any conditions
if (count($where) > 0) {
$query .= "WHERE " . implode($where, " AND ");
}
This is personal preference, as the query optimizer would surely strip out the 0=0 on it's own and so it wouldn't have a performance impact, but I just like my SQL to have as few hacks as possible.
If the error is occurring when trying to insert a row to your table, try specifying the list of fields, in the insert query -- this way, the number of data in the values clause will match the number of expected columns.
Else, MySQL expects six columns : it expects the id column -- for which you didn't specify a value.
Basically, instead of this :
$insert = "insert into gb_entries " .
"values ('$username', '$name', '$gender', '$dob', '$email')";
Use something like that :
$insert = "insert into gb_entries (username, name, gender, dob, email) " .
"values ('$username', '$name', '$gender', '$dob', '$email')";
I had a similar problem. The column count was correct. the problem was that i was trying to save a String (the value had quotes around it) in an INT field. So your problem is probably coming from the single quotes you have around the '$dob'. I know, the mysql error generated doesn't make sense..
funny thing, I had the same problem again.. and found my own answer here (quite embarrassingly)
It's an UNEXPECTED Data problem (sounds like better error msg to me). I really think, that error message should be looked at again
Does modifying this line help?
$insert = "insert into gb_entries (username, name, gender, dob, email) " .
"values ('$username', '$name', '$gender', '$dob', '$email')";

Categories