There does not seem to be a repeat of this question and I feel this should be a simple fix.
I have tested the stored procedure and when adding the parameters it works fine,
I have also tested a simple SQL statement which also works as expected.
However, when I try to pass my variables into the statement, I get a "Zero results using SQL:" I have also tried to do this as just a prepared statement or as just pure SQL with my variables, but again it never stores anything in the database.
The debug output shows what I am trying to pass, but nothing goes into the database
Here is the full code
require_once (getcwd() . "/lib/dataLib.php");
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
if (isset($_POST['btnSubmit']))
{
$projectName = $_POST['projectName'];
$projectDescription = $_POST['projectDescription'];
$projectLink = $_POST['projectLink'];
addItemToDatabase($projectName, $projectDescription, $projectLink);
}
}
/********************************
* addItemToDatabase
*******************************/
function addItemToDatabase($name, $description, $link)
{
$projectLinkSanSpace = str_replace(' ', '', $link);
$projectLinkAsLink = "<a href='project/" . $projectLinkSanSpace . "'>" . $link . "</a>";
databaseConnection('programWork');
$conn = new mysqli(DBF_SERVER, DBF_USER, DBF_PASSWORD, DBF_NAME);
if ($conn -> connect_error)
{
die("Connection Failed!: " . $conn ->connect_error);
}
/*$sql = 'insert into projectList (
*projectName,
*projectDescription,
*projectPage,
*projectSource)
*Values ("Stuff", "Things", "Yeah", "Yeah")'; */
$sql = "call insertItemIntoWork($name, $description, $projectLinkAsLink, $projectLinkAsLink)";
$result = $conn->query($sql);
displayResult($result, $sql);
}
some notes on the code,
I am using a lib to call external functions which I did not copy/paste here, as I do not think they are relevant to the question. I also did not include the HTML bits which is just the form which should be fairly straight forward, and should work since the debug displayResults() shows values.
Bottom line question is, is there something procedural that I am screwing up here. I do not have to call a function I suppose but is this a situation where the variables are set after the query is ran?
UPDATE
I added an error handler per Jay below:
$echoSuccess = true;
$msg = "The query completed successfully";
if ($conn->query($sql) === TRUE)
{
if ($echoSuccess)
{
echo "<span class='errMsg'>" . $msg . " successful.</span><br />";
}
} else
{
echo "<strong>Error when: " . $msg . "</strong> using SQL: " . $sql . "<br />" . $conn->error;
//displayResult($result, $sql)
}
Saying there are errors in my SQL.
I think I can work those out and on account of that I do not think this question needs further answering, but rather illustrates the need of error handlers
So,
Thank you Jay Blanchard for pointing me in the right direction, turns out the spaces in my input were causing issues entering items into the database.
To fix this I had to add quotes around my parameters, though this seems like an odd requirement (perhaps I am missing something)
But it works now as expected.
Here are the alterations:
error_reporting(E_ALL); ini_set('display_errors', 1);
include "lib/style.php";
require_once (getcwd() . "/lib/coleSterlingLib.php");
//require_once (getcwd() . "/lib/jsFormInteraction.js");
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
if (isset($_POST['btnSubmit']))
{
$projectName = $_POST['projectName'];
$projectName = "'" . $projectName . "'";
$projectDescription = $_POST['projectDescription'];
$projectDescription = "'" . $projectDescription . "'";
$projectLink = $_POST['projectLink'];
$projectLink = "'" . $projectLink . "'";
addItemToDatabase($projectName, $projectDescription, $projectLink);
}
}
Note the $projectName = "'" . $projectName . "'";
Everything else stayed roughly the same
function addItemToDatabase($name, $description, $link)
{
$projectLinkSanSpace = str_replace(' ', '', $link);
$projectLinkAsLink = "<a href='project/" . $projectLinkSanSpace . "'>" . $link . "</a>";
databaseConnection('programWork');
$conn = new mysqli(DBF_SERVER, DBF_USER, DBF_PASSWORD, DBF_NAME);
if ($conn->connect_error)
{
die("Connection Failed!: " . $conn->connect_error);
}
//$sql = 'insert into projectList (projectName, projectDescription, projectPage, projectSource) Values ("Stuff", "Things", "Yeah", "Yeah")';
$sql = "call insertItemIntoWork($name, $description, $link, $link)";
//$result = $conn->query($sql);
$echoSuccess = true;
$msg = "The query completed successfully";
if ($conn->query($sql) === TRUE)
{
if ($echoSuccess)
{
echo "<span class='errMsg'>" . $msg . " successful.</span><br />";
}
} else
{
echo "<strong>Error when: " . $msg . "</strong> using SQL: " . $sql . "
<br />" . $conn->error;
//displayResult($result, $sql)
}
}
Related
I have a php file that gets some arguments to pass them to sql command. The first one is this:
if (isset ($_GET['pedio'])){
$pedio = " ` pedio ` LIKE '%" . $_GET['pedio'] . "%'";
}
With this form, the code is not running. The problem is "%'". If I remove % from "%'" then the code is running but it not what I want to take as expression. I tried:
$pedio = " `pedio` LIKE '%" . $_GET['pedio'] . chr(37) . "'";
but it didn't help. If i change chr(37) to chr(38) then the code is running but I have & in the end of the expression, not %. What is wrong with it? Any solutions?
EDIT:
my code:
<?php
if (isset($_GET['pedio'])) {
$pedio = " pedio LIKE '%$pedio%'";
}
if (isset($_GET['instit_type'])) {
if ($pedio != "") {
$instit_type = " AND";
}
$instit_type.= " instit_type = '" . $_GET['instit_type'] . "'";
}
if (isset($_GET['city'])) {
if ($pedio != "" || $instit_type != "") {
$city = " AND";
}
$city.= " city = '" . $_GET['city'] . "'";
}
echo "<p>" . $pedio . " , " . $instit_type . " , " . $city . "</p>";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM schools WHERE"; . $pedio;
// . $instit_type . $city . $category;
// echo $sql; $result = $conn->query($sql);
This modification is not working either:
if (isset ($_GET['pedio']))
{
switch ($_GET['pedio']){
case 1:
$pedio = " `pedio` LIKE '%1%'";
case 2:
$pedio = " `pedio` LIKE '%2%'";
case 3:
$pedio = " `pedio` LIKE '%3%'";
case 4:
$pedio = " `pedio` LIKE '%4%'";
}
}
Now, I noticed that
$pedio = " `pedio` = '%1%'";
code is running with no problem but the sql command is wrong and no results are returned. Replacing LIKE with = eliminates my problem? How is this possible? What is going on anyway?
Its worth an answer.
If your base Query starts with $sql = "SELECT * FROM schools WHERE";, you need to manipulate the current variable by adding a . before = src.
Full code example
ATTENTION This example isnt secure! Use prepared statements instead.
<?php
$baseSql = "SELECT * FROM school";
if(isset($_GET['pedio'])) {
$baseSql .= "WHERE pedio LIKE '%" . $_GET['pedio'] . "%'";
}
?>
You can try the following :
$variable = $_GET['pedio'];
$pedio = "pedio LIKE '%$variable%'";
The below php database query (from phpMyAdmin) only brings back one value (the first one or the oldest) into amcharts:
<?php
class custom_class2
{
var $charts; // reference to the calling object.
function customfunction2($content,$conf)
{
global $TSFE;
$TSFE->set_no_cache();
// do whatever you want here
// db connection
mysql_connect("hostname", "username", "password");
mysql_select_db("database name");
//db abfrage
$query = "
SELECT
YEAR(datetime) AS dy,
MONTH(datetime) -1 AS dm,
DAY(datetime) AS dd,
HOUR(datetime) AS th,
MINUTE(datetime) AS tm,
temp,
hum,
pressure
FROM stock1
ORDER BY datetime
";
// NEW: Variable definition
$zeilenzaehler = 1;
// output of the rows
$result = mysql_query($query) OR die("Error: $query <br>" . mysql_error());
while ($row = mysql_fetch_array($result))
{
// return
if ($zeilenzaehler != 1)
{
$content.= ",";
}
$content.= "{date: new Date(" . $row['dy'] . "," . $row['dm'] . "," . $row['dd'] . "," . $row['th'] . "," . $row ['tm'] . "),t:" . $row['temp'] . ",h:" . $row['hum'] . ",p:" . $row['pressure'] . "}";
return $content;
// Variable now on 2
$zeilenzaehler = 2;
}
}
}
?>
Everything else looks like its working fine. Many thanks for the help
You return the first found result in your while-loop. That is why you have just one result. Also as mysql_* functions are depreceted consider switching to
mysqli_* or PDO.
I am adding code from your request:
<?php
class custom_class2
{
var $charts; // reference to the calling object.
function customfunction2($content,$conf)
{
global $TSFE;
$TSFE->set_no_cache();
// do whatever you want here
// db connection
$mysqli = new mysqli("hostname", "username", "password", "database name");
if ($mysqli->connect_error) {
// your error handling here
}
//db abfrage
$query = "
SELECT
YEAR(datetime) AS dy,
MONTH(datetime) -1 AS dm,
DAY(datetime) AS dd,
HOUR(datetime) AS th,
MINUTE(datetime) AS tm,
temp,
hum,
pressure
FROM stock1
ORDER BY datetime
";
// NEW: Variable definition
$zeilenzaehler = 1;
// output of the rows
$result = $mysqli->query($query);
if (FALSE === $result) {
// you can put different error handling here
echo 'Error: ' . $query . ' ' . $mysql->error);
die();
}
$total = array();
while (NULL !== ($row = $result->fetch_array()))
{
// return
if ($zeilenzaehler != 1)
{
$content.= ",";
}
$content.= "{date: new Date(" . $row['dy'] . "," . $row['dm'] . "," . $row['dd'] . "," . $row['th'] . "," . $row ['tm'] . "),t:" . $row['temp'] . ",h:" . $row['hum'] . ",p:" . $row['pressure'] . "}";
// return $content;
// if you not return the first result you can gather results in array, so array will contain every row in result, $total[0], $total[1]...:
// $total[] = $content; or:
$total[] = "{date: new Date(" . $row['dy'] . "," . $row['dm'] . "," . $row['dd'] . "," . $row['th'] . "," . $row ['tm'] . "),t:" . $row['temp'] . ",h:" . $row['hum'] . ",p:" . $row['pressure'] . "}";
// Variable now on 2
$zeilenzaehler = 2;
}
$result->free();
return $total; // return all rows
}
}
?>
Okay so my code works pretty well so far, it all goes through, my only problem is that when I try and print the unordered list and it's contents I get nothing. When I view my source code I have <ul> </ul>. There's a space, so surely something is happening.
This is my code, I have commented it slightly but what's happening is obvious:
$uname = mysqli_real_escape_string($link, $_SESSION['Username']); //Get username ready
$sql = mysqli_query($link, "SELECT * FROM users WHERE Username = '" . $uname . "'"); //SQL Query result
if(!$sql)
{
echo "Error retrieving User ID. Please try again. MySQL Error: " . mysqli_error($link);
}
elseif($row = mysqli_fetch_assoc($sql))
{
$uid = $row['UserID']; //Obtain UserID
}
else
{
echo "Error: " . mysqli_error($link) . "<br />" . $uname . " / " . $sql . " / " . $uid;
}
mysqli_free_result($sql);
$sql = mysqli_query($link, "SELECT * FROM auditions"); //Get everything from the auditions table
if(!$sql)
{
echo "Error retrieving auditions. Please try again later. Error: " . mysqli_error($link);
}
elseif($row = mysqli_fetch_assoc($sql))
{
if(mysqli_num_rows($sql)==0)
{
echo "Sorry, there are currently no open auditions. Please try back at a later date.";
}
else
{
echo "<ul>";
while($row = mysqli_fetch_assoc($sql))
{
echo "<li><a href='auditions.php?id=" . $row['AudID'] . "'>" . $row['AudName'] . "</a></li>";
}
echo "</ul>";
}
}
else
{
echo "Error: " . mysqli_error($link);
}
Where am I going wrong? The only thing it doesn't do is actually pick up any results and I've put some data into the table so there are entries! Otherwise it would say there aren't any. I've reversed this so it shows the message if there aren't 0 entries and that works. What am I doing wrong guys?
Thanks in advance.
You are fetching the result twice. Instead, only fetch the result in the while loop:
<?php
$sql = mysqli_query($link, "SELECT * FROM auditions"); //Get everything from the auditions table
if(!$sql)
{
echo "Error retrieving auditions. Please try again later. Error: " . mysqli_error($link);
}
else{
if(mysqli_num_rows($sql)==0)
{
echo "Sorry, there are currently no open auditions. Please try back at a later date.";
}
else
{
echo "<ul>";
while($row = mysqli_fetch_assoc($sql))
{
echo "<li><a href='auditions.php?id=" . $row['AudID'] . "'>" . $row['AudName'] . "</a></li>";
}
echo "</ul>";
}
}
?>
See this link for more information regarding mysql_fetch_assoc
my code partially works in ELSE part below. What I mean partially is it doesn't INSERT INTO table but since all verification stages are correct, it redirects to thanks page.What I normally expect is both. Insert into table A N D then go to thanks page.I thought my situation is about the prepared statement so I studied http://php.net/manual/en/mysqli.quickstart.prepared-statements.php but I couldn't solve my case. I am getting NO notice, warning or error. but my table is still empty. Can you help with my fault(s) please?ThanksBR
header( "HTTP/1.1 303 See Other" );
if ($_SESSION['hatalar'] != '')
{
$sonraki_sayfa = sitenin_koku.'yazılar/'.$_SESSION['spesifik_yazi_url'];
header('Location: ' . $sonraki_sayfa);
}
else //verification passed. save the comment + redirect to thanks page.
{
/* YORUMU TABLOYA YAZDIRALIM */
$sorgum = "INSERT INTO tb_yorumlar (kolon_yorumcu_isim, kolon_statu, kolon_yorum, kolon_hangi_yazara, kolon_hangi_basliga, kolon_yorum_tarihi, kolon_ip) VALUES (?, ?, ?, ?, ?, NOW(), ?)";
if ($beyan = $db_baglanti->prepare($sorgum))
{
/* give their values to parameters */
$bindparametre1 = $_POST['yf-isim'];
$bindparametre2 = 'onay';
$bindparametre3 = $_POST['yf-mesaj'];
$bindparametre4 = $_SESSION['spesifik_yazi_yazar'];
$bindparametre5 = $_SESSION['spesifik_yazi_baslik'];
$bindparametre6 = $_SERVER['REMOTE_ADDR'];
/* bind parameters */
if (!$beyan -> bind_param("ssssss", $bindparametre1, $bindparametre2, $bindparametre3, $bindparametre4, $bindparametre5, $bindparametre6))
{echo "parametre atama hatası: (" . $beyan->errno . ") " . $beyan->error;}
/* execute statement */
if (!$beyan->execute())
{echo "Gerçekleştirme hatası: (" . $beyan->errno . ") " . $beyan->error ;}
}
else {echo "Hazırlama hatası: (" . $db_baglanti->errno . ") " . $db_baglanti->error;}
/* TEŞEKKÜR SAYFASINA YÖNLENDİRELİM */
$sonraki_sayfa = sitenin_koku.'yorumunuz-için-teşekkür-ederim';
header('Location: ' . $sonraki_sayfa);
}
I would comment out the header location part (see below) and echo out the values - make sure that the values you're inserting are actually filled (not null).
if ($beyan = $db_baglanti->prepare($sorgum)) {
/* give their values to parameters */
$bindparametre1 = $_POST['yf-isim'];
$bindparametre2 = 'onay';
$bindparametre3 = $_POST['yf-mesaj'];
$bindparametre4 = $_SESSION['spesifik_yazi_yazar'];
$bindparametre5 = $_SESSION['spesifik_yazi_baslik'];
$bindparametre6 = $_SERVER['REMOTE_ADDR'];
if (!$beyan->bind_param("ssssss", $bindparametre1, $bindparametre2, $bindparametre3, $bindparametre4, $bindparametre5, $bindparametre6)) {
echo "parametre atama hatas?: (" . $beyan->errno . ") " . $beyan->error;
}
if (!$beyan->execute()) {
echo "Gerçekles,tirme hatas?: (" . $beyan->errno . ") " . $beyan->error ;
}
}
else {
echo "Haz?rlama hatas?: (" . $db_baglanti->errno . ") " . $db_baglanti->error;
}
/* TES,EKKÜR SAYFASINA YÖNLENDI.RELI.M */
$sonraki_sayfa = sitenin_koku.'yorumunuz-için-tes,ekkür-ederim';
//header('Location: ' . $sonraki_sayfa);
echo $bindparametre1 . "<br>";
echo $bindparametre2 . "<br>";
echo $bindparametre3 . "<br>";
echo $bindparametre4 . "<br>";
echo $bindparametre5 . "<br>";
echo $bindparametre6 . "<br>";
PHP sessions work by default with my configuration, if I just go session_start() and try the standard session increment test it works.
if (!isset($_SESSION['count'])) {
$_SESSION['count'] = 0;
} else {
$_SESSION['count']++;
}
However I want to use a MySQL table for session storage. I've put together my sessions.php file with all the functions, copied them right out of a book like a n00b, and the functions work (affect the database) if I call them like regular functions, but using the standard test above does not work. It sets the session for just the page load, and no change in the database. I put a line in each function to log each call, and the log reflects that the functions are being called by session_start().
Here's what my code looks like:
session_module_name("user");
session_set_save_handler("session_open", "session_close",
"session_read", "session_write", "session_remove", "session_gc");
session_start();
session_open, etc, being the name of my functions. I've even tried another set of functions out of an o'rly example, and got the same results.
Any ideas why? session_register() also yields the same results.
EDIT: here are the actual functions, I apologize for the length, but I log everything in dev.
function session_db(){
return("my_db_name");
}
function session_table(){
return("sessions_table");
}
function session_log($message){
if($file = fopen($application["siteroot"] . 'log/session.txt', "a")){
fwrite($file, date("Y-m-d H:i:s ") . $message . "\n");
fclose($file);
}
}
function session_open($path, $name){
session_log("session_open");
return(true);
}
function session_close(){
session_log("session_close");
return(true);
}
function session_read($id){
session_log("session_read");
if(!mysql_select_db(session_db())){
session_log("session_read select database error: " . mysql_error());
return(false);
}
$sql = "select * from " . session_table() . " where id='" . $id . "'";
if(!$result = mysql_query($sql)){
session_log("MySQL error: " . mysql_error() . " with SQL: " . $sql);
return(false);
}
if(mysql_num_rows($result)){
session_log("MySQL query returned " . mysql_num_rows($result) . "rows.");
$row = mysql_fetch_assoc($result);
session_log("session_read returned " . $row["data"]);
return($row["data"]);
}
else{
session_log("session_read found zero rows with SQL: " . $sql);
return("");
}
}
function session_write($id, $data){
session_log("session_write");
if(!mysql_select_db(session_db())){
session_log("session_write select database error: " . mysql_error());
return(false);
}
$sql = "update " . session_table() . " set data = '" . addslashes($data) . "', time=null";
if(isset($PHP_AUTH_USER)){
$sql .= ", user='" . addslashes($PHP_AUTH_USER) . "'";
}
$sql .= " where id='" . $id . "'";
if(!$result = mysql_query($sql)){
session_log("session_write error " . mysql_error() . " with SQL: " . $sql);
return(false);
}
if(mysql_affected_rows()){
session_log("session_write update affected " . mysql_affected_rows() . " rows with SQL: " . $sql);
return(true);
}
session_log("session_write updated zero rows with SQL: " .$sql);
$sql = "insert into " . session_table() . "(data,id) values('" . addslashes($data) . "','" . $id . "')";
if(!$result = mysql_query($sql)){
session_log("session_write error " . mysql_error() . "with SQL: " . $sql);
return(false);
}
else{
session_log("mysql_write inserted with SQL: " . $sql);
return(true);
}
}
function session_remove($id){
session_log("session_remove");
if(!mysql_select_db(session_db())){
session_log("session_remove select database error: " . mysql_error());
return(false);
}
$sql = "delete " . session_table() . " where id='" . $id . "'";
if($result = mysql_query($sql)){
session_log("MySQL query delete worked");
return(true);
}
else{
session_log("MySQL update error: " . mysql_error() . " with SQL: " . $sql);
return(false);
}
}
function session_gc($life){
session_log("session_gc");
if(!mysql_select_db(session_db())){
session_log("session_gc select database error: " . mysql_error());
return(false);
}
$sql = "delete " . session_table() . " where time < '" . date("YmdHis", time() - $life) . "'";
print("session_gc sql: " . $sql);
if($result = mysql_query($sql)){
session_log("session_gc deleted " . mysql_affected_rows() . " rows.");
return(true);
}
else{
session_log("session_gc error: " . mysql_error() . " with SQL: " . $sql);
return(false);
}
}
I don't think you need the call to session_module_name, try commenting it out and see what happens.
There are a couple of things...
We might need to see, at the very least, the actual functions.
You probably want to register a shutdown function, your writes are probably being called too late to save to the database.
register_shutdown_function('session_write_close');
Just to clarify, the reason for the above is that the write and close functions are normally called after objects are destroyed. This call will ensure that these are made before object destruction.