PHP MySQL INSERT query no longer works (was working yesterday) - php

I have a problem with an INSERT query.
Here is the problem:
Yesterday I was using this code to upload data, it was working fine. Today, when I hit submit on the form, it just shows a blank page. No errors, just blank. Nothing in the error log. All SELECT queries are working fine, so the SELECT Count(id) query still works.
Here is what I have tried:
Re-uploading to server
syntax adjustments eg '".$v.'" instead of '$v'
adding print lines to check that none of the variables are null. All is okay, all data is present just before the INSERT query.
Test insert via PHP my admin, all okay
The function call is correct - it is and remains unchanged from Yesterday
The function takes a list of species, a family and a genus, then adds them to the database.
Here is the code (the un-santised version - both were working yesterday):
error_reporting(E_ALL);
ini_set('display_errors', '1');
function submit($family, $genus, $species){
//require statement
require 'databaseConnect.php';
//get num of species
if(!($result = mysql_query("SELECT Count(id) as num FROM speciesList", $connection))) mysql_error();
$nums = mysql_fetch_row($result);
$num=$nums[0];
//parse species
$holder="";
$array = Array();
while(strlen($species)!=0){
if($species[0]==';'){
$array[] = $holder;
$holder="";
}else{
$holder = $holder . $species[0];
}
$species=substr($species, 1);
}
foreach($array as $v){
$num++;
if(!(mysql_query("INSERT INTO speciesList VALUES($num, '$family', '$genus', '.$v')", $connection))){
mysql_error();
}else{
print "success ";
}
}
mysql_close($connection);
}
Thank you very much in advance, this problem is rather mysterious to me!
Em

You never ever want to use string replacement with parameters to build SQL statements as it leaves you vulnerable to SQL injection attacks. Instead, bind your parameters.
Your code isn't returning an error because you call mysql_error() and ignore the return value. It returns the error string, so you want your code to be more like this:
if(!(mysql_query("INSERT INTO speciesList VALUES($num, '$family', '$genus', '.$v')", $connection))){
print_r( mysql_error() );
}else{
print "success ";
}
If you need help understanding the error once you see it, please post it here.

if(!(mysql_query("INSERT INTO speciesList VALUES($num, '$family', '$genus', '.$v')", $connection))){
echo mysql_error();
}else{
There maybe other things that are amiss, but the mysql_error() function returns a string. Your script needs to take some action to display the string.
I find that a better way of doing this is to construct the variables separately, so they can be displayed. And I'm not sure you want that dot before $v. See if this makes sense to you.
foreach($array as $v)
{
$num++;
$sql = "INSERT INTO speciesList VALUES($num, '$family', '$genus', '$v')";
$res = mysql_query($sql);
if (!$res) die("FAIL: $sql BECAUSE: " . mysql_error());
echo "<br/>SUCCESS: $sql";
}

Related

PHP variable is not working with WHERE clause

My query is not working when I use the variable in the WHERE clause. I have tried everything. I echo the variable $res, it shows me the perfect value, when I use the variable in the query the query is not fetching anything thus mysqli_num_rows is giving me the zero value, but when I give the value that the variable contains statically the query executes perfectly. I have used the same kind of code many times and it worked perfectly, but now in this part of module it is not working.
Code:
$res = $_GET['res']; // I have tried both post and get
echo $res; //here it echos the value = mahanta
$query = "SELECT * FROM `seller` WHERE `restaurant` = '$res'"; // Here it contains the problem I have tried everything. Note: restaurant name is same as it is in the database $res contains a value and also when I give the value of $res i.e. mahanta in the query it is then working.
$z = mysqli_query($conn, $query);
$row2 = mysqli_fetch_array($z);
echo var_dump($row2); // It is giving me null
$num = mysqli_num_rows($z); // Gives zero
if ($num > 0) {
while ($row2 = mysqli_fetch_array($z)) {
$no = $row2['orders'];
$id = $res . $no;
}
}
else {
echo "none selected";
}
As discussed in the comment. By printing the query var_dump($query), you will get the exact syntax that you are sending to your database to query.
Debugging Tip: You can also test by pasting the var_dump($query) value in your database and you will see the results if your query is okay.
So update your query syntax and print the query will help you.
$query = "SELECT * FROM `seller` WHERE `restaurant` = '$res'";
var_dump($query);
Hope this will help you and for newbies in future, how to test your queries.
Suggestion: Also see how to write a mysql query syntax for better understanding php variables inside mysql query
The problem is the way you're using $res in your query. Use .$res instead. In PHP (native or framework), injecting variables into queries need a proper syntax.

why does query in mysql works but query in php doesnt and its only due to specific columns

I'm trying to do a simple query:
SELECT
job_title,
job_description,
job_tasks,
technology_skills,
job_activities
FROM
careeryou_db3
WHERE
Job_Interests = " CIE"
It works perfectly in mysql giving me this result:
http://imgur.com/a/E9yv3
However, when I use this in my PHP it returns an empty data set. I did some troubleshooting by trying to query the columns one by one and it works(returning the correct results respectively.
SELECT
job_title, job_description, job_tasks
FROM
careeryou_db3
WHERE
Job_Interests = " CIE"
Apparently, when I try to query anything from the columns of [technology_skills] OR [job_activities], the php result would return as BLANK. Does anyone have any idea why? this is strange and im kinda new to this
This is my php code:
$query = 'SELECT job_title,job_description,job_tasks FROM careeryou_db3 WHERE Job_Interests = " CIE" ';
$resultset = mysql_query($query, $connection);
$records = array();
while($r = mysql_fetch_assoc($resultset)){
$records[] = $r;
}
echo json_encode($records);
I can't see any error on your sql syntax. Can you check the mysql logs for better error information?
See here for details
https://dev.mysql.com/doc/refman/5.7/en/error-log.html
[mysqld]
log_error=/var/log/mysql/mysql_error.log
general_log_file=/var/log/mysql/mysql.log
It would help how you call the mysql, place the query build code as example.
It might be worth adding these lines for extra debugging to ensure your connection and query is successful.
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)) {
....
It is because of the data in those columns that are conflicting with the PHP. Apparently this "—" cannot get parse into PHP which explains why the query works only in phpMyAdmin and not my PHP script.

Creating a dynamic MySQL query from URL paramaters

I am really trying to wrap my head around this and failing miserably. What I want to do it build a MySQL query based on the URL parameters passed by the URL. I am trying to create a re usable dynamic script that can do what it needs to do based on the URL parameter.
This is what I have come up with, and it appears that it does what it is supposed to do (no errors or anything) but nothing actually gets inserted in the database. I know somewhere I have made a dumb mistake (or thought something out wrong) so hopefully one of you guys can point me in the right direction.
Thanks!
//List all possible variables you can expect the script to receive.
$expectedVars = array('name', 'email', 'score', 'age', 'date');
// This is used for the second part of the query (WHERE, VALUES, ETC)
$fields = array('uName','uEmail','uScore','uAge','uDate');
// Make sure some fields are actually populated....
foreach ($expectedVars as $Var)
{
if (!empty($_GET[$Var]))
{
$fields[] = sprintf("'%s' = '%s'", $Var, mysql_real_escape_string($_GET[$Var]));
}
}
if (count($fields) > 0)
{
// Construct the WHERE Clause
$whereClause = "VALUES " . implode(",",$fields);
//Create the SQL query itself
$sql = ("INSERT INTO $mysql_table ($fields) . $whereClause ");
echo "1"; //It worked
mysql_close($con);
}
else
{
// Return 0 if query failed.
echo "0";
}
?>
You missed mysql_query($sql):
if(!mysql_query($sql)){
//die(mysql_error());
}
Please consider to use PDO or My SQLi using parametrize query because mysl_* function depreciated.
Your SQL is all wrong. You're using the field = value syntax for an INSERT, then you're concatenating an array as if it were a string ($fields), and you're missing a couple of parentheses around the values.
a couple of things: i've found for php <-> mysql its important to see what's going into mysql and experiement directly with those queries in phpmyadmin when i get stuck.
1 - in my code I output mysql_error() when the query fails or when a debug flag is set. this usually explains the sql issue in a way that can point me to a misspelled field name etc...
2 - this way i can feed that mysql query directly into phpmyadmin and tweak it until it gives me the results i want. (while i'm there i can also use explain to see if i need to optimize the table)
specifics in your code. unlike C languages sprintf is implied. here's how i'd write your code:
// List all possible variables you can expect the script to receive.
$expectedvars = array('name', 'email', 'score', 'age', 'date');
// This is used for the second part of the query (WHERE, VALUES, ETC)
// $fields = array('uName','uEmail','uScore','uAge','uDate');
$fields = array();
// Set only the variables that were populated ...
foreach ($expectedvars as $var) {
if (!empty($_GET[$var])) {
$name = "u" + ucwords($var); // convert var into mysql field names
$fields[] = "{$name} = " . mysql_real_escape_string($_GET[$var]);
}
}
// only set those fields which are passed in, let the rest use the mysql default
if (count($fields) > 0) {
// Create the SQL query itself
$sql = "INSERT INTO {$mysql_table} SET " . implode("," , $fields);
$ret = mysql_query($sql);
if (!$ret) {
var_dump('query_failed: ', $sql, $ret);
echo "0"; // Query failed
} else {
echo "1"; // It worked
}
} else {
// Return 0 if nothing to do
echo "0";
}
mysql_close($con);

php array to string not working online server

I have a problem. I have an array of values from database, when I try to pass it to a string with commas, it works fine on my localhost, but when I upload it to my online server, the string doesn't show any values. For example: select from table where in (,,) only shows the commas and in my xampp server it works excellent. Any ideas what this can be?
Here's the code:
<?php
$sql = "select id from users where gid = 1";
$result = mysql_query( $sql);
$cat_titles=array();
while( $row=mysql_fetch_assoc($result) )
{
$cat_titles[] = $row['id '];
// do stuff with other column
// data if we want
}
mysql_free_result( $result );
echo "<p>\n";
foreach($cat_titles as $v)
{
$cat_titles[]= $row['id'];
}
echo "</p>\n";
$cat_titles = implode(',',$cat_titles);
$cat_titles = substr($cat_titles,0,-2);
echo $cat_titles;
echo "select * from users where IN (".$cat_titles.")";
?>
A number of potential issues here:
You are not handling error conditions around you database access, so if you are having issue with your queries you would never know.
Your second select query doesn't specify a field in the WHERE clause, so it will never work
This section of code does absolutely nothing and is in fact where you problem likely lies.
foreach($cat_titles as $v)
{
$cat_titles[]= $row['id'];
}
Here $row['id'] won't have a value, so you are basically looping throguh your existing array and appending empty value to new indexes.
In all likelihood you could do this with a single query, it might help if you explain what you are actually trying to do.
You should not be using mysql_* functions. They are deprecated. Use mysqli or PDO instead.

pg_query() seems to not execute queries in a loop

I'm converting a site from MySQL to Postgres and have a really weird bug. This code worked as-is before I switched the RDBMS. In the following loop:
foreach ($records as $record) {
print "<li> <a href = 'article.php?doc={$record['docid']}'> {$record['title']} </a> by ";
// Get list of authors and priorities
$authors = queryDB($link, "SELECT userid FROM $authTable WHERE docid='{$record['docid']}' AND role='author' ORDER BY priority");
// Print small version of author list
printAuthors($authors, false);
// Print (prettily) the status
print ' (' . nameStatus($record['status']) . ") </li>\n";
}
the FIRST query is fine. Subsequent calls don't work (pg_query returns false in the helper function, so it dies). The code for queryDB is the following:
function queryDB($link, $query) {
$result = pg_query($link, $query) or die("Could not query db! Statement $query failed: " . pg_last_error($link));
// Push each result into an array
while( $line = pg_fetch_assoc($result)) {
$retarray[] = $line;
}
pg_free_result($result);
return $retarray;
}
The really strange part: when I copy the query and run it with psql (as the same user that PHP's connecting with) everything runs fine. OR if I copy the meat of queryDB into my loop in place of the function call, I get the correct result. So how is this wrapper causing bugs?
Thanks!
I discovered that there was no error output due to having my php.ini misconfigured; after turning errors back on I started getting output, I got things like18 is not a valid PostgreSQL link resource. Changing my connect code to use pg_pconnect() (the persistent version) fixed this. (Found this idea here.)
Thanks to everyone who took a look and tried to help!

Categories