PHP - Mysql Unique Key Error
I have a mysql unique index on two columns:
UNIQUE KEY `page_id` (`page_id`,`tag_id`) I have a mysql query like this: Code: [Select] mysql_query("insert into link_tags (page_id, tag_id) values ($page_id, $tag_id)"); If I run that, what would be the best way for php not to fail if the key already exists? within a while loop, would this be best? Code: [Select] if(mysql_query("insert into link_tags (page_id, tag_id) values ($page_id, $tag_id)")) continue; Or would the code above (first code) be sufficient enough? Similar TutorialsI have a mysql table which will store users email addresses (each is unique and is the primary field) and a timestamp. I have added another column called `'unique_code' (varchar(64), utf8_unicode_ci)`. What I would very much appreciate assistance with is; a) Generating a 5 digit alphanumeric code, ie: 5ABH6 b) Check all rows the 'unique_code' column to ensure it is unique, otherwise re-generate and check again c) Insert the uniquely generated 5 digit alphanumeric code into `'unique_code'` column, corresponding to the email address just entered. d) display the code on screen. What code must I put and where? **My current php is as follows:** Code: [Select] require "includes/connect.php"; $msg = ''; if($_POST['email']){ // Requested with AJAX: $ajax = ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'); try{ if(!filter_input(INPUT_POST,'email',FILTER_VALIDATE_EMAIL)){ throw new Exception('Invalid Email!'); } $mysqli->query("INSERT INTO coming_soon_emails SET email='".$mysqli->real_escape_string($_POST['email'])."'"); if($mysqli->affected_rows != 1){ throw new Exception('You are already on the notification list.'); } if($ajax){ die('{"status":1}'); } $msg = "Thank you!"; } catch (Exception $e){ if($ajax){ die(json_encode(array('error'=>$e->getMessage()))); } $msg = $e->getMessage(); } } Hi, First off: I got a table with two columns and 100.000 rows. Some of the rows are duplicates (allowing me to "weight" the chance of some rows being hit the first time the script runs) Allright. This i what I want to do: When the user clicks a button: 1. Generate a random selected row from the table (this I allready accomplished using this code: Code: [Select] <?php //CODE FROM WWW.GREGGDEV.COM function random_row($table, $column) { $max_sql = "SELECT max(" . $column . ") AS max_id FROM " . $table; $max_row = mysql_fetch_array(mysql_query($max_sql)); $random_number = mt_rand(1, $max_row['max_id']); $random_sql = "SELECT * FROM " . $table . " WHERE " . $column . " >= " . $random_number . " ORDER BY " . $column . " ASC LIMIT 1"; $random_row = mysql_fetch_row(mysql_query($random_sql)); if (!is_array($random_row)) { $random_sql = "SELECT * FROM " . $table . " WHERE " . $column . " < " . $random_number . " ORDER BY " . $column . " DESC LIMIT 1"; $random_row = mysql_fetch_row(mysql_query($random_sql)); } return $random_row; } //USAGE $randomdata = random_row('MYTABLE', 'MYCOLUMN'); echo $randomdata[2]; // Where [2] is the data I want to extract. ?> This script works fine. The problem is that I want to exclude the results that have allready been shown. With me? Therefore, since I have duplicate rows of certain data, I need to exclude all the rows that are the same. I have a couple of solutions, but I can't seem to fit it into this script. (I will not use the ORDER_BY_RAND() query; it'll be too slow for a table with 100.000 rows) SO: Here's ideas I've come up with that might work, but because of my limited experience with PHP and MySQL, haven't been able to accomplish. 1) Insert a "temporary" column in the table which is filled with 1 and 0's where 1 indicates that the row has allready been taken? (If possible) 2) Use PHP sessions to store the previously generated rows? 3) Create a temporary table, which fills up with the allready generated rows by the random script? 4) Create a unique txt-file (e.g: _USERSIPADRESS__.txt) which can be used to save and extract data from the random script? (fopen, fwrite and so fourth) I hope you understand what I'm trying to do Any suggestions would be highly appreciated. Thank you. Hello guys, How do I total unique id's with php or MySQL. For instance in MySQL I have... ID 1 1 3 4 2 1 1 3 How can I total all of the 1's, all of the twos, all of the threes and so forth. I have four 1's, one 2, two 3's and so forth... I am trying to write a script that runs through a CSV file and inserts unique values in a mysql database and spits the duplicate out into a new CSV. I can find the duplicates when I load it into an array, but when I insert them into a MySQL database, I cannot determine if they are duplicates. If I use INSERT IGNORE, it will run the whole file, and reject the duplicates. This is fine, except I need to create a file of the duplicate entries. What is the best way to determine if the insert attempt was rejected? I could do a select to see if the row is there, spit it out...insert if not, but I was thinking there should be a way for MySQL to talk back to me to cut the queries in half... Any ideas? Thanks Solution: Turns out the headers will not send unless all of the other code is behind an else userinfo.php?user=MikeH, possible addition to the sticked post? So strictly speaking I dont have a header error because my script does not produce errors. However my script should be redirecting me to "notes.php?error=ad" but instead it just sends me back to the page I was previously at. My script is made to process a download via "tokens" and then redirect the user. That all works fine but what I am trying to do now is check if the user has already about the download and if they have redirect them to the error page letting them know. So in short the URL goes like this: notes.php?viewn=2 -> purchase.php?user=MikeH&nid=2 (unseen page all processing) -> notes.php?error=ad however what it is doing is: notes.php?viewn=2 -> purchase.php?user=MikeH&nid=2 (unseen page all processing) -> notes.php?viewn=2 Here is the notes code: <?php }else if (isset($_GET['viewn'])){ $cid = $_GET['viewn']; $query = "SELECT * FROM approvednotes WHERE cid =".$cid; $res = mysql_query($query) or die (mysql_error()); $i=0; $r=1; ?> <h2>Programs:</h2> <table summary="Summary Here" cellpadding="0" cellspacing="0"> <tr> <td><b>File Name</b></td> <td><b>Author</b></td> <td><b>Cost</b></td> <td><b>Buy</b></td> </tr> <?php echo "<tbody>"; echo "<tr class= \"dark\">"; while ($row = mysql_fetch_array($res)){ if($i == 1){ echo "</tr>"; $r++; if($r% 1 == 0){ echo "<tr class = \"light\">"; $i=0; $r = 0; }else{ echo "<tr class = \"dark\">"; $i=0; } } echo "<td> ". $row['name']."</td><td>".$row['username']."</td><td>".$row['value']." <img src=\"images/money.png \" height=\"30px\" /></td><td><a href=\"purchase.php?user=".$session->username."&nid=".$row['id']."\"><img src=\"images/buy.png\" height=\"30px\"/></a></td>"; $i++; } echo "</table>"; }?> Here is the purchase code: <?php include("include/session.php"); if($session->checkLogin()){ $user= $_GET['user']; if ($user == $session->username){ $note = $_GET['nid']; $query3 = "SELECT * FROM users_downloaded WHERE nid=$note AND username='$user'"; $res3 = mysql_query($query3) or die (mysql_error()); $pass = mysql_num_rows($res3); if ($pass != 0){ header("Location: notess.php?error=ad"); } $nquery = "SELECT * FROM approvednotes WHERE id= ".$note; $nres = mysql_query($nquery) or die (mysql_error()); //Get info about the file while ($nrow = mysql_fetch_assoc($nres)){ $price = $nrow['value'] ; $location = $nrow['location']; } //see if user even has enough credits for this function creditcheck($username){ $usern= $_GET['user']; $query = "SELECT * FROM users WHERE username = '".$usern."'"; $res = mysql_query($query) or die(mysql_error()); while ($row = mysql_fetch_array($res)){ $credits = $row['credits']; } return $credits; } $credits = creditcheck($user); if($credits >= $price){ //user has enough credits to purchase note. $newamount = $credits - $price; $person = $session->username; $query = "UPDATE users SET credits =".$newamount." WHERE username='$person'"; $res = mysql_query($query) or die (mysql_error()); $query2 = "INSERT INTO users_downloaded (nid, username) VALUES ('$note','$person')"; $res2 = mysql_query($query2) or die (mysql_error()); header("Location: download.php?f=".$location); exit; }else{ //error not enough money!! header("Location: notes.php?error=ne"); } } }else{ header ("Location: notes.php?error=nl"); } ?> I've started a to-do app, and everything works fine. Every user has his own unique to-do items that he can add. The only issue is that when I log-in with a user, ALL the items of all users are displayed when I'm redirect to my main page. I want to make it as so every user has his own page where only the to-do items he has created are visible, not every item from every user. I'm a total beginner with PHP so I'm sorry if this is a stupid question. This is my todomain.php code <?php require 'db_conn.php'; require 'config.php'; session_start(); // If the session variable is empty, this // means the user is yet to login // User will be sent to 'login.php' page // to allow the user to login if (!isset($_SESSION['id'])) { $_SESSION['msg'] = "You have to log in first"; header('location: login.php'); } // Logout button will destroy the session, and // will unset the session variables // User will be headed to 'login.php' // after loggin out if (isset($_GET['logout'])) { session_destroy(); unset($_SESSION['id']); header("location: login.php"); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset= "UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <link rel="stylesheet" href="css/bootstrap-grid.min.css"> <link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="style.css"> <a href="index.php?logout='1'" style="color: black;"> Click here to Logout </a> <?php if (isset($_SESSION['success'])) : ?> <div class="error success" > <h3> <?php echo $_SESSION['success']; unset($_SESSION['success']); echo $_SESSION["username"] ?> </h3> </div> <?php endif ?> <title>TODO App</title> <script src="https://kit.fontawesome.com/d72928d9b9.js" crossorigin="anonymous"></script> </head> <body> <div class="container m-5 p-2 rounded mx-auto bg-light shadow"> <!-- App title section --> <div class="row m-1 p-4"> <div class="col"> <div class="p-1 h1 text-primary text-center mx-auto display-inline-block"> <i class="fa fa-check bg-primary text-white rounded p-2"></i> <u>My Todo-s</u> </div> </div> </div> <!-- Create todo section --> <form action="app/add.php" method="POST" autocomplete="off"> <div class="row m-1 p-3"> <div class="col col-11 mx-auto"> <div class="row bg-white rounded shadow-sm p-2 add-todo-wrapper align-items-center justify-content-center"> <div class="col"> <input class="form-control form-control-lg border-0 add-todo-input bg-transparent rounded" type="text" name="title" placeholder="Add new .."> </div> <div class="col-auto m-0 px-2 d-flex align-items-center"> <label class="text-secondary my-2 p-0 px-1 view-opt-label due-date-label d-none">Due date not set</label> <i class="fa fa-calendar my-2 px-1 text-primary btn due-date-button" data-toggle="tooltip" data-placement="bottom" title="Set a Due date"></i> <i class="fa fa-calendar-times-o my-2 px-1 text-danger btn clear-due-date-button d-none" data-toggle="tooltip" data-placement="bottom" title="Clear Due date"></i> </div> <div class="col-auto px-0 mx-0 mr-2"> <button type="submit" class="btn btn-primary">Add</button> </div> </div> </div> </div> </form> <?php $todos=$conn->query("SELECT * FROM todos ORDER BY id ASC"); ?> <div class="row mx-1 px-5 pb-3 w-80"> <div class="col mx-auto"> <?php while($todo=$todos->fetch(PDO::FETCH_ASSOC)){ ?> <!-- Todo Item 1 --> <div class="row px-3 align-items-center todo-item rounded"> <?php if($todo['checked']){ ?> <input type="checkbox" class="check-box" data-todo-id="<?php echo $todo['id'];?>" checked /> <h2 class="checked"><?php echo $todo['title'] ?> </h2> <div class="col-auto m-1 p-0 todo-actions"> <div class="row d-flex align-items-center justify-content-end"> </div> </div> <?php } else{ ?> <input type="checkbox" class="check-box" data-todo-id="<?php echo $todo['id'];?>"/> <h2><?php echo $todo['title'] ?></h2> <?php } ?> <div class="col-auto m-1 p-0 d-flex align-items-center"> <h2 class="m-0 p-0"> <i class="fa fa-square-o text-primary btn m-0 p-0 d-none" data-toggle="tooltip" data-placement="bottom" title="Mark as complete"></i> </h2> </div> <div class="col-auto m-1 p-0 todo-actions"> <div class="row d-flex align-items-center justify-content-end"> <h5 class="m-0 p-0 px-2"> <i class="fa fa-pencil text-info btn m-0 p-0" data-toggle="tooltip" data-placement="bottom" title="Edit todo"></i> </h5> <h5 class="m-0 p-0 px-2"> <i class="remove-to-do fa fa-trash-o text-danger btn m-0 p-0" data-toggle="tooltip" data-placement="bottom" title="Delete todo" id="<?php echo $todo['id']; ?>"></i> </h5> </div> <div class="row todo-created-info"> <div class="col-auto d-flex align-items-center pr-2"> <i class="fa fa-info-circle my-2 px-2 text-black-50 btn" data-toggle="tooltip" data-placement="bottom" title="" data-original-title="Created date"></i> <label class="date-label my-2 text-black-50"><?php echo $todo['date_time'] ?></label> </div> </div> </div> </div> <?php } ?> </div> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script> <script src="js/bootstrap.bundle.min.js"></script> <script src="js/myjs.js" ></script> <script src="js/jquery-3.3.1.min.js"></script> <script> $(document).ready(function(){ $(".remove-to-do").click(function(e){ const id = $(this).attr('id'); $.post('app/remove.php', { id: id }, (data) => { if(data){ $(this).parent().parent().parent().parent().hide(300); } } ); }); $(".check-box").click(function(e){ const id = $(this).attr('data-todo-id'); $.post('app/checking.php', { id: id }, (data) => { if(data!='error'){ const h2= $(this).next(); if(data === '1'){ h2.removeClass('checked'); }else{ h2.addclass('checked'); } } } ); }); }); </script> </body> </html>
I spent several hours trying to figure this thing out. Thought I had it nailed, but still getting duplicate record entries into the MySQL DB when I do NOT want them.
Here's the plot:
People filling out the possible attendance form for a Ham Radio event *sometimes* bring a 2nd person (either a spouse or a friend). The 2nd person may, or may not, also has a Callsign which I need to put INSERT the same MySQL Callsign column. In any event, to also identify the 2nd person as coming 'with' the 1st person.
MOST of the attendees are individuals with NO 2nd person.
My entry form has these primary fields:
callsign
fullname
AND...
callsign2
fullname2
What I came up with was to process the MySQL INSERT for the primary callsign & fullname into their respective MySQL DB Columns (which works fine), and then........... immediately following the main Query INSERT, to do a substitution type thing depending on whether or not a form entry was made in the callsign2 field, AND/OR, the fullname2 field.
This partially works, but if there is ONLY a primary callsign and fullname in the form, I'm still getting a duplicate record entry which includes the callsign in the `with` column (which should ONLY take place IF there is a 2nd person indicated).
Confusing?
Here is what I have been wrestling with to try and accomplish the objective, and now my eyes are glazed over ;-(
// TRICKY PART HERE // If a 2nd Callsign AND a Fullname if ($callsign2 != ' ' && $fullname2 != ' ') { // Still make reference to the primary Callsign in the MySQL DB `with` column $with = $callsign; // Assignment to allow 2nd Callsign to be entered in the MySQL `callsign` column $callsign=$callsign2; $fullname=$fullname2; $sql="INSERT INTO `mytable` (`callsign`, `fullname`, `with`) VALUES ('$callsign', '$fullname', '$with')"; // If NO 2nd Callsign BUT a Fullname } elseif ($callsign2 = ' ' && $fullname2 != ' ') { // Make reference to the primary Callsign in the MySQL DB `with` column $with = $callsign; $callsign=$callsign2; $fullname=$fullname2; $sql="INSERT INTO `mytable` (`callsign`, `fullname`, `with`) VALUES ('$callsign', '$fullname', '$with')"; } else { // The only thing I could thing of to (hopefully) NOT make a 2nd entry // record in the MySQL DB IF there is NO 2nd person referenced $with = $callsign; } if (!mysqli_query($con,$sql)) { die('Error: ' . mysqli_error($con)); }This mostly works EXCEPT if only a single (primary) person entry. The recap the objetives: 1. If ONLY a primary/single person entry on the form: * callsign & fullname get INSERTed into the `callsign` and `fullname` columns in the DB as ONLY one record entry 2. If BOTH a primary and 2nd person on the form: A. IF the 2nd person has a Callsign, then the 2nd record entry would be: * callsign2 & fullname2 get INSERTed into the `callsign` & `fullname` columns in the 2nd DB as a separate record entry * callsign of the primary person also gets INSERTED into the `with` column in the same 2nd DB record entry B. IF the 2nd person does NOT have a callsign, then the 2nd record entry would be: * fullname2 gets INSERTed into the `fullname` column in the DB as a separate 2nd DB record entry * callsign of the primary person also gets INSERTED into the `with` column in the same 2nd DB record entry I obvioiusly have overlooked something, but just can't seem to figure it out at this point {SIGH}. Thanks for any enlightenment. -FreakingOUT I have a form that passes multiple images and I wanted them to have a substring of a md5 encrypted time for generating unique codes so I don't delete or overwrite an older file. I keep the actual images in a folder and the path in mysql. The folder is working perfectly and there are no problems generating unique codes but I have been trying all night and I can't figure out why mysql won't update. I can actually get it to update but then I loose the functionallity of the code and if I don't upload a 4 images and leave one blank, the blank one deletes the previously uploaded field in the table row. Here is the md5 encrypted time for generating unique codes: Code: [Select] $unique = strtolower(substr(md5(time()), 0, 4)); This is how it works with the folder: Code: [Select] $filePath = $uploadDir . $unique . $fileName; This is how I get it to update mysql but then loose functionality: Code: [Select] $values[$i] = $unique . mysql_real_escape_string(basename(trim($_FILES[$fields[$i]]['name']))); Here is the entire code: Code: [Select] <?php require_once('storescripts/connect.php'); mysql_select_db($database_phpimage,$phpimage); $unique = strtolower(substr(md5(time()), 0, 4)); $uploadDir = 'upload/'; if(isset($_POST['upload' . $config])) { foreach ($_FILES as $file) { $fileName = $file['name']; $tmpName = $file['tmp_name']; $fileSize = $file['size']; $fileType = $file['type']; if($fileName==""){ $filePath = 'upload/'; } else{ $filePath = $uploadDir . $unique . $fileName; } $filePath = str_replace(" ", "_", $filePath); $result = move_uploaded_file($tmpName, $filePath); if(!get_magic_quotes_gpc()) { $fileName = addslashes($fileName); $filePath = addslashes($filePath); } $fileinsert[]=$filePath; } } $mid = mysql_real_escape_string(trim($_POST['mid'])); $cat = mysql_real_escape_string(trim($_POST['cat'])); $item = mysql_real_escape_string(trim($_POST['item'])); $price = mysql_real_escape_string(trim($_POST['price'])); $about = mysql_real_escape_string(trim($_POST['about'])); $fields = array(); $values = array(); $updateVals = array(); for($i=1; $i<=4; $i++) { $fields[$i] = 'name'.$i; $values[$i] = mysql_real_escape_string(basename(trim($_FILES[$fields[$i]]['name']))); if($values[$i] != '') { $updateVals[] = "{$fields[$i]} = '{$values[$i]}'"; } } $updateNames = ''; if(count($updateVals)) { $updateNames = ", " . implode(', ', $updateVals); } $update = "INSERT INTO image (mid, cid, item, price, about, name1, name2, name3, name4) VALUES ('$mid', '$cat', '$item', '$price', '$about', '$values[1]', '$values[2]', '$values[3]', '$values[4]') ON DUPLICATE KEY UPDATE cid = '$cat', item = '$item', price = '$price', about = '$about' $updateNames"; $result = mysql_query($update) or die (mysql_error()); $id = mysql_insert_id(); ?> <p style="font-size:35px; font-family:Arial, Helvetica, sans-serif; color:#255E67; margin-left:25px;">Your Item Has Been Uploaded!</p> <script type="text/javascript"> setTimeout('ourRedirect()', 2000) function ourRedirect() { location.href='protator_php.php?mid=<?php echo $id ?>' } </script> Hello, I need some help. Say that I have a list in my MySQL database that contains elements "A", "S", "C", "D" etc... Now, I want to generate an html table where these elements should be distributed in a random and unique way while leaving some entries of the table empty, see the picture below. But, I have no clue how to do this... Any hints? Thanks in advance, Vero I have been pulling my hair out for the lasy 3 hours i am trying to update a MySql table but i cant get it too work, i just keep getting MySql error #1064 - You have an error in your SQL syntax; if i just update 1 field it works fine but if i try to update more than 1 field it dosent work, Help Please! <?php $root = $_SERVER['DOCUMENT_ROOT']; require("$root/include/mysqldb.php"); require("$root/include/incpost.php"); $con = mysql_connect("$dbhost","$dbuser","$dbpass"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("$dbame", $con); mysql_query("UPDATE Reg_Profile_p SET build='$build' col='$col' size='$size' WHERE uin = '$uinco'"); ?> does anyone know who to resolve this issue of importing a CSV file from excel into sql? I get this error when I do. LOAD DATA LOCAL INFILE '/tmp/phpq2aAbU' INTO TABLE `Events` FIELDS TERMINATED BY ',' ENCLOSED BY '\\"' ESCAPED BY '\\\\' LINES TERMINATED BY '\r\n' 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 'Number LIKE '%TEST%' OR Name LIKE '%TEST%'' at line 1 Is the error message i get... Here is my code... <?php $search=$_POST['searchform']; if(!$search) die('Please enter a search'); //connect to the database $db=mysql_connect ("xxxxxx", "xxxx", "xxxx") or die ('I cannot connect to the database because: ' . mysql_error()); //-select the database to use $mydb=mysql_select_db("wadkin"); //-query the database table $sql="SELECT ID, Stock Number, Name FROM Contacts WHERE Stock Number LIKE '%" . $search . "%' OR Name LIKE '%" . $search ."%'"; //-run the query against the mysql query function $result=mysql_query($sql) or die (mysql_error()); //-create while loop and loop through result set while($row=mysql_fetch_array($result)){ $Stock =$row['Stock Number']; $Name=$row['Name']; $ID=$row['ID']; //-display the result of the array echo "<ul>\n"; echo "<li>" . "<a href=\"search.php?id=$ID\">" .$Stock . " " . $Name . "</a></li>\n"; echo "</ul>"; } ?> Can someone correct for me please????!!!!! I am getting this error: Warning: mysql_fetch_row(): supplied argument is not a valid MySQL result resource in /home/content/20/8917120/html/goldenfruit/test.php on line 11 for this code: <?php $connect = mysql_connect('DB credentials removed'); if (!$connect) { die('Could not connect: ' .mysql_error()); } $data = mysql_query("SELECT * FROM fruits"); $row = mysql_fetch_row($data); echo $row[0]; echo hello; ?> I cannot seem to find the error in this. Can anyone help? I dont know whats wrong Error: Code: [Select] 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 '::1, 3, , now())' at line 1 Error Line: mysql_query('INSERT INTO `'. $db .'`.`votes` (`ip`, `serverId`, `ownerId`, `date`) VALUES ('. $ip .', '. $serverId .', '. $ownerId .', now())') or die(mysql_error()); Hi guys, I'm having a really frustrating problem with some PHP and MySQL. I've tested the MySQL in PHPMyAdmin and it runs fine, which is why I've posted this in PHP problems. All I want to do is copy one table to another (dropping the other first) as a backup, then recreate the original table but blank. I've tried running the functions in PHPMyAdmin, which works. Then I used its "Create PHP Code" function to make the PHP, which I edited to remove line breaks etc. Even if I used the unedited PHP made by PHPMyAdmin, it still doesn't work! The error is always a syntax one: "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 'CREATE TABLE mobackup (campaign_id varchar(20) NOT NULL, number varchar(13) NOT ' at line 1" Here's the code: Code: [Select] <?php $connection = mysql_connect(connection details hidden for security purposes, but they definitely work); mysql_select_db("betfredpiri", $connection); $sql = "DROP TABLE IF EXISTS mobackup; CREATE TABLE mobackup (campaign_id varchar(20) NOT NULL, number varchar(13) NOT NULL, message varchar(160) NOT NULL, mo_id int(15) NOT NULL, shortcode int(7) NOT NULL, received_time varchar(20) NOT NULL, network varchar(15) NOT NULL, retry tinyint(1) NOT NULL, FULLTEXT KEY message (message)) ENGINE = MyISAM DEFAULT CHARSET = latin1; INSERT INTO mobackup SELECT * FROM mo; DROP TABLE IF EXISTS mo; CREATE TABLE mo (campaign_id varchar(20) NOT NULL, number varchar(13) NOT NULL, message varchar(160) NOT NULL, mo_id int(15) NOT NULL, shortcode int(7) NOT NULL, received_time varchar(20) NOT NULL, network varchar(15) NOT NULL, retry tinyint(1) NOT NULL, FULLTEXT KEY message (message)) ENGINE = MyISAM DEFAULT CHARSET = latin1;"; mysql_query(mysql_real_escape_string($sql)); ?> I've also tried it with the following statements: Code: [Select] <?php $sql2 = "DROP TABLE IF EXISTS mobackup;" ."CREATE TABLE mobackup (campaign_id varchar(20) NOT NULL, " ."number varchar(13) NOT NULL, " ."message varchar(160) NOT NULL, " ."mo_id int( 15 ) NOT NULL, " ."shortcode int(7) NOT NULL, " ."received_time varchar(20) NOT NULL, " ."network varchar(15) NOT NULL, " ."retry tinyint(1) NOT NULL, " ."FULLTEXT KEY message (message) ) ENGINE = MyISAM DEFAULT CHARSET = latin1;" ."INSERT INTO mobackup SELECT * FROM mo;" ."DROP TABLE IF EXISTS mo;" ."CREATE TABLE mo (campaign_id varchar(20) NOT NULL, " ."number varchar(13) NOT NULL, " ."message varchar(160) NOT NULL, " ."mo_id int(15) NOT NULL, " ."shortcode int(7) NOT NULL, " ."received_time varchar(20) NOT NULL, " ."network varchar(15) NOT NULL, " ."retry tinyint(1) NOT NULL, " ."FULLTEXT KEY message (message)) ENGINE = MyISAM DEFAULT CHARSET = latin1;"; ?>and Code: [Select] <?php $sql3 = "\n" . "DROP TABLE IF EXISTS `betfredpiri`.`mobackup`;\n" . " CREATE TABLE `betfredpiri`.`mobackup` ( `campaign_id` varchar( 20 ) NOT NULL ,\n" . " `number` varchar( 13 ) NOT NULL ,\n" . " `message` varchar( 160 ) NOT NULL ,\n" . " `mo_id` int( 15 ) NOT NULL ,\n" . " `shortcode` int( 7 ) NOT NULL ,\n" . " `received_time` varchar( 20 ) NOT NULL ,\n" . " `network` varchar( 15 ) NOT NULL ,\n" . " `retry` tinyint( 1 ) NOT NULL ,\n" . " FULLTEXT KEY `message` ( `message` ) ) ENGINE = MyISAM DEFAULT CHARSET = latin1;\n" . "\n" . "INSERT INTO `betfredpiri`.`mobackup` SELECT * FROM `betfredpiri`.`mo`;" . "DROP TABLE IF EXISTS `betfredpiri`.`mo`;\n" . " CREATE TABLE `betfredpiri`.`mo` ( `campaign_id` varchar( 20 ) NOT NULL ,\n" . " `number` varchar( 13 ) NOT NULL ,\n" . " `message` varchar( 160 ) NOT NULL ,\n" . " `mo_id` int( 15 ) NOT NULL ,\n" . " `shortcode` int( 7 ) NOT NULL ,\n" . " `received_time` varchar( 20 ) NOT NULL ,\n" . " `network` varchar( 15 ) NOT NULL ,\n" . " `retry` tinyint( 1 ) NOT NULL ,\n" . " FULLTEXT KEY `message` ( `message` ) ) ENGINE = MyISAM DEFAULT CHARSET = latin1;\n"; ?> Both adaptations of PHPMyAdmin's export to a PHP statement. Any ideas would be most welcome! I'm tearing my hair out over this. Jamie hey guys; Another problem with sql. Code: [Select] { echo "Welcome " . $row['username']; echo "<br />"; echo "<br />"; echo "<br />"; $msgquery = "SELECT * FROM spotty_messages WHERE (id_receiver = '" . $userid . "') AND message_read = '0'"; $messageres = mysql_query($msgquery); $messrow = mysql_fetch_array($messageres); $messagenum = mysql_num_rows($messageres); } $i = 0; while ($i < $messagenum) { $f1 = "From:" . mysql_result($messrow,$i,"sender"); echo " <tr> <td>" . $f1 ."</font></td> " ; $i++; } This is returning the error : Warning: mysql_result() expects parameter 1 to be resource, null given in /customers/klueless.net/klueless.net/httpd.www/daisysite/messages.php on line 106 Please help, thanks! Code: [Select] $con=mysql_connect("****","****","****"); mysql_select_db("****"); $queryuser=mysql_query("SELECT * FROM users WHERE name='$name'"); $checkuser=mysql_num_rows($queryuser); if($checkuser != 0) { $error = $name." is already in the database. <br /> <a href='****'>Return</a>"; $errortype = "1";} else { /* Now we will write a query to insert user details into database */ $insert = mysql_query("INSERT INTO users (name, group, sex, grouprank) VALUES ('$name', '$group', '$sex', '$grouprank')"); if($insert) { $error = $name. "Was successfully added to the database. <br /> <a href='****'>Return</a>"; $errortype = "0";} else { $error = "Error in registration: ".mysql_error(); $errortype = "1";} /* closing the if else statements */ } echo $error; ?>Error: Code: [Select] Error in registration: 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 'group, sex, grouprank) VALUES ('ljkh', 'lnkb', 'female', 'lkjh')' at line 1 Please help. THanks Hi I am trying to figure out with this example i saw online does not work...I am building a database to store user and password and i keep getting an error "undefined index username" i need it to pull the username from mysql database so how do i do this??? mysql_connect("host", "username", "pw") or die (mysql_error()); mysql_select_db('username') or die (mysql_error()); if(mysql_num_rows(mysql_query("SELECT * from users WHERE username='" . $_POST['username'] . "'")) == 1) ( this is the error line) now I have the actual host username and pw in my file i just took it off for my security lol. |