I am working on a class where I want to check if everything is filled in and if everything is filled in then insert into the database, but I am stuck on how I can insert within my class so I hope you guys could help me. I never got any errors of this problem.
Here is the code:
<?php
class clsCatCheck
{
private $catName;
public function __construct($catName)
{
$this->setCatName($catName);
}
public function setCatName($catName)
{
$connect = new PDO('mysql:host=hostname;dbname=dbname', "username", "password");
$select = $connect->prepare('SELECT * FROM category');
$row = $select->fetch();
if (isset($_POST['addCat'])) {
if (empty($_POST['catName'])) {
throw new Exception('Geen categorienaam is ingevuld<br />');
}
//if (strlen($_POST['catName'] <= 4)) {
// throw new Exception('De categorienaam moet minimaal 4 letters of langer zijn<br />');
//}
if ($_POST['catName'] == $row[1]) {
throw new Exception('Deze categorienaam bestaat al<br />');
}
}
else {
$query = $connect->prepare("INSERT INTO category (catName) VALUES (:catName = catName)");
$query->bindParam(':catName', $_POST['catName'] ,PDO::PARAM_STR);
$query->execute();
}
$this->catName = $catName;
}
public function getCatName()
{
return $this->catName;
}
}
Already thanks for helping.
If you want more code from me just ask.
You are not binding parameters correctly.
Corrected code:
$query = $connect->prepare("INSERT INTO category (catName) VALUES (:catName)");
$query->bindParam(':catName', $_POST['catName'] ,PDO::PARAM_STR);
Related
I have this code on "insert.php":
if ($stmt = $GLOBALS['mysqli']->prepare("INSERT INTO table1(iduser, title, msg, anonim, ip, iduniversity) VALUES (?,?,?,?,?,?)")) {
$stmt->bind_param("issisi", $_SESSION['iduser'], $_POST['title'], $_POST['msg'], $anonim, getIP(), $_SESSION['iduniversity']);
if ($stmt->execute()) {
$idmsg = $GLOBALS['mysqli']->insert_id;
$i = 0;
$stmt2 = $GLOBALS['mysqli']->prepare("INSERT INTO tag(idmsg, tag) VALUES(?,?)");
foreach ($tags as $tag) {
if ($tag != '') {
$stmt2->bind_param("is", $idmsg, $tag);
if ($stmt2->execute()) {
$i++;
}
}
}
$stmt2->close();
$stmt->close();
mysqli_close($GLOBALS['mysqli']);
sendFile($idmsg);
header("Location: /public/watch_msg.php?idmsg=" . $idmsg);
exit();
} else {
exit("Ops! Ocorreu algum erro. COD1370");
}
} else {
exit("Ops! Ocorreu algum erro. COD1371");
}
So, everything is working fine, except that sometimes when it redirects to "watch_msg.php" the message seems not to be on the database yet. When this happens, as soon as I refresh the page, everything is there!
First thing I thought is that there could be a race-condition somewhere, but I read in another question that PHP is sequential, and as I close both statements and connection before the redirect (so that used tables should be unlocked), why i'm getting this result somethimes? What i'm doing wrong?
Also, no functions outputs anything, but "sendFile" saves an image if the user sends one, so headers should be fine (it also gives me the error when I comment the function).
Code on watch_msg:
$msg = NULL;
$tags = NULL;
$coments = NULL;
$data_high = date("Y-m-d H:i:s");
$iduser;
if ($loggedin) { //If logged in
$idmsg = filter_input(INPUT_GET, 'idmsg', FILTER_SANITIZE_STRING);
$iduser = $_SESSION['iduser'];
$query = "SELECT * FROM table1 WHERE iduser = ? AND idmsg = ? AND datemsg < ?";
$stmt = $GLOBALS['mysqli']->prepare($query);
$stmt->bind_param("iis", $iduser, $idmsg, $data_high);
if ($stmt->execute()) {
$msg = mysqli_fetch_assoc($stmt->get_result());
if ($msg === NULL) {
exit('This message doesn\'t exists');
}
...
} else {
echo "Error.";
}
}
I'm working on a project, im trying to assign two variables but I keep getting NULL when i var_dump() the variables
my code:
User.php
<?php
class TheUser
{
public $isMember = 0;
public $userID = 0;
public $info = [];
public $user_name = 'guest';
public function __construct()
{
global $mysqli,$config;
if($_SESSION['the_user'] &&mysqli_num_rows($query = mysqli_query($mysqli,'SELECT * FROM `users` WHERE `username` = \''.$_SESSION['the_user'].'\' '))) {
{
$this->info = mysqli_fetch_assoc($query);
$this->user_name = $this->info['username'];
$this->isMember = 1;
$this->userID = $this->info['id'];
}
}}
function LoginUser()
{
global $mysqli,$config,$_SESSION;
if($_SESSION['the_user']) {die('go away');}
if(!$_POST['username']) { die('username already exist'); }
if(!$_POST['password']) { die('password is required...'); }
if(!mysqli_num_rows($query = mysqli_query($mysqli,'SELECT `id`, `username`, `email`, `password` FROM `users` WHERE `username` = \''.$_POST['username'].'\''))) { die('0: El usuario ingresado no existe'); }
$r = mysqli_fetch_row($query);
if($r[3] != $_POST['password']) { die('0: La contraseƱa es incorrecta'); }
//if($r[3] != $_POST['password']){ die(' incorrect password'); }
$_SESSION['the_user'] = $r[1];
$theUser = $_SESSION['the_user'];
$this->isMember = 1;
$this->userID = $r[0];
die('ok');
}
}
then my controller look like:
<?php
include __DIR__.'/../../header.php';
$templateToShow = 'login';
$WhatLevel = 0;
$isAjax = empty($_GET['ajax']) ? 0 : 1;
$KeepGoing = true;
$PageTitle = $config['title'];
if($_POST)
{
$ala = $LU->LoginUser();
}
//session_destroy();
var_dump($_SESSION['the_user']);
var_dump($isMember);
var_dump($userID);
if(empty($isAjax) && !$templateToShow)
{
echo $twig->render('index.twig.php');
}else{
echo $twig->render("$templateToShow.twig.php",[
]);
}
I know there is no security implemented YET... I'm just doing it this way first so I can fix it later.
What I'm trying to do is to
assign $isMember to 1
assign $userID to the user id that i got from the database
I do not know why but I keep getting this :
string(6) "admin" int(0) int(0)
I'm sorry if i do not make sense, but it is 3 am and im so frustrated :/
In your code you used $_SESSION, so you have to add session_start() at the begin of each php files.
And you want to use variable in other class of another file, so you have to include that file and with this code,
$user = new TheUser;
$user->$isMember
Got some code here. Been stuck on it for ages and I can't seem to get around the error.
<?PHP
error_reporting(E_ALL);
ini_set('display_errors',1);
$mysqli = new mysqli('localhost', 'username', 'password', 'table');
$statsObjects = array();
$collatedObjects = array();
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
Global $areRows;
$areRows = 2;
if( $result = $mysqli->query("SELECT * FROM stats WHERE collated = 0", MYSQLI_USE_RESULT) )
{
while($row = $result->fetch_assoc())
{
array_push($statsObjects,
new Statistic(
$row['ID'],
$row['player_GUID'],
$row['shots_fired'],
$row['shots_hit'],
$row['damage_done'],
$row['damage_taken'],
$row['friendly_damage_done'],
$row['friendly_damage_taken']
));
}
$success = true;
} //end if
$result->free_result();
if($success)
{
foreach($statsObjects as $stat)
{
$statsGuid = $stat->getGuid();
$query = "SELECT COUNT(*) AS total FROM collatedStats WHERE player_GUID = '" . $statsGuid . "'";
if( $result2 = $mysqli->query($query, MYSQLI_USE_RESULT) )
{
$value = $result2->fetch_assoc();
$rows = $value['total'];
if($rows > 0)
{
$areRows = 1;
}
else
{
$areRows = 0;
}
}
else
{
echo("Error <br/>");
echo($mysqli->error);
}
if($areRows == 1)
{
echo("Found a row! <br/>");
}
elseif($areRows == 0)
{
Echo("No rows found. =) <br/>");
}
} //end foreach
}
//OBJECT
class Statistic
{
var $GUID;
var $shotsfired;
var $shotshit;
var $damagedone;
var $damagetaken;
var $friendlydamagedone;
var $friendlydamagetaken;
var $ID;
function Statistic($ID, $GUID, $fired, $hit, $ddone, $dtaken, $fddone, $fdtaken)
{
$this->id = $ID;
$this->GUID = $GUID;
$this->shotsfired = $fired;
$this->shotshit = $hit;
$this->damagedone = $ddone;
$this->damagetake = $dtaken;
$this->friendlydamagedone = $fddone;
$this->friendlydamagetaken = $fdtaken;
}
function getID()
{
return $this->ID;
}
function getGuid()
{
return $this->GUID;
}
function getShotsFired()
{
return $this->shotsfired;
}
function getShotsHit()
{
return $this->shotshit;
}
function getDamageDone()
{
return $this->damagedone;
}
function getDamageTaken()
{
return $this->damagetaken;
}
function getFriendlyDDone()
{
return $this->friendlydamagedone;
}
function getFriendlyDTaken()
{
return $this->friendlydamagetaken;
}
function getAccuracy()
{
if($shotsfired == 0)
{
$accuracy = 0;
}
else
{
$accuracydec = $shotshit / $shotsfired;
$accuracy = $accuracydec * 100;
}
return $accuracy;
}
}
Basically every time i run the code, it keeps coming up with the error "Commands out of sync; you can't run this command now". I've spent 2 days trying to fix it - following peoples instructions about freeing the result before running the next one. I even used a prepared statement in previous code however it didn't work either - this is newly written code in an attempt to get it working. All the reading i've done suggests that this error happens when you try to run an sql command while another one is still receiving data - however i've called my first query, stored it all in an array - and then i'm looping through the array to get the next lot of data..and that's giving me an error, which is where i'm getting confused.
Any help would be appreciated!
Thank You to #andrewsi for his help - it turns out that having the MYSQLI_USE_RESULT inside SELECT * FROM stats WHERE collated = 0", MYSQLI_USE_RESULT was giving me the error. Removing that allowed me to do my code normally.
Hopefully this helps others that may have the same problem. =)
<?php
$mysqli=mysqli_connect("localhost","root","","politicalforum");
$query="SELECT query_title FROM administrator";
$query.="SELECT thread_id FROM threads";
if($mysqli->multi_query($query))
{
do
{
if($result=$mysqli->store_result())
{
while($row=$result->fetch_row())
{
printf("%s\n",$row[0]);
}
$result->free();
}
if($mysqli->more_results())
{
print("-------------------------------");
}
}while($mysql->next_result());
}
$mysqli->close();
?>
It doesnt work.. it doesnt go to the first if condition that identifies if it is a multiquery..
I have other question, ..why are multi_query() is useful..,
UPDATE:
Strict Standards: mysqli::next_result() [mysqli.next-result]: There is
no next result set. Please, call
mysqli_more_results()/mysqli::more_results() to check whether to call
this function/method in C:\xampp\htdocs\PoliticalForum2\test.php on
line 42
SOLVED:
<?php
$mysqli=mysqli_connect("localhost","root","","politicalforum");
$query="SELECT query_title FROM administrator;";
$query.="SELECT thread_id FROM threads;";
if($mysqli->multi_query($query))
{
do
{
if($result=$mysqli->store_result())
{
while($row=$result->fetch_row())
{
printf("%s<br/>",$row[0]);
}
$result->free();
}
if($mysqli->more_results())
{
print("-------------------------------<br/>");
}
else
{
echo '<br/>';
}
}while($mysqli->more_results() && $mysqli->next_result());
}
$mysqli->close();
?>
You need a semicolon at the end of the first query.
$query="SELECT query_title FROM administrator;";
$query.="SELECT thread_id FROM threads";
mysqli::multi_query
The reason why you get this warning, is simply because you use a do...while loop that evaluates the condition after running the command block. So when there are no more results, the contents of the loop are ran one additional time, yielding that warning.
Using a while ($mysql->next_result())...do loop should fix this. (On a general note: Using post-test loops like you did is quite uncommon in database programming)
If code is poetry, I am trying to be Shakespeare!
You can fix it like this:
if ($res) {
do {
$mycon->next_result(); //// instead of putting it in a while, put it here
if ($result = $mycon->store_result()) {
while ($row = $result->fetch_row()) {
foreach ($row as $cell)
$flag = $cell;
}
///$result->close();
}
$sale=$sale+1;
} while ($sale > 2);
}
I got the answer for the same.
please find my function below.
public function executeStoredProcedureMulti($strQuery)
{
$yml = sfYaml::load(sfConfig::get('sf_config_dir').'/databases.yml');
$params = $yml['all']['doctrine']['param'];
$dsnName = $params['dsn'];
$arrDsn = explode(";",$dsnName);
$hostName = explode("=",$arrDsn[0])[1];
$schemaName = explode("=",$arrDsn[1])[1];
$this->dbconn = mysqli_connect($hostName, $params['username'], $params['password'], $schemaName);
//return if connection was created successfully
if($this->dbconn)
{
mysqli_set_charset($this->dbconn,"utf8");
//return true;
}
else
{
$this->nErrorNumber = mysqli_connect_errno();
$this->strErrorDesc = mysqli_connect_error();
return false;
}
//check if connection exists
if($this->dbconn)
{
/* close connection */
//execute the query
if($this->dbconn->multi_query($strQuery))
{
//create table array in dataset object
$dataSet = array();
do {
//store first result set
if ($result = $this->dbconn->store_result())
{
//create data table passing it the column data
$dataTable = new CDataTable($result->fetch_fields());
//parse through each row
while ($row = $result->fetch_row())
{
$dataTable->AddRow($row);
}
$result->free();
$dataSet[] = $dataTable;
}
if (!$this->dbconn->more_results()) {
break;
}
} while ($this->dbconn->next_result());
$this->dbconn->close();
//return the complete dataset
return $dataSet;
}
else//save the error to member variables
{
$this->nErrorNumber = $this->dbconn->errno;
$this->strErrorDesc = $this->dbconn->error;
}
}
return false;
}
This is working Need to create a Class CTableData. Please make one and it will work great
.
I'm getting following error message.
Notice: Trying to get property of non-object in
C:\xampp\htdocs\my\include\user_functions.php on line 34
Here is my Code
$conn = db_connection();
if($conn == false) {
user_error('Unable to connect to database');
return false;
}
$query = "UPDATE user SET passwd = '".$new_passwd."'
WHERE username = '".$username."' ";
$result=$conn->query($query);
if($result == false) {
user_error('Query Error'.$conn->error);
return false;
}
if($result->num_rows == 1) {
echo 'Password changed';
} else {
echo 'Failed ';
}
here is my db_connection
function db_connection() {
$db = new mysqli('localhost','root','','php_login');
if(!$db) {
echo 'Could not connect to database server';
} else {
return $db;
}
}
The UPDATE statement doesn't return a result set. What are you trying to get from fetch_array?
UPDATE
class mysqli{
public $aff_num_rows;
//some properties
//some properties
//some methods
//some methods
public function query($sql)
{
$resultset = mysql_query($sql); //after query instantiate the $aff_numrows
//property with function
$this->aff_num_rows = mysql_affected_rows(); //guess you are using sqlite
//so you might have different function
//and you can use this property
}
}
And in you code you have
if($conn->aff_num_rows == 1) {
echo 'password changed';
} else {
echo 'error changing pasword';
}